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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e8914a3392df58f88fa9b5f656406289565e0751 | 29,360,396,449,153 | 22698385e69bbfb11b385330b418f720838370a0 | /app/src/main/java/ar/gov/mendoza/PrometeoMuni/ListGenericActivity.java | 75481bc9124a98195dd77d05833b4bb5a9c66ad2 | []
| no_license | sycsa/PrometeoMunicipal | https://github.com/sycsa/PrometeoMunicipal | bc52a9b2de8452d0e146b240f1da86c35b1fe232 | 2b427b374ceea32ee7f388d989409f48566ff793 | refs/heads/main | 2023-06-08T10:21:43.862000 | 2021-06-28T18:04:23 | 2021-06-28T18:04:23 | 381,116,333 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ar.gov.mendoza.PrometeoMuni;
import android.os.Bundle;
import ar.gov.mendoza.PrometeoMuni.ui.base.BaseLoaderActivity;
public class ListGenericActivity extends BaseLoaderActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_generic);
}
}
| UTF-8 | Java | 357 | java | ListGenericActivity.java | Java | []
| null | []
| package ar.gov.mendoza.PrometeoMuni;
import android.os.Bundle;
import ar.gov.mendoza.PrometeoMuni.ui.base.BaseLoaderActivity;
public class ListGenericActivity extends BaseLoaderActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_generic);
}
}
| 357 | 0.798319 | 0.798319 | 18 | 18.833334 | 23.322021 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 0 |
0eff892efa8b9380b4814e5ad4d4aa44b9b0cdb7 | 2,705,829,410,979 | 91f46eaae8479fbf2d1b7213c1a13b9a1dbe8dbc | /src/main/java/pl/michal/olszewski/zadania/zad18_19/CriteriaQueryTasks.java | f07936530b269ff425ec04dee4704d30419941c3 | []
| no_license | olszewskimichal/sda-jpa | https://github.com/olszewskimichal/sda-jpa | d115cf9d3933af0cafb336309c4f67efa5a3edeb | d789e8030e77d4266cd4aa7104ffea44a037b1eb | refs/heads/master | 2020-05-03T00:05:51.814000 | 2019-04-22T18:45:53 | 2019-04-22T18:45:53 | 178,300,191 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.michal.olszewski.zadania.zad18_19;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pl.michal.olszewski.materialy.Employee;
import pl.michal.olszewski.materialy.EntityManagerSingleton;
public class CriteriaQueryTasks {
public static void main(String[] args) {
}
List<Employee> findAllEmployeesByName(String name) {
EntityManager entityManager = EntityManagerSingleton.INSTANCE.getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> from = query.from(Employee.class);
query.select(from)
.where(
criteriaBuilder.equal(from.get("name"), name)
);
TypedQuery<Employee> tq = entityManager.createQuery(query);
return tq.getResultList();
}
List<Employee> findAllEmployeesWithSalaryBiggerThan(Long salary) {
EntityManager entityManager = EntityManagerSingleton.INSTANCE.getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> from = query.from(Employee.class);
query.select(from)
.where(
criteriaBuilder.greaterThan(from.get("salary"), salary)
);
TypedQuery<Employee> tq = entityManager.createQuery(query);
return tq.getResultList();
}
}
| UTF-8 | Java | 1,621 | java | CriteriaQueryTasks.java | Java | []
| null | []
| package pl.michal.olszewski.zadania.zad18_19;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pl.michal.olszewski.materialy.Employee;
import pl.michal.olszewski.materialy.EntityManagerSingleton;
public class CriteriaQueryTasks {
public static void main(String[] args) {
}
List<Employee> findAllEmployeesByName(String name) {
EntityManager entityManager = EntityManagerSingleton.INSTANCE.getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> from = query.from(Employee.class);
query.select(from)
.where(
criteriaBuilder.equal(from.get("name"), name)
);
TypedQuery<Employee> tq = entityManager.createQuery(query);
return tq.getResultList();
}
List<Employee> findAllEmployeesWithSalaryBiggerThan(Long salary) {
EntityManager entityManager = EntityManagerSingleton.INSTANCE.getEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class);
Root<Employee> from = query.from(Employee.class);
query.select(from)
.where(
criteriaBuilder.greaterThan(from.get("salary"), salary)
);
TypedQuery<Employee> tq = entityManager.createQuery(query);
return tq.getResultList();
}
}
| 1,621 | 0.760025 | 0.757557 | 43 | 36.697674 | 27.491678 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.581395 | false | false | 0 |
44c09b8e377876b3a1553786b1d435b410f02a29 | 15,023,795,612,063 | 89f59253f79bc81f66dd52eb0e62e55428b36774 | /app/src/main/java/com/wildnet/widnetreusablecomponents/MainActivity.java | 303f02d8590f47ab57efea66a3a78b76c9868556 | []
| no_license | abhilucks93/WRC_IMAGE_PICKER | https://github.com/abhilucks93/WRC_IMAGE_PICKER | 34d3da28777b95cadff7744ae3501bbb6a8d7ae6 | 73047375341fc2b6e0f7f3c0ef221dcd856831a4 | refs/heads/master | 2020-04-05T12:58:57.115000 | 2017-07-04T12:12:23 | 2017-07-04T12:12:23 | 94,991,870 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wildnet.widnetreusablecomponents;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.wildnet.wrcpicker.imagePicker.listeners.OnActionCompleteListener;
import com.wildnet.wrcpicker.imagePicker.model.ImageItemBean;
import com.wildnet.wrcpicker.imagePicker.patternClasses.WrcImagePicker;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnActionCompleteListener {
Button customCamera, customGallery, defaultGallery, defaultCamera, customSingle, customMultiple;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
}
private void findViewById() {
customCamera = (Button) findViewById(R.id.bt_custom_camera);
customCamera.setOnClickListener(this);
defaultCamera = (Button) findViewById(R.id.bt_default_camera);
defaultCamera.setOnClickListener(this);
defaultGallery = (Button) findViewById(R.id.bt_default_gallery);
defaultGallery.setOnClickListener(this);
customGallery = (Button) findViewById(R.id.bt_custom_gallery);
customGallery.setOnClickListener(this);
customSingle = (Button) findViewById(R.id.bt_custom_single);
customSingle.setOnClickListener(this);
customMultiple = (Button) findViewById(R.id.bt_custom_multiple);
customMultiple.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageView);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_custom_camera:
WrcImagePicker.getInstance(this).clickImage().setCustom(true).build(this);
break;
case R.id.bt_default_camera:
WrcImagePicker.getInstance(this).clickImage().build(this);
break;
case R.id.bt_default_gallery:
WrcImagePicker.getInstance(this).pickImage().build(new OnActionCompleteListener() {
@Override
public void _actionCompleted(List<ImageItemBean> items) {
}
});
break;
case R.id.bt_custom_gallery:
WrcImagePicker.getInstance(this).pickImage().setCustom(true).build(this);
break;
case R.id.bt_custom_single:
WrcImagePicker.getInstance(this).customPick().singleMode().build(this);
break;
case R.id.bt_custom_multiple:
WrcImagePicker.getInstance(this).customPick().multipleMode().maxCount(5).build(this);
break;
}
}
@Override
public void _actionCompleted(final List<ImageItemBean> items) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//stuff that updates ui
if (items.get(0).getUri() != null)
imageView.setImageURI(items.get(0).getUri());
else if (items.get(0).getPath() != null)
imageView.setImageURI(Uri.parse(items.get(0).getPath()));
}
});
}
}
| UTF-8 | Java | 3,411 | java | MainActivity.java | Java | []
| null | []
| package com.wildnet.widnetreusablecomponents;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.wildnet.wrcpicker.imagePicker.listeners.OnActionCompleteListener;
import com.wildnet.wrcpicker.imagePicker.model.ImageItemBean;
import com.wildnet.wrcpicker.imagePicker.patternClasses.WrcImagePicker;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnActionCompleteListener {
Button customCamera, customGallery, defaultGallery, defaultCamera, customSingle, customMultiple;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
}
private void findViewById() {
customCamera = (Button) findViewById(R.id.bt_custom_camera);
customCamera.setOnClickListener(this);
defaultCamera = (Button) findViewById(R.id.bt_default_camera);
defaultCamera.setOnClickListener(this);
defaultGallery = (Button) findViewById(R.id.bt_default_gallery);
defaultGallery.setOnClickListener(this);
customGallery = (Button) findViewById(R.id.bt_custom_gallery);
customGallery.setOnClickListener(this);
customSingle = (Button) findViewById(R.id.bt_custom_single);
customSingle.setOnClickListener(this);
customMultiple = (Button) findViewById(R.id.bt_custom_multiple);
customMultiple.setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageView);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_custom_camera:
WrcImagePicker.getInstance(this).clickImage().setCustom(true).build(this);
break;
case R.id.bt_default_camera:
WrcImagePicker.getInstance(this).clickImage().build(this);
break;
case R.id.bt_default_gallery:
WrcImagePicker.getInstance(this).pickImage().build(new OnActionCompleteListener() {
@Override
public void _actionCompleted(List<ImageItemBean> items) {
}
});
break;
case R.id.bt_custom_gallery:
WrcImagePicker.getInstance(this).pickImage().setCustom(true).build(this);
break;
case R.id.bt_custom_single:
WrcImagePicker.getInstance(this).customPick().singleMode().build(this);
break;
case R.id.bt_custom_multiple:
WrcImagePicker.getInstance(this).customPick().multipleMode().maxCount(5).build(this);
break;
}
}
@Override
public void _actionCompleted(final List<ImageItemBean> items) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//stuff that updates ui
if (items.get(0).getUri() != null)
imageView.setImageURI(items.get(0).getUri());
else if (items.get(0).getPath() != null)
imageView.setImageURI(Uri.parse(items.get(0).getPath()));
}
});
}
}
| 3,411 | 0.639695 | 0.637936 | 108 | 30.583334 | 29.832907 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462963 | false | false | 0 |
e30841274cd38582a2bfc0c2894f8fb8778e70e5 | 18,425,409,713,412 | 5ec17d8c1da4bbac39228934495202a15382131a | /app/src/main/java/threadtest/Test2Runnable.java | bb7cab9d697e93278c7e3f5943c642fc96746ed9 | []
| no_license | CYPChenYanPIng/MyApplication | https://github.com/CYPChenYanPIng/MyApplication | 432d10a4b5fde74d38d170c8137f482473d1724e | 3ae34ef48452925dd517e9e81b2a8c97d3be28c3 | refs/heads/master | 2023-06-29T00:26:22.448000 | 2021-08-02T14:38:16 | 2021-08-02T14:38:16 | 283,775,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package threadtest;
import android.util.Log;
/**
* Created by shuipingyue@uxin.com on 2020/10/26.
*/
class Test2Runnable implements Runnable{
private static final String TAG = "cyp";
private LockObject lockObject;
public Test2Runnable(LockObject lockObject) {
this.lockObject = lockObject;
}
@Override
public void run() {
synchronized (lockObject) {
lockObject.notifyAll();
Log.i(TAG, "run: Test2Runnable 还在运行");
}
}
}
| UTF-8 | Java | 509 | java | Test2Runnable.java | Java | [
{
"context": "test;\n\nimport android.util.Log;\n\n/**\n * Created by shuipingyue@uxin.com on 2020/10/26.\n */\nclass Test2Runnable implements",
"end": 85,
"score": 0.9999188780784607,
"start": 65,
"tag": "EMAIL",
"value": "shuipingyue@uxin.com"
}
]
| null | []
| package threadtest;
import android.util.Log;
/**
* Created by <EMAIL> on 2020/10/26.
*/
class Test2Runnable implements Runnable{
private static final String TAG = "cyp";
private LockObject lockObject;
public Test2Runnable(LockObject lockObject) {
this.lockObject = lockObject;
}
@Override
public void run() {
synchronized (lockObject) {
lockObject.notifyAll();
Log.i(TAG, "run: Test2Runnable 还在运行");
}
}
}
| 496 | 0.636727 | 0.61477 | 23 | 20.782608 | 18.254139 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 0 |
395e06f06805962508faed06d09f50e45b5a24ec | 19,250,043,431,197 | 2a77968f94f590daed0b5a2b1cbba368be0c4d92 | /src/test/java/Runner.java | 313bdebfeade17b8c72983c79a0fc218d88b87a3 | []
| no_license | ostap-oleksyn/LoadDataDownload | https://github.com/ostap-oleksyn/LoadDataDownload | 66798a96e6738c1239d6dd255b639eaa2b3647b1 | d80ae10118cc217f3ca78e6bf8a1553bc27aa3b3 | refs/heads/master | 2016-03-18T20:20:45.129000 | 2015-07-16T14:31:43 | 2015-07-16T14:31:43 | 39,140,462 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import Utils.ProfileUtil;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Runner {
protected WebDriver driver;
protected Runner() {
}
@BeforeClass
public void setUp() {
driver = new FirefoxDriver(ProfileUtil.getProfile());
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
/*//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";
//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");
//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);*/
| UTF-8 | Java | 1,659 | java | Runner.java | Java | []
| null | []
|
import Utils.ProfileUtil;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Runner {
protected WebDriver driver;
protected Runner() {
}
@BeforeClass
public void setUp() {
driver = new FirefoxDriver(ProfileUtil.getProfile());
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
/*//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";
//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");
//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);
//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);*/
| 1,659 | 0.710669 | 0.708861 | 54 | 29.685184 | 26.199961 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.685185 | false | false | 0 |
3b428ff76566588a7ba9446a05f7cf98e5ec630d | 23,656,679,901,052 | c7b6d68ef87ee0f05dad7cb8132dcd6e23bcb370 | /src/java/eu/sig/training/ch05/buildandsendmail/BuildAndSendMail.java | 1c40d02863a1931727c811314df97567c57e4145 | []
| no_license | fariz0020/training-assignments-simple | https://github.com/fariz0020/training-assignments-simple | 2270868af3b4d9fc848441cca2fe487358f80bee | ae5d3fa8c747373943d3e78936cd1346275f4b75 | refs/heads/master | 2020-05-06T12:32:27.361000 | 2019-04-14T14:54:58 | 2019-04-14T14:54:58 | 180,127,402 | 0 | 0 | null | true | 2019-04-08T10:40:34 | 2019-04-08T10:40:34 | 2019-03-05T12:55:09 | 2018-08-28T09:17:31 | 291 | 0 | 0 | 0 | null | false | false | package eu.sig.training.ch05.buildandsendmail;
import java.util.HashMap;
import java.util.Map;
public class BuildAndSendMail {
private Map<String, String> stringMap;
public void buildAndSendMail(MailMan m, Map<String, String> strings, MailFont font) {
// Format the email address
String mId = strings.get("firstName").charAt(0) + "." + strings.get("lastName").substring(0, 7) + "@"
+ strings.get("division").substring(0, 5) + ".compa.ny";
// Format the message given the content type and raw message
MailMessage mMessage = formatMessage(font,
strings.get("message1") + strings.get("message2") + strings.get("message3"));
// Send message
stringMap = new HashMap<>();
stringMap.put("mId", mId);
stringMap.put("subject", strings.get("subject"));
m.send(stringMap, mMessage);
}
@SuppressWarnings("unused")
private MailMessage formatMessage(MailFont font, String string) {
return null;
}
private class MailMan {
@SuppressWarnings("unused")
public void send(Map<String, String> stringMap, MailMessage mMessage) {}
}
private class MailFont {
}
private class MailMessage {
}
} | UTF-8 | Java | 1,249 | java | BuildAndSendMail.java | Java | []
| null | []
| package eu.sig.training.ch05.buildandsendmail;
import java.util.HashMap;
import java.util.Map;
public class BuildAndSendMail {
private Map<String, String> stringMap;
public void buildAndSendMail(MailMan m, Map<String, String> strings, MailFont font) {
// Format the email address
String mId = strings.get("firstName").charAt(0) + "." + strings.get("lastName").substring(0, 7) + "@"
+ strings.get("division").substring(0, 5) + ".compa.ny";
// Format the message given the content type and raw message
MailMessage mMessage = formatMessage(font,
strings.get("message1") + strings.get("message2") + strings.get("message3"));
// Send message
stringMap = new HashMap<>();
stringMap.put("mId", mId);
stringMap.put("subject", strings.get("subject"));
m.send(stringMap, mMessage);
}
@SuppressWarnings("unused")
private MailMessage formatMessage(MailFont font, String string) {
return null;
}
private class MailMan {
@SuppressWarnings("unused")
public void send(Map<String, String> stringMap, MailMessage mMessage) {}
}
private class MailFont {
}
private class MailMessage {
}
} | 1,249 | 0.63811 | 0.630104 | 44 | 27.40909 | 29.162802 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 0 |
ca16018688c5936b8b472cbbf7194cba4c831988 | 7,258,494,755,598 | d392fee59a5a4ddbcc17673eeb1eefe0b546befb | /app/src/main/java/com/example/WeatherApp/DynamicFragment.java | e8bf25730450884e187c8888df81f0b127cc9065 | []
| no_license | leshwar/Android-Weather-App | https://github.com/leshwar/Android-Weather-App | f66746ff812216766ef8da0a46545eb4bcf8f5d6 | eb1a5b5d2e64f1bd0e2618e999f4a470763fba6a | refs/heads/master | 2020-11-29T02:25:27.731000 | 2020-03-27T05:22:58 | 2020-03-27T05:22:58 | 229,992,864 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.WeatherApp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.cardview.widget.CardView;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.os.health.SystemHealthManager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static android.content.ContentValues.TAG;
public class DynamicFragment extends Fragment {
View view;
int val;
TextView c;
String send_city_state_country;
String lat_fav;
String lon_fav;
int searchQuery = 0;
public static ArrayList<Fragment> mFragments = new ArrayList<>();
public static Fragment mFragment = new Fragment();
public static ArrayList<Fragment> getFragmentsList() {
return mFragments;
}
public static Fragment getFragment() {
return mFragment;
}
//Calling the Dark Sky API in Node Server to get Data.
public void darkSkyAPI(String url, final String location) {
//Pass Data Variable
final TextView dark_sky_data = view.findViewById(R.id.dark_sky_data);
//Card1 Variables
final TextView card1_temp = view.findViewById(R.id.card1_temp);
final TextView card1_summary = view.findViewById(R.id.card1_summary);
final TextView card1_location = view.findViewById(R.id.card1_location);
final ImageView card1_icon = view.findViewById(R.id.card1_icon);
//Card2 Variables
final TextView card2_humi_value = view.findViewById(R.id.card2_humi_value);
final TextView card2_wind_value = view.findViewById(R.id.card2_wind_value);
final TextView card2_visi_value = view.findViewById(R.id.card2_visi_value);
final TextView card2_pres_value = view.findViewById(R.id.card2_pres_value);
//Card3 Variables
final TextView date1 = view.findViewById(R.id.date1);
final ImageView icon1 = view.findViewById(R.id.icon1);
final TextView low_temp1 = view.findViewById(R.id.low_temp1);
final TextView high_temp1 = view.findViewById(R.id.high_temp1);
final TextView date2 = view.findViewById(R.id.date2);
final ImageView icon2 = view.findViewById(R.id.icon2);
final TextView low_temp2 = view.findViewById(R.id.low_temp2);
final TextView high_temp2 = view.findViewById(R.id.high_temp2);
final TextView date3 = view.findViewById(R.id.date3);
final ImageView icon3 = view.findViewById(R.id.icon3);
final TextView low_temp3 = view.findViewById(R.id.low_temp3);
final TextView high_temp3 = view.findViewById(R.id.high_temp3);
final TextView date4 = view.findViewById(R.id.date4);
final ImageView icon4 = view.findViewById(R.id.icon4);
final TextView low_temp4 = view.findViewById(R.id.low_temp4);
final TextView high_temp4 = view.findViewById(R.id.high_temp4);
final TextView date5 = view.findViewById(R.id.date5);
final ImageView icon5 = view.findViewById(R.id.icon5);
final TextView low_temp5 = view.findViewById(R.id.low_temp5);
final TextView high_temp5 = view.findViewById(R.id.high_temp5);
final TextView date6 = view.findViewById(R.id.date6);
final ImageView icon6 = view.findViewById(R.id.icon6);
final TextView low_temp6 = view.findViewById(R.id.low_temp6);
final TextView high_temp6 = view.findViewById(R.id.high_temp6);
final TextView date7 = view.findViewById(R.id.date7);
final ImageView icon7 = view.findViewById(R.id.icon7);
final TextView low_temp7 = view.findViewById(R.id.low_temp7);
final TextView high_temp7 = view.findViewById(R.id.high_temp7);
final TextView date8 = view.findViewById(R.id.date8);
final ImageView icon8 = view.findViewById(R.id.icon8);
final TextView low_temp8 = view.findViewById(R.id.low_temp8);
final TextView high_temp8 = view.findViewById(R.id.high_temp8);
final LinearLayout spinner = view.findViewById(R.id.progress_bar_layout);
final RelativeLayout main_layout = view.findViewById(R.id.main_view);
//Setting Fab Icon
final FloatingActionButton fabAdd = view.findViewById(R.id.fabAdd);
final FloatingActionButton fabRemove = view.findViewById(R.id.fabRemove);
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
String shared_value = pref.getString(send_city_state_country,null);
if(shared_value != null) {
fabAdd.hide();
fabRemove.show();
}
else {
fabAdd.show();
fabRemove.hide();
}
if(val == 0 && searchQuery == 0) {
fabAdd.hide();
fabRemove.hide();
}
try {
RequestQueue queue = Volley.newRequestQueue(getContext());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Dark Sky Response", response);
dark_sky_data.setText(response.toString());
String temperature = jsonObject.getJSONObject("currently").getString("temperature");
String summary = jsonObject.getJSONObject("currently").getString("summary");
String icon = jsonObject.getJSONObject("currently").getString("icon");
//Converting Temp to Round value
float i = Float.valueOf(temperature);
int j = (int)Math.round(i);
temperature = Integer.toString(j);
temperature = temperature + "\u00B0 F";
card1_temp.setText(temperature);
card1_summary.setText(summary);
card1_location.setText(location);
card1_icon.setImageResource(R.drawable.weather_sunny);
if(icon.equals("clear-day")) {
card1_icon.setImageResource(R.drawable.weather_sunny);
}
if(icon.equals("clear-night")) {
card1_icon.setImageResource(R.drawable.weather_night);
}
if(icon.equals("rain")) {
card1_icon.setImageResource(R.drawable.weather_rainy);
}
if(icon.equals("sleet")) {
card1_icon.setImageResource(R.drawable.weather_snowy_rainy);
}
if(icon.equals("snow")) {
card1_icon.setImageResource(R.drawable.weather_snowy);
}
if(icon.equals("wind")) {
card1_icon.setImageResource(R.drawable.weather_windy_variant);
}
if(icon.equals("fog")) {
card1_icon.setImageResource(R.drawable.weather_fog);
}
if(icon.equals("cloudy")) {
card1_icon.setImageResource(R.drawable.weather_cloudy);
}
if(icon.equals("partly-cloudy-night")) {
card1_icon.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(icon.equals("partly-cloudy-day")) {
card1_icon.setImageResource(R.drawable.weather_partly_cloudy);
}
DecimalFormat df = new DecimalFormat("0.00");
String humidity = jsonObject.getJSONObject("currently").getString("humidity");
Float humidity_float = Float.parseFloat(humidity);
humidity_float = humidity_float * 100;
int humidity_int = Math.round(humidity_float);
String windSpeed = jsonObject.getJSONObject("currently").getString("windSpeed");
String visibility = jsonObject.getJSONObject("currently").getString("visibility");
String pressure = jsonObject.getJSONObject("currently").getString("pressure");
card2_humi_value.setText(humidity_int + " %");
double windSpeed_float = Math.round(Float.valueOf(windSpeed) * 100.0) / 100.0;
card2_wind_value.setText(df.format(windSpeed_float) + " mph");
double visibility_float = Math.round(Float.valueOf(visibility) * 100.0) / 100.0;
card2_visi_value.setText(df.format(visibility_float) + " km");
double pressure_float = Math.round(Float.valueOf(pressure) * 100.0) / 100.0;
card2_pres_value.setText(df.format(pressure_float) + " mb");
JSONObject data = jsonObject.getJSONObject("daily");
JSONArray data_array = data.getJSONArray("data");
//List 1
String time = data_array.getJSONObject(0).getString("time");
Date date = new java.util.Date(Long.parseLong(time)*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
summary = data_array.getJSONObject(0).getString("icon");
String temperatureLow = data_array.getJSONObject(0).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
String temperatureHigh = data_array.getJSONObject(0).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon1.setImageResource(R.drawable.weather_sunny);
date1.setText(formattedDate);
if(summary.equals("clear-day")) {
icon1.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon1.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon1.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon1.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon1.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon1.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon1.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon1.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon1.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon1.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp1.setText(temperatureLow);
high_temp1.setText(temperatureHigh);
//List 2
time = data_array.getJSONObject(1).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = "";
summary = data_array.getJSONObject(1).getString("icon");
temperatureLow = data_array.getJSONObject(1).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(1).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon2.setImageResource(R.drawable.weather_sunny);
date2.setText(formattedDate);
if(summary.equals("clear-day")) {
icon2.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon2.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon2.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon2.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon2.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon2.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon2.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon2.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon2.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon2.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp2.setText(temperatureLow);
high_temp2.setText(temperatureHigh);
//List 3
time = data_array.getJSONObject(2).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = "";
summary = data_array.getJSONObject(2).getString("icon");
temperatureLow = data_array.getJSONObject(2).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(2).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon3.setImageResource(R.drawable.weather_sunny);
date3.setText(formattedDate);
if(summary.equals("clear-day")) {
icon3.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon3.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon3.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon3.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon3.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon3.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon3.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon3.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon3.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon3.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp3.setText(temperatureLow);
high_temp3.setText(temperatureHigh);
//List 4
time = data_array.getJSONObject(3).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
String summary4 = data_array.getJSONObject(3).getString("icon");
temperatureLow = data_array.getJSONObject(3).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(3).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon4.setImageResource(R.drawable.weather_sunny);
date4.setText(formattedDate);
if(summary.equals("clear-day")) {
icon4.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon4.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon4.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon4.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon4.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon4.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon4.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon4.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon4.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon4.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp4.setText(temperatureLow);
high_temp4.setText(temperatureHigh);
//List 5
time = data_array.getJSONObject(4).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(4).getString("icon");
temperatureLow = data_array.getJSONObject(4).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(4).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon5.setImageResource(R.drawable.weather_sunny);
date5.setText(formattedDate);
if(summary.equals("clear-day")) {
icon5.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon5.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon5.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon5.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon5.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon5.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon5.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon5.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon5.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon5.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp5.setText(temperatureLow);
high_temp5.setText(temperatureHigh);
//List 6
time = data_array.getJSONObject(5).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(5).getString("icon");
temperatureLow = data_array.getJSONObject(5).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(5).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
icon6.setImageResource(R.drawable.weather_sunny);
summary = summary.toLowerCase();
icon6.setImageResource(R.drawable.weather_sunny);
date6.setText(formattedDate);
if(summary.equals("clear-day")) {
icon6.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon6.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon6.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon6.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon6.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon6.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon6.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon6.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon6.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon6.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp6.setText(temperatureLow);
high_temp6.setText(temperatureHigh);
//List 7
time = data_array.getJSONObject(6).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(6).getString("icon");
temperatureLow = data_array.getJSONObject(6).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(6).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon7.setImageResource(R.drawable.weather_sunny);
date7.setText(formattedDate);
if(summary.equals("clear-day")) {
icon7.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon7.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon7.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon7.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon7.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon7.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon7.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon7.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon7.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon7.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp7.setText(temperatureLow);
high_temp7.setText(temperatureHigh);
//List 8
time = data_array.getJSONObject(7).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(7).getString("icon");
temperatureLow = data_array.getJSONObject(7).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(7).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon8.setImageResource(R.drawable.weather_sunny);
date8.setText(formattedDate);
if(summary.equals("clear-day")) {
icon8.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon8.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon8.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon8.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon8.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon8.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon8.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon8.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon8.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon8.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp8.setText(temperatureLow);
high_temp8.setText(temperatureHigh);
spinner.setVisibility(View.GONE);
main_layout.setVisibility(View.VISIBLE);
}
catch (JSONException err){
Log.d("Dark Sky Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("DarkSky Fails","Volley didn't work" + error);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
catch (Exception err) {
Log.d("Error", err.toString());
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Here, the previous Main activity must be called. and inflate that XML code.
//Then all the functions in Main Activity.java must be called.
setHasOptionsMenu(true);
view = inflater.inflate(R.layout.main_page, container, false);
val = getArguments().getInt("someInt", 0);
//Calling the Functions to Load Data in Home Screen.
if(val == 0) {
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "http://ip-api.com/json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
//Calling the DarkSky API to fetch the Weather Details
String lat = jsonObject.getString("lat");
String lon = jsonObject.getString("lon");
String city = jsonObject.getString("city");
String region = jsonObject.getString("region");
String country_code = jsonObject.getString("countryCode");
if(country_code.equals("US")) {
country_code = "USA";
}
String location = city + ", " + region + ", " + country_code;
send_city_state_country = location;
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+lat+"&lon="+lon;
darkSkyAPI(url, location);
}
catch (JSONException err){
Log.d("Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley didn't work", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
else {
//Adding Fragments to a List.
TabAdapter adapter = MainActivity.returnTabAdapter();
mFragments.add(adapter.getItem(val));
ArrayList<String> cities = MainActivity.returnCities();
String[] arrOfStr = cities.get(val-1).split("\\|");
send_city_state_country = arrOfStr[0];
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+arrOfStr[1]+"&lon="+arrOfStr[2];
darkSkyAPI(url, send_city_state_country);
}
//Clicking the Card1 Calls this function
CardView card1_info = view.findViewById(R.id.card1);
card1_info.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
Log.d("image", "clicked");
Intent intent = new Intent(getContext(),DetailedWeather.class);
TextView dark_sky_data = view.findViewById(R.id.dark_sky_data);
String dark_sky_response = dark_sky_data.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("data", dark_sky_response);
bundle.putString("city_state_country", send_city_state_country);
intent.putExtras(bundle);
startActivity(intent);
}
});
final FloatingActionButton fabAdd = view.findViewById(R.id.fabAdd);
final FloatingActionButton fabRemove = view.findViewById(R.id.fabRemove);
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
String shared_value = pref.getString(send_city_state_country,null);
if(shared_value != null) {
fabAdd.hide();
fabRemove.show();
}
else {
fabAdd.show();
fabRemove.hide();
}
if(val == 0) {
fabAdd.hide();
fabRemove.hide();
}
fabAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), send_city_state_country+ " was added to favourites", Toast.LENGTH_SHORT).show();
fabAdd.hide();
fabRemove.show();
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString(send_city_state_country,lat_fav + "|" +lon_fav);
editor.commit();
}
});
fabRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), send_city_state_country+ " was removed from favourites", Toast.LENGTH_SHORT).show();
fabAdd.show();
fabRemove.hide();
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.remove(send_city_state_country);
editor.commit();
//editor.clear();
//Removing the Tab on home page only
if(searchQuery == 0) {
TabLayout tabLayout = MainActivity.returnTabs();
tabLayout.removeTabAt(val);
startActivity(new Intent(getContext(), MainActivity.class));
}
}
});
return view;
}
public static DynamicFragment addfrag(int val) {
DynamicFragment fragment = new DynamicFragment();
Bundle args = new Bundle();
args.putInt("someInt", val);
fragment.setArguments(args);
return fragment;
}
//Code to inflate Menu class
public ArrayAdapter<String> dataAdapter;
public String query2;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == 0) {
}
if(id == 16908332) {
startActivity(new Intent(getContext(), MainActivity.class));
}
return super.onOptionsItemSelected(item);
}
@SuppressLint("ResourceAsColor")
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.options_menu, menu);
final MenuItem searchMenu = menu.findItem(R.id.search);
final androidx.appcompat.widget.SearchView search = (SearchView) MenuItemCompat.getActionView(searchMenu);
final SearchView.SearchAutoComplete searchAutoComplete = search.findViewById(androidx.appcompat.R.id.search_src_text);
searchAutoComplete.setBackgroundColor(Color.DKGRAY);
searchAutoComplete.setDropDownBackgroundResource(R.color.colorWhite);
searchMenu.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
if(query2 != null) {
startActivity(new Intent(getContext(), MainActivity.class));
}
TabLayout tab = MainActivity.returnTabs();
tab.setVisibility(View.VISIBLE);
return true;
}
});
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchQuery = 1;
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
searchMenu.collapseActionView();
searchMenu.setVisible(false);
ActionBar actionbar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setTitle(query);
FloatingActionButton fab = view.findViewById(R.id.fabAdd);
RelativeLayout main_layout = view.findViewById(R.id.main_view);
main_layout.setVisibility(View.GONE);
LinearLayout progress_bar_layout = view.findViewById(R.id.progress_bar_layout);
progress_bar_layout.setVisibility(View.VISIBLE);
fab.show();
TextView search_result = view.findViewById(R.id.search_result);
search_result.setVisibility(View.VISIBLE);
TabLayout tab = MainActivity.returnTabs();
tab.setVisibility(View.GONE);
CustomViewPager viewPager = (CustomViewPager) MainActivity.returnViewPager();
viewPager.setBackgroundColor(Color.BLACK);
viewPager.setEnableSwipe(false);
view.setPadding(0, 10, 0, 0);
query2 = query;
//Call the API Again to direct to right text
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "http://elanka-hw8-final.appspot.com/googleGeoCode?address="+query;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
//Calling the DarkSky API to fetch the Weather Details
String lat = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lat");
lat_fav = lat;
String lon = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lng");
lon_fav = lon;
send_city_state_country = query2;
String location = query2;
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+lat+"&lon="+lon;
darkSkyAPI(url, location);
}
catch (JSONException err){
Log.d("Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley didn't work", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
String url = "http://elanka-hw8-final.appspot.com/api/weatherCard?city="+newText;
try {
RequestQueue queue = Volley.newRequestQueue(getContext());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
List<String> data = new ArrayList<String>();
JSONArray predictions = jsonObject.getJSONArray("predictions");
for(int i = 0; i < predictions.length(); i++) {
data.add(predictions.getJSONObject(i).getString("description"));
}
dataAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, data);
searchAutoComplete.setAdapter(dataAdapter);
}
catch (JSONException err){
Log.d("Weather Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Weather Card Fails","Volley didn't work" + error);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
catch (Exception err) {
Log.d("Error", err.toString());
}
return false;
}
});
searchAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
search.setQuery(dataAdapter.getItem(position).toString(), false);
}
});
}
} | UTF-8 | Java | 50,145 | java | DynamicFragment.java | Java | []
| null | []
| package com.example.WeatherApp;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.cardview.widget.CardView;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.os.health.SystemHealthManager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static android.content.ContentValues.TAG;
public class DynamicFragment extends Fragment {
View view;
int val;
TextView c;
String send_city_state_country;
String lat_fav;
String lon_fav;
int searchQuery = 0;
public static ArrayList<Fragment> mFragments = new ArrayList<>();
public static Fragment mFragment = new Fragment();
public static ArrayList<Fragment> getFragmentsList() {
return mFragments;
}
public static Fragment getFragment() {
return mFragment;
}
//Calling the Dark Sky API in Node Server to get Data.
public void darkSkyAPI(String url, final String location) {
//Pass Data Variable
final TextView dark_sky_data = view.findViewById(R.id.dark_sky_data);
//Card1 Variables
final TextView card1_temp = view.findViewById(R.id.card1_temp);
final TextView card1_summary = view.findViewById(R.id.card1_summary);
final TextView card1_location = view.findViewById(R.id.card1_location);
final ImageView card1_icon = view.findViewById(R.id.card1_icon);
//Card2 Variables
final TextView card2_humi_value = view.findViewById(R.id.card2_humi_value);
final TextView card2_wind_value = view.findViewById(R.id.card2_wind_value);
final TextView card2_visi_value = view.findViewById(R.id.card2_visi_value);
final TextView card2_pres_value = view.findViewById(R.id.card2_pres_value);
//Card3 Variables
final TextView date1 = view.findViewById(R.id.date1);
final ImageView icon1 = view.findViewById(R.id.icon1);
final TextView low_temp1 = view.findViewById(R.id.low_temp1);
final TextView high_temp1 = view.findViewById(R.id.high_temp1);
final TextView date2 = view.findViewById(R.id.date2);
final ImageView icon2 = view.findViewById(R.id.icon2);
final TextView low_temp2 = view.findViewById(R.id.low_temp2);
final TextView high_temp2 = view.findViewById(R.id.high_temp2);
final TextView date3 = view.findViewById(R.id.date3);
final ImageView icon3 = view.findViewById(R.id.icon3);
final TextView low_temp3 = view.findViewById(R.id.low_temp3);
final TextView high_temp3 = view.findViewById(R.id.high_temp3);
final TextView date4 = view.findViewById(R.id.date4);
final ImageView icon4 = view.findViewById(R.id.icon4);
final TextView low_temp4 = view.findViewById(R.id.low_temp4);
final TextView high_temp4 = view.findViewById(R.id.high_temp4);
final TextView date5 = view.findViewById(R.id.date5);
final ImageView icon5 = view.findViewById(R.id.icon5);
final TextView low_temp5 = view.findViewById(R.id.low_temp5);
final TextView high_temp5 = view.findViewById(R.id.high_temp5);
final TextView date6 = view.findViewById(R.id.date6);
final ImageView icon6 = view.findViewById(R.id.icon6);
final TextView low_temp6 = view.findViewById(R.id.low_temp6);
final TextView high_temp6 = view.findViewById(R.id.high_temp6);
final TextView date7 = view.findViewById(R.id.date7);
final ImageView icon7 = view.findViewById(R.id.icon7);
final TextView low_temp7 = view.findViewById(R.id.low_temp7);
final TextView high_temp7 = view.findViewById(R.id.high_temp7);
final TextView date8 = view.findViewById(R.id.date8);
final ImageView icon8 = view.findViewById(R.id.icon8);
final TextView low_temp8 = view.findViewById(R.id.low_temp8);
final TextView high_temp8 = view.findViewById(R.id.high_temp8);
final LinearLayout spinner = view.findViewById(R.id.progress_bar_layout);
final RelativeLayout main_layout = view.findViewById(R.id.main_view);
//Setting Fab Icon
final FloatingActionButton fabAdd = view.findViewById(R.id.fabAdd);
final FloatingActionButton fabRemove = view.findViewById(R.id.fabRemove);
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
String shared_value = pref.getString(send_city_state_country,null);
if(shared_value != null) {
fabAdd.hide();
fabRemove.show();
}
else {
fabAdd.show();
fabRemove.hide();
}
if(val == 0 && searchQuery == 0) {
fabAdd.hide();
fabRemove.hide();
}
try {
RequestQueue queue = Volley.newRequestQueue(getContext());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("Dark Sky Response", response);
dark_sky_data.setText(response.toString());
String temperature = jsonObject.getJSONObject("currently").getString("temperature");
String summary = jsonObject.getJSONObject("currently").getString("summary");
String icon = jsonObject.getJSONObject("currently").getString("icon");
//Converting Temp to Round value
float i = Float.valueOf(temperature);
int j = (int)Math.round(i);
temperature = Integer.toString(j);
temperature = temperature + "\u00B0 F";
card1_temp.setText(temperature);
card1_summary.setText(summary);
card1_location.setText(location);
card1_icon.setImageResource(R.drawable.weather_sunny);
if(icon.equals("clear-day")) {
card1_icon.setImageResource(R.drawable.weather_sunny);
}
if(icon.equals("clear-night")) {
card1_icon.setImageResource(R.drawable.weather_night);
}
if(icon.equals("rain")) {
card1_icon.setImageResource(R.drawable.weather_rainy);
}
if(icon.equals("sleet")) {
card1_icon.setImageResource(R.drawable.weather_snowy_rainy);
}
if(icon.equals("snow")) {
card1_icon.setImageResource(R.drawable.weather_snowy);
}
if(icon.equals("wind")) {
card1_icon.setImageResource(R.drawable.weather_windy_variant);
}
if(icon.equals("fog")) {
card1_icon.setImageResource(R.drawable.weather_fog);
}
if(icon.equals("cloudy")) {
card1_icon.setImageResource(R.drawable.weather_cloudy);
}
if(icon.equals("partly-cloudy-night")) {
card1_icon.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(icon.equals("partly-cloudy-day")) {
card1_icon.setImageResource(R.drawable.weather_partly_cloudy);
}
DecimalFormat df = new DecimalFormat("0.00");
String humidity = jsonObject.getJSONObject("currently").getString("humidity");
Float humidity_float = Float.parseFloat(humidity);
humidity_float = humidity_float * 100;
int humidity_int = Math.round(humidity_float);
String windSpeed = jsonObject.getJSONObject("currently").getString("windSpeed");
String visibility = jsonObject.getJSONObject("currently").getString("visibility");
String pressure = jsonObject.getJSONObject("currently").getString("pressure");
card2_humi_value.setText(humidity_int + " %");
double windSpeed_float = Math.round(Float.valueOf(windSpeed) * 100.0) / 100.0;
card2_wind_value.setText(df.format(windSpeed_float) + " mph");
double visibility_float = Math.round(Float.valueOf(visibility) * 100.0) / 100.0;
card2_visi_value.setText(df.format(visibility_float) + " km");
double pressure_float = Math.round(Float.valueOf(pressure) * 100.0) / 100.0;
card2_pres_value.setText(df.format(pressure_float) + " mb");
JSONObject data = jsonObject.getJSONObject("daily");
JSONArray data_array = data.getJSONArray("data");
//List 1
String time = data_array.getJSONObject(0).getString("time");
Date date = new java.util.Date(Long.parseLong(time)*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
summary = data_array.getJSONObject(0).getString("icon");
String temperatureLow = data_array.getJSONObject(0).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
String temperatureHigh = data_array.getJSONObject(0).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon1.setImageResource(R.drawable.weather_sunny);
date1.setText(formattedDate);
if(summary.equals("clear-day")) {
icon1.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon1.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon1.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon1.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon1.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon1.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon1.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon1.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon1.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon1.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp1.setText(temperatureLow);
high_temp1.setText(temperatureHigh);
//List 2
time = data_array.getJSONObject(1).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = "";
summary = data_array.getJSONObject(1).getString("icon");
temperatureLow = data_array.getJSONObject(1).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(1).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon2.setImageResource(R.drawable.weather_sunny);
date2.setText(formattedDate);
if(summary.equals("clear-day")) {
icon2.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon2.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon2.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon2.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon2.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon2.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon2.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon2.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon2.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon2.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp2.setText(temperatureLow);
high_temp2.setText(temperatureHigh);
//List 3
time = data_array.getJSONObject(2).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = "";
summary = data_array.getJSONObject(2).getString("icon");
temperatureLow = data_array.getJSONObject(2).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(2).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon3.setImageResource(R.drawable.weather_sunny);
date3.setText(formattedDate);
if(summary.equals("clear-day")) {
icon3.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon3.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon3.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon3.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon3.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon3.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon3.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon3.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon3.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon3.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp3.setText(temperatureLow);
high_temp3.setText(temperatureHigh);
//List 4
time = data_array.getJSONObject(3).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
String summary4 = data_array.getJSONObject(3).getString("icon");
temperatureLow = data_array.getJSONObject(3).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(3).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon4.setImageResource(R.drawable.weather_sunny);
date4.setText(formattedDate);
if(summary.equals("clear-day")) {
icon4.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon4.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon4.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon4.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon4.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon4.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon4.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon4.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon4.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon4.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp4.setText(temperatureLow);
high_temp4.setText(temperatureHigh);
//List 5
time = data_array.getJSONObject(4).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(4).getString("icon");
temperatureLow = data_array.getJSONObject(4).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(4).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon5.setImageResource(R.drawable.weather_sunny);
date5.setText(formattedDate);
if(summary.equals("clear-day")) {
icon5.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon5.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon5.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon5.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon5.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon5.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon5.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon5.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon5.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon5.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp5.setText(temperatureLow);
high_temp5.setText(temperatureHigh);
//List 6
time = data_array.getJSONObject(5).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(5).getString("icon");
temperatureLow = data_array.getJSONObject(5).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(5).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
icon6.setImageResource(R.drawable.weather_sunny);
summary = summary.toLowerCase();
icon6.setImageResource(R.drawable.weather_sunny);
date6.setText(formattedDate);
if(summary.equals("clear-day")) {
icon6.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon6.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon6.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon6.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon6.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon6.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon6.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon6.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon6.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon6.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp6.setText(temperatureLow);
high_temp6.setText(temperatureHigh);
//List 7
time = data_array.getJSONObject(6).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(6).getString("icon");
temperatureLow = data_array.getJSONObject(6).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(6).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon7.setImageResource(R.drawable.weather_sunny);
date7.setText(formattedDate);
if(summary.equals("clear-day")) {
icon7.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon7.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon7.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon7.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon7.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon7.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon7.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon7.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon7.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon7.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp7.setText(temperatureLow);
high_temp7.setText(temperatureHigh);
//List 8
time = data_array.getJSONObject(7).getString("time");
date = new java.util.Date(Long.parseLong(time)*1000L);
sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
//sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
formattedDate = sdf.format(date);
summary = data_array.getJSONObject(7).getString("icon");
temperatureLow = data_array.getJSONObject(7).getString("temperatureLow");
i = Float.valueOf(temperatureLow);
j = (int)Math.round(i);
temperatureLow = Integer.toString(j);
temperatureHigh = data_array.getJSONObject(7).getString("temperatureHigh");
i = Float.valueOf(temperatureHigh);
j = (int)Math.round(i);
temperatureHigh = Integer.toString(j);
summary = summary.toLowerCase();
icon8.setImageResource(R.drawable.weather_sunny);
date8.setText(formattedDate);
if(summary.equals("clear-day")) {
icon8.setImageResource(R.drawable.weather_sunny);
}
if(summary.equals("clear-night")) {
icon8.setImageResource(R.drawable.weather_night);
}
if(summary.equals("rain")) {
icon8.setImageResource(R.drawable.weather_rainy);
}
if(summary.equals("sleet")) {
icon8.setImageResource(R.drawable.weather_snowy_rainy);
}
if(summary.equals("snow")) {
icon8.setImageResource(R.drawable.weather_snowy);
}
if(summary.equals("wind")) {
icon8.setImageResource(R.drawable.weather_windy_variant);
}
if(summary.equals("fog")) {
icon8.setImageResource(R.drawable.weather_fog);
}
if(summary.equals("cloudy")) {
icon8.setImageResource(R.drawable.weather_cloudy);
}
if(summary.equals("partly-cloudy-night")) {
icon8.setImageResource(R.drawable.weather_night_partly_cloudy);
}
if(summary.equals("partly-cloudy-day")) {
icon8.setImageResource(R.drawable.weather_partly_cloudy);
}
low_temp8.setText(temperatureLow);
high_temp8.setText(temperatureHigh);
spinner.setVisibility(View.GONE);
main_layout.setVisibility(View.VISIBLE);
}
catch (JSONException err){
Log.d("Dark Sky Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("DarkSky Fails","Volley didn't work" + error);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
catch (Exception err) {
Log.d("Error", err.toString());
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//Here, the previous Main activity must be called. and inflate that XML code.
//Then all the functions in Main Activity.java must be called.
setHasOptionsMenu(true);
view = inflater.inflate(R.layout.main_page, container, false);
val = getArguments().getInt("someInt", 0);
//Calling the Functions to Load Data in Home Screen.
if(val == 0) {
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "http://ip-api.com/json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
//Calling the DarkSky API to fetch the Weather Details
String lat = jsonObject.getString("lat");
String lon = jsonObject.getString("lon");
String city = jsonObject.getString("city");
String region = jsonObject.getString("region");
String country_code = jsonObject.getString("countryCode");
if(country_code.equals("US")) {
country_code = "USA";
}
String location = city + ", " + region + ", " + country_code;
send_city_state_country = location;
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+lat+"&lon="+lon;
darkSkyAPI(url, location);
}
catch (JSONException err){
Log.d("Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley didn't work", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
else {
//Adding Fragments to a List.
TabAdapter adapter = MainActivity.returnTabAdapter();
mFragments.add(adapter.getItem(val));
ArrayList<String> cities = MainActivity.returnCities();
String[] arrOfStr = cities.get(val-1).split("\\|");
send_city_state_country = arrOfStr[0];
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+arrOfStr[1]+"&lon="+arrOfStr[2];
darkSkyAPI(url, send_city_state_country);
}
//Clicking the Card1 Calls this function
CardView card1_info = view.findViewById(R.id.card1);
card1_info.setOnClickListener(new View.OnClickListener() {
//@Override
public void onClick(View v) {
Log.d("image", "clicked");
Intent intent = new Intent(getContext(),DetailedWeather.class);
TextView dark_sky_data = view.findViewById(R.id.dark_sky_data);
String dark_sky_response = dark_sky_data.getText().toString();
Bundle bundle = new Bundle();
bundle.putString("data", dark_sky_response);
bundle.putString("city_state_country", send_city_state_country);
intent.putExtras(bundle);
startActivity(intent);
}
});
final FloatingActionButton fabAdd = view.findViewById(R.id.fabAdd);
final FloatingActionButton fabRemove = view.findViewById(R.id.fabRemove);
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
String shared_value = pref.getString(send_city_state_country,null);
if(shared_value != null) {
fabAdd.hide();
fabRemove.show();
}
else {
fabAdd.show();
fabRemove.hide();
}
if(val == 0) {
fabAdd.hide();
fabRemove.hide();
}
fabAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), send_city_state_country+ " was added to favourites", Toast.LENGTH_SHORT).show();
fabAdd.hide();
fabRemove.show();
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.putString(send_city_state_country,lat_fav + "|" +lon_fav);
editor.commit();
}
});
fabRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), send_city_state_country+ " was removed from favourites", Toast.LENGTH_SHORT).show();
fabAdd.show();
fabRemove.hide();
SharedPreferences pref = getActivity().getApplicationContext().getSharedPreferences("MyPref", Context.MODE_WORLD_READABLE); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.remove(send_city_state_country);
editor.commit();
//editor.clear();
//Removing the Tab on home page only
if(searchQuery == 0) {
TabLayout tabLayout = MainActivity.returnTabs();
tabLayout.removeTabAt(val);
startActivity(new Intent(getContext(), MainActivity.class));
}
}
});
return view;
}
public static DynamicFragment addfrag(int val) {
DynamicFragment fragment = new DynamicFragment();
Bundle args = new Bundle();
args.putInt("someInt", val);
fragment.setArguments(args);
return fragment;
}
//Code to inflate Menu class
public ArrayAdapter<String> dataAdapter;
public String query2;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == 0) {
}
if(id == 16908332) {
startActivity(new Intent(getContext(), MainActivity.class));
}
return super.onOptionsItemSelected(item);
}
@SuppressLint("ResourceAsColor")
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.options_menu, menu);
final MenuItem searchMenu = menu.findItem(R.id.search);
final androidx.appcompat.widget.SearchView search = (SearchView) MenuItemCompat.getActionView(searchMenu);
final SearchView.SearchAutoComplete searchAutoComplete = search.findViewById(androidx.appcompat.R.id.search_src_text);
searchAutoComplete.setBackgroundColor(Color.DKGRAY);
searchAutoComplete.setDropDownBackgroundResource(R.color.colorWhite);
searchMenu.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
if(query2 != null) {
startActivity(new Intent(getContext(), MainActivity.class));
}
TabLayout tab = MainActivity.returnTabs();
tab.setVisibility(View.VISIBLE);
return true;
}
});
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchQuery = 1;
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
searchMenu.collapseActionView();
searchMenu.setVisible(false);
ActionBar actionbar = ((AppCompatActivity)getActivity()).getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setTitle(query);
FloatingActionButton fab = view.findViewById(R.id.fabAdd);
RelativeLayout main_layout = view.findViewById(R.id.main_view);
main_layout.setVisibility(View.GONE);
LinearLayout progress_bar_layout = view.findViewById(R.id.progress_bar_layout);
progress_bar_layout.setVisibility(View.VISIBLE);
fab.show();
TextView search_result = view.findViewById(R.id.search_result);
search_result.setVisibility(View.VISIBLE);
TabLayout tab = MainActivity.returnTabs();
tab.setVisibility(View.GONE);
CustomViewPager viewPager = (CustomViewPager) MainActivity.returnViewPager();
viewPager.setBackgroundColor(Color.BLACK);
viewPager.setEnableSwipe(false);
view.setPadding(0, 10, 0, 0);
query2 = query;
//Call the API Again to direct to right text
RequestQueue queue = Volley.newRequestQueue(getContext());
String url = "http://elanka-hw8-final.appspot.com/googleGeoCode?address="+query;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
//Calling the DarkSky API to fetch the Weather Details
String lat = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lat");
lat_fav = lat;
String lon = jsonObject.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lng");
lon_fav = lon;
send_city_state_country = query2;
String location = query2;
String url = "http://elanka-hw8-final.appspot.com/forecast?lat="+lat+"&lon="+lon;
darkSkyAPI(url, location);
}
catch (JSONException err){
Log.d("Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley didn't work", error.toString());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
String url = "http://elanka-hw8-final.appspot.com/api/weatherCard?city="+newText;
try {
RequestQueue queue = Volley.newRequestQueue(getContext());
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Converting the String to JSON
try {
JSONObject jsonObject = new JSONObject(response);
List<String> data = new ArrayList<String>();
JSONArray predictions = jsonObject.getJSONArray("predictions");
for(int i = 0; i < predictions.length(); i++) {
data.add(predictions.getJSONObject(i).getString("description"));
}
dataAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, data);
searchAutoComplete.setAdapter(dataAdapter);
}
catch (JSONException err){
Log.d("Weather Error", err.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Weather Card Fails","Volley didn't work" + error);
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
catch (Exception err) {
Log.d("Error", err.toString());
}
return false;
}
});
searchAutoComplete.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
search.setQuery(dataAdapter.getItem(position).toString(), false);
}
});
}
} | 50,145 | 0.512913 | 0.505394 | 1,012 | 48.551384 | 30.263441 | 163 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.610672 | false | false | 0 |
9d3a89066c2356f8951c732a415afcc494921cd2 | 25,683,904,442,158 | 8cf76915affa9c0cbdccf13444e48c34e60cf2d0 | /src/com/java/flight/tracker/dao/AirportDAOImpl.java | 4f8f1ec27ea998d611d75ca614536d4a1f57463d | []
| no_license | leejooho77/Spring_MVC_and_Hibernate_Recap | https://github.com/leejooho77/Spring_MVC_and_Hibernate_Recap | d90d20754fc4369c812c304dd4285afce695c3ce | bfa6ce08f99bba79ffc25ce245b8e19fa8c5114f | refs/heads/master | 2020-05-23T10:35:05.277000 | 2019-05-27T03:25:05 | 2019-05-27T03:25:05 | 186,722,442 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.java.flight.tracker.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.flight.tracker.entity.Airport;
@Repository
public class AirportDAOImpl implements AirportDAO {
@Autowired
SessionFactory sessionFactory;
@Override
public List<Airport> getAirports() {
// get current hibernate session
Session session = sessionFactory.getCurrentSession();
// get list of airports
Query<Airport> query = session.createQuery("FROM Airport ORDER BY name", Airport.class);
return query.list();
}
@Override
public List<Integer> getIdByCountry(String name) {
// get current hibernate session
Session session = sessionFactory.getCurrentSession();
// get corresponding data and return
List<Integer> ids = null;
if(name != null && name.trim().length() > 0) {
ids = session.createQuery("SELECT a.id FROM Airport a WHERE lower(a.country) LIKE (:name)", Integer.class)
.setParameter("name", "%" + name.toLowerCase() + "%")
.list();
} else {
ids = session.createQuery("SELECT a.id FROM Airport a", Integer.class)
.list();
}
return ids;
}
}
| UTF-8 | Java | 1,307 | java | AirportDAOImpl.java | Java | []
| null | []
| package com.java.flight.tracker.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.flight.tracker.entity.Airport;
@Repository
public class AirportDAOImpl implements AirportDAO {
@Autowired
SessionFactory sessionFactory;
@Override
public List<Airport> getAirports() {
// get current hibernate session
Session session = sessionFactory.getCurrentSession();
// get list of airports
Query<Airport> query = session.createQuery("FROM Airport ORDER BY name", Airport.class);
return query.list();
}
@Override
public List<Integer> getIdByCountry(String name) {
// get current hibernate session
Session session = sessionFactory.getCurrentSession();
// get corresponding data and return
List<Integer> ids = null;
if(name != null && name.trim().length() > 0) {
ids = session.createQuery("SELECT a.id FROM Airport a WHERE lower(a.country) LIKE (:name)", Integer.class)
.setParameter("name", "%" + name.toLowerCase() + "%")
.list();
} else {
ids = session.createQuery("SELECT a.id FROM Airport a", Integer.class)
.list();
}
return ids;
}
}
| 1,307 | 0.72609 | 0.725325 | 45 | 28.044445 | 25.756945 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.8 | false | false | 0 |
c6c9ae76e393afe62be344cac3a2dd19a96131dc | 25,752,623,968,265 | 05cf5903df9a6559a187936f722128549ee3c610 | /src/io/haitaoc/leetcode/dp/Leet_279_PerfectSquare.java | b5ffe0ad994fd8c839c2f1a02373f6ee3a4aea08 | []
| no_license | haitao-c/Java_algo_solution-master | https://github.com/haitao-c/Java_algo_solution-master | a75ff27b37e142580d63361a315a59ddf1f5a5a2 | 2d624a8bd4a9a60528ab71f3134eaad5da9b4dd0 | refs/heads/master | 2020-03-27T15:58:12.814000 | 2018-09-22T09:03:19 | 2018-09-22T09:03:19 | 146,751,056 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.haitaoc.leetcode.dp;
import java.util.Arrays;
public class Leet_279_PerfectSquare {
/**
* 判断一个数是否是完全平方数
* 正则表达式进行匹配
*
* @param num
* @return
*/
private boolean isSqrt(double num) {
String regex = "\\d+.0+";
return (Math.sqrt(num) + "").matches(regex);
}
public int numSquares(int n) {
// 1. 递归方法 return recursion(n);
// 2. 记忆化搜索方法
/*int[] memo = new int[n+1];
Arrays.fill(memo,-1);
return memorize(n,memo);*/
// 3. 动态规划 1)超时
/*int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i < n+1; i++) {
dp[i] = Integer.MAX_VALUE;
}
for (int i = 2; i < n + 1; i++) {
if(isSqrt(i)){
dp[i] = 1;
continue;
}
// 填充dp表
for (int j = 1; j <= i - 1; j++) {
if (isSqrt(j)) {
// i = j + (i-j)
dp[i] = Math.min(1+dp[i - j], dp[i]);
}
}
}*/
// 2) 所有的完美平方数都可以看做一个普通数加上一个完美平方数,那么递推式就变为了:dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]),
int[] dp = new int[n + 1];
Arrays.fill(dp,Integer.MAX_VALUE);
for (int i = 0; i*i <=n ; i++) {
dp[i*i] = 1;
}
for(int i = 1; i <= n; i++) { //选定第一个数为 i
for(int j = 1; i + j * j <= n; j++) { //选定另一个数为 j*j
dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]); //从小到大查找
}
}
/*for (int i = 0; i < n+1; i++) {
System.out.print(dp[i]+" ");
}
System.out.println();
*/
return dp[n];
}
// 1. 递归解法
private int recursive(int n) {
if (isSqrt(n))
return 1;
// 赋给res初始值为无穷大,
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
if (isSqrt(i))
// 因为递归的过程中,当前值可能会更小的值被取代,所以比较的参数中要有res当前值
res = Math.min(res, 1 + recursive(n - i));
}
return res;
}
// 2.记忆化搜索方法
private int memorize(int n, int[] memo) {
if (isSqrt(n))
return 1;
if (memo[n] != -1)
return memo[n];
// 赋给res初始值为无穷大,
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
if (isSqrt(i))
// 因为递归的过程中,当前值可能会更小的值被取代,所以比较的参数中要有res当前值
res = Math.min(res, 1 + memorize(n - i, memo));
}
memo[n] = res;
return res;
}
public static void main(String... args) {
System.out.println(new Leet_279_PerfectSquare().numSquares(12));
}
}
| UTF-8 | Java | 3,094 | java | Leet_279_PerfectSquare.java | Java | []
| null | []
| package io.haitaoc.leetcode.dp;
import java.util.Arrays;
public class Leet_279_PerfectSquare {
/**
* 判断一个数是否是完全平方数
* 正则表达式进行匹配
*
* @param num
* @return
*/
private boolean isSqrt(double num) {
String regex = "\\d+.0+";
return (Math.sqrt(num) + "").matches(regex);
}
public int numSquares(int n) {
// 1. 递归方法 return recursion(n);
// 2. 记忆化搜索方法
/*int[] memo = new int[n+1];
Arrays.fill(memo,-1);
return memorize(n,memo);*/
// 3. 动态规划 1)超时
/*int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i < n+1; i++) {
dp[i] = Integer.MAX_VALUE;
}
for (int i = 2; i < n + 1; i++) {
if(isSqrt(i)){
dp[i] = 1;
continue;
}
// 填充dp表
for (int j = 1; j <= i - 1; j++) {
if (isSqrt(j)) {
// i = j + (i-j)
dp[i] = Math.min(1+dp[i - j], dp[i]);
}
}
}*/
// 2) 所有的完美平方数都可以看做一个普通数加上一个完美平方数,那么递推式就变为了:dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]),
int[] dp = new int[n + 1];
Arrays.fill(dp,Integer.MAX_VALUE);
for (int i = 0; i*i <=n ; i++) {
dp[i*i] = 1;
}
for(int i = 1; i <= n; i++) { //选定第一个数为 i
for(int j = 1; i + j * j <= n; j++) { //选定另一个数为 j*j
dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]); //从小到大查找
}
}
/*for (int i = 0; i < n+1; i++) {
System.out.print(dp[i]+" ");
}
System.out.println();
*/
return dp[n];
}
// 1. 递归解法
private int recursive(int n) {
if (isSqrt(n))
return 1;
// 赋给res初始值为无穷大,
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
if (isSqrt(i))
// 因为递归的过程中,当前值可能会更小的值被取代,所以比较的参数中要有res当前值
res = Math.min(res, 1 + recursive(n - i));
}
return res;
}
// 2.记忆化搜索方法
private int memorize(int n, int[] memo) {
if (isSqrt(n))
return 1;
if (memo[n] != -1)
return memo[n];
// 赋给res初始值为无穷大,
int res = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
if (isSqrt(i))
// 因为递归的过程中,当前值可能会更小的值被取代,所以比较的参数中要有res当前值
res = Math.min(res, 1 + memorize(n - i, memo));
}
memo[n] = res;
return res;
}
public static void main(String... args) {
System.out.println(new Leet_279_PerfectSquare().numSquares(12));
}
}
| 3,094 | 0.414126 | 0.397398 | 99 | 26.171717 | 19.253252 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.626263 | false | false | 0 |
fab1d85a2213986d232596045bec1c230503eecd | 11,982,958,774,285 | 1942ad08fc5f23235ed725a2b68f775e9f6f46c6 | /website/src/main/java/de/sdsd/projekt/prototype/jsonrpc/AgrirouterEndpoint.java | f2bee48b4642712ab90e4f1f690561f2f66ee5fb | [
"MIT"
]
| permissive | smetal1/sdsd | https://github.com/smetal1/sdsd | 7300a82f818e0598e420fc9e5176917c4734d70b | 9904e505bc30491fdf49b74b491fabd9cd0df8de | refs/heads/master | 2022-12-17T22:23:35.164000 | 2020-09-29T06:57:09 | 2020-09-29T06:57:09 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.sdsd.projekt.prototype.jsonrpc;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import agrirouter.commons.MessageOuterClass.Messages;
import agrirouter.request.payload.endpoint.Capabilities.CapabilitySpecification.PushNotification;
import de.sdsd.projekt.agrirouter.ARException;
import de.sdsd.projekt.agrirouter.ARMessageType;
import de.sdsd.projekt.agrirouter.ARMessageType.ARDirection;
import de.sdsd.projekt.agrirouter.AROnboarding.SecureOnboardingContext;
import de.sdsd.projekt.agrirouter.request.ARCapability;
import de.sdsd.projekt.agrirouter.request.AREndpoint;
import de.sdsd.projekt.agrirouter.request.feed.ARMsgHeader;
import de.sdsd.projekt.agrirouter.request.feed.ARMsgHeader.ARMsgHeaderResult;
import de.sdsd.projekt.prototype.applogic.AgrirouterFunctions.ReceivedMessageResult;
import de.sdsd.projekt.prototype.applogic.ApplicationLogic;
import de.sdsd.projekt.prototype.data.ARCaps;
import de.sdsd.projekt.prototype.data.ARConn;
import de.sdsd.projekt.prototype.data.File;
import de.sdsd.projekt.prototype.data.SDSDException;
import de.sdsd.projekt.prototype.data.User;
import de.sdsd.projekt.prototype.data.Util;
/**
* JSONRPC-Endpoint for agrirouter functions.
*
* @author <a href="mailto:48514372+julianklose@users.noreply.github.com">Julian Klose</a>
*/
public class AgrirouterEndpoint extends JsonRpcEndpoint {
public AgrirouterEndpoint(ApplicationLogic application) {
super(application);
}
public JSONObject status(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
if(user != null) {
ARConn arConn = user.agrirouter();
SecureOnboardingContext soc = user.getSecureOnboardingContext();
JSONObject out = new JSONObject()
.put("pendingEndpoints", user.getPendingEndpoints() != null)
.put("onboarding", soc != null && soc.isReadyToOnboard());
if(arConn != null) {
out
.put("onboarded", true)
.put("qa", arConn.isQA())
.put("mqtt", arConn.isMQTT())
.put("expireDays", Duration.between(Instant.now(), arConn.getExpirationDate()).toDays());
} else {
out
.put("onboarded", false)
.put("qa", false)
.put("mqtt", false);
}
return out;
}
else return new JSONObject();
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject reconnect(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("reconnect: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
application.agrirouter.reconnect(user);
return new JSONObject().put("success", true);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject reonboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("reonboard: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
return new JSONObject().put("success", true).put("redirectUrl", application.agrirouter.reonboard(user).toString());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject startSecureOnboarding(HttpServletRequest req, boolean qa, boolean mqtt) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("StartSecureOnboarding: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else {
return new JSONObject().put("success", true).put("redirectUrl", application.agrirouter.startSecureOnboarding(user, qa, mqtt).toString());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSecureOnboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSecureOnboard: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else {
boolean ok = application.agrirouter.secureOnboard(user);
if(ok) application.logInfo(user, "Onboarded to agrirouter account " + user.agrirouter().getAccountId()
+ " as endpoint " + user.agrirouter().getOwnEndpointId());
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterOffboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterOffboard: user(" + (user != null ? user.getName() : "none") + ") onboarded("
+ (user != null ? user.agrirouter() != null : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = application.agrirouter.offboard(user);
if(ok) application.logInfo(user, "Onboarding revoked");
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private JSONObject endpointToJson(AREndpoint ep) {
if(ep == null) return new JSONObject();
JSONArray accepts = ep.getCapabilities() == null ? new JSONArray() : ep.getCapabilities().stream()
.filter(cap -> cap.getDirection() != ARDirection.SEND)
.map(cap -> cap.getType().technicalMessageType())
.collect(Util.toJSONArray());
return new JSONObject()
.put("id", ep.getId())
.put("name", ep.getName())
.put("type", ep.getType())
.put("active", ep.isActive())
.put("accepts", accepts);
}
public JSONObject listEndpoints(HttpServletRequest req, boolean update) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("listEndpoints: user(" + (user != null ? user.getName() : "none")
+ ") onboarding(" + (user != null ? user.agrirouter() != null : "none") + ") update(" + update + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
try {
List<AREndpoint> endpointLists = update ?
application.agrirouter.readEndpoints(user).join()
: application.agrirouter.getCachedEndpoints(user);
final User finaluser = user;
return new JSONObject()
.put("all", endpointLists.stream()
.filter(e -> !e.getId().equals(finaluser.agrirouter().getOwnEndpointId()) &&
(e.getType().equals("application") || e.getType().equals("pairedAccount")
|| e.getType().equals("machine") || e.getType().equals("virtualCU")))
.map(this::endpointToJson)
.collect(Util.toJSONArray()))
.put("receiver", endpointLists.stream()
.filter(AREndpoint::canReceive)
.map(this::endpointToJson)
.collect(Util.toJSONArray()));
} catch (CompletionException e) {
throw e.getCause();
}
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private CompletableFuture<Boolean> sendFile(final User user, String fileid, boolean publish, String[] targets)
throws SDSDException, IOException, ARException {
ObjectId fid = new ObjectId(fileid);
if(!application.list.files.exists(user, fid)) throw new SDSDException("File not found");
final File file = application.list.files.get(user, fid);
final List<String> targetlist = Arrays.asList(targets);
return application.agrirouter.sendFile(user, file, publish, targetlist)
.handle((v, e) -> {
try {
StringBuilder sb = new StringBuilder("Send file \"")
.append(file.getFilename())
.append("\" to ")
.append(targetlist.stream()
.map(id -> application.list.endpoints.get(user, id).getName())
.collect(Collectors.joining("\", \"")))
.append("\": ");
String error = null;
if (e != null) {
if (e.getCause() != null)
error = e.getCause().getMessage();
else
error = e.getMessage();
application.logError(user, sb.append(error).toString());
}
else if(v != null && v)
application.logInfo(user, sb.append("Successful").toString());
else
return false;
return true;
} catch (Throwable e1) {
e1.printStackTrace();
return false;
}
});
}
public JSONObject sendFiles(HttpServletRequest req, String[] files, String[] targets, boolean wait) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("sendFiles: user(" + (user != null ? user.getName() : "none") + ") files("
+ String.join(", ", files) + ") targets(" + String.join(", ", targets) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = true;
if(files.length > 0 && targets.length > 0) {
ArrayList<CompletableFuture<Boolean>> futures = new ArrayList<CompletableFuture<Boolean>>(files.length);
for (String file : files) {
futures.add(sendFile(user, file, false, targets));
}
if(wait) {
for (CompletableFuture<Boolean> f : futures) {
ok &= f.join();
}
}
}
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject publishFiles(HttpServletRequest req, String[] files, String[] targets, boolean wait) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("publishFiles: user(" + (user != null ? user.getName() : "none") + ") files("
+ String.join(", ", files) + ") targets(" + String.join(", ", targets) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = true;
if(files.length > 0) {
ArrayList<CompletableFuture<Boolean>> futures = new ArrayList<CompletableFuture<Boolean>>(files.length);
for (String file : files) {
futures.add(sendFile(user, file, true, targets));
}
if(wait) {
for (CompletableFuture<Boolean> f : futures) {
ok &= f.join();
}
}
}
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject receiveFiles(HttpServletRequest req, boolean recent) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
try {
ARMsgHeaderResult headers = recent
? application.agrirouter.readMessageHeaders(user, Instant.now().truncatedTo(ChronoUnit.DAYS), Instant.now()).join()
: application.agrirouter.readAllMessageHeaders(user).join();
List<ARMsgHeader> complete = headers.stream()
.filter(h -> !h.getIds().isEmpty() && h.isComplete())
.collect(Collectors.toList());
System.out.println("receiveFiles: user(" + (user != null ? user.getName() : "none")
+ ") recent(" + recent + ") found " + headers.size() + " new messages, "
+ complete.size() + " of these are complete and valid.");
application.logInfo(user, headers.size() + (recent ? " recent" : " new") + " messages available");
if(complete.size() < headers.size())
application.logInfo(user, "There are " + (headers.size() - complete.size())
+ " incomplete messages, that won't be downloaded now.");
int messagesReceived = receiveFiles(user, complete);
System.out.println("receiveFiles: user(" + (user != null ? user.getName() : "none")
+ ") recent(" + recent + ") received " + messagesReceived + " new messages.");
return new JSONObject().put("received", messagesReceived)
.put("moreMessagesAvailable", headers.getSingleMessageCount() < headers.getTotalMessagesInQuery());
} catch(CompletionException e) {
throw e.getCause();
}
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private int receiveFiles(User user, List<ARMsgHeader> headers) {
if(headers.isEmpty()) return 0;
int received = 0;
try {
List<ReceivedMessageResult> results = application.agrirouter.receiveMessages(user, headers).join();
for(int i = 0; i < results.size(); ++i) {
ReceivedMessageResult res = results.get(i);
if(res.isSaved()) {
if(res.isNew())
application.logInfo(user, "Received file: \"" + res.getName() + "\" from "
+ application.list.endpoints.get(user, headers.get(i).getSender()).getName());
++received;
}
else if(res.isError())
throw res.getError();
else {
System.out.println("ARReceive: Discarded file because of missing storage task.");
application.logInfo(user, "Discarded file because of missing storage task");
}
}
} catch (Throwable e) {
if(e instanceof CompletionException) e = e.getCause();
createError(user, e);
}
return received;
}
public JSONObject agrirouterClearFeeds(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterClearFeeds: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
long count = 0;
try {
Messages msgs = application.agrirouter.clearFeed(user).join();
count = msgs.getMessagesList().stream()
.filter(msg -> "VAL_000209".equals(msg.getMessageCode()))
.count();
application.logInfo(user, "Deleted " + count + " messages in the agrirouter feed");
} catch (CompletionException e) {
throw e.getCause();
}
return new JSONObject()
.put("success", true)
.put("count", count);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSubList(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSubList: user(" + (user != null ? user.getName() : "none") +
") onboarding(" + (user != null ? user.agrirouter() != null : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
return new JSONObject().put("subs", new JSONArray());
else {
Set<ARMessageType> subs = user.agrirouter().getSubscriptions();
ARCaps caps = application.list.capabilities.get(user, user.username);
JSONArray array = caps.getCapabilities().stream()
.sorted()
.filter(ARCapability::isReceive)
.map(cap -> artype(cap.getType())
.put("active", subs.contains(cap.getType())))
.collect(Util.toJSONArray());
return new JSONObject().put("subs", array);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSetSubs(HttpServletRequest req, String[] subs) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSetSubs: user(" + (user != null ? user.getName() : "none")
+ ") subs(" + String.join(", ", subs) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = application.agrirouter.setSubscriptions(user, subs);
if(ok) application.logInfo(user, "Set agrirouter subscriptions to " + String.join(", ", subs));
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject listCapabilities(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("listCapabilities: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
ARCaps caps = application.list.capabilities.get(user, user.username);
JSONArray array = new JSONArray();
for(ARMessageType t : ARMessageType.values()) {
if(t.technicalMessageType().isEmpty()) continue;
if(t == ARMessageType.OTHER && !user.agrirouter().isQA()) continue;
JSONObject cap = artype(t);
ARDirection dir = caps.getCapability(t);
if(dir != null) cap.put("direction", dir.number());
array.put(cap);
}
return new JSONObject().put("capabilities", array)
.put("pushNotifications", caps.getPushNotification().getNumber());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject setCapabilities(HttpServletRequest req, JSONArray capabilities, int pushNotifications) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.format("setCapabilities: user(%s) capabilities(%d) pushNotifications(%d)\n",
user != null ? user.getName() : "none", capabilities.length(), pushNotifications);
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
Map<ARMessageType, ARDirection> capMap = new HashMap<>(capabilities.length());
for(int i = 0; i < capabilities.length(); ++i) {
JSONObject cap = capabilities.getJSONObject(i);
ARDirection dir = ARDirection.from(cap.optInt("direction", -1));
if(dir == null) continue;
ARMessageType type = ARMessageType.from(cap.getString("type"));
capMap.put(type, dir);
}
PushNotification push = PushNotification.forNumber(pushNotifications);
if(push == null) throw new SDSDException("Unknown pushNotifications value: " + pushNotifications);
boolean ok = application.agrirouter.setCapabilities(user, capMap, push);
if(ok) application.logInfo(user, "Set %d agrirouter capabilities and pushnotification %s",
capabilities.length(), push.name());
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
}
| UTF-8 | Java | 19,263 | java | AgrirouterEndpoint.java | Java | [
{
"context": " functions.\n * \n * @author <a href=\"mailto:48514372+julianklose@users.noreply.github.com\">Julian Klose",
"end": 1718,
"score": 0.7133005857467651,
"start": 1717,
"tag": "EMAIL",
"value": "2"
},
{
"context": "unctions.\n * \n * @author <a href=\"mailto:48514372+julianklose@users.noreply.github.com\">Julian Klose</a>\n */\npublic class AgrirouterEndp",
"end": 1755,
"score": 0.9968166351318359,
"start": 1719,
"tag": "EMAIL",
"value": "julianklose@users.noreply.github.com"
},
{
"context": "to:48514372+julianklose@users.noreply.github.com\">Julian Klose</a>\n */\npublic class AgrirouterEndpoint extends J",
"end": 1769,
"score": 0.9998556971549988,
"start": 1757,
"tag": "NAME",
"value": "Julian Klose"
}
]
| null | []
| package de.sdsd.projekt.prototype.jsonrpc;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import agrirouter.commons.MessageOuterClass.Messages;
import agrirouter.request.payload.endpoint.Capabilities.CapabilitySpecification.PushNotification;
import de.sdsd.projekt.agrirouter.ARException;
import de.sdsd.projekt.agrirouter.ARMessageType;
import de.sdsd.projekt.agrirouter.ARMessageType.ARDirection;
import de.sdsd.projekt.agrirouter.AROnboarding.SecureOnboardingContext;
import de.sdsd.projekt.agrirouter.request.ARCapability;
import de.sdsd.projekt.agrirouter.request.AREndpoint;
import de.sdsd.projekt.agrirouter.request.feed.ARMsgHeader;
import de.sdsd.projekt.agrirouter.request.feed.ARMsgHeader.ARMsgHeaderResult;
import de.sdsd.projekt.prototype.applogic.AgrirouterFunctions.ReceivedMessageResult;
import de.sdsd.projekt.prototype.applogic.ApplicationLogic;
import de.sdsd.projekt.prototype.data.ARCaps;
import de.sdsd.projekt.prototype.data.ARConn;
import de.sdsd.projekt.prototype.data.File;
import de.sdsd.projekt.prototype.data.SDSDException;
import de.sdsd.projekt.prototype.data.User;
import de.sdsd.projekt.prototype.data.Util;
/**
* JSONRPC-Endpoint for agrirouter functions.
*
* @author <a href="mailto:48514372+<EMAIL>"><NAME></a>
*/
public class AgrirouterEndpoint extends JsonRpcEndpoint {
public AgrirouterEndpoint(ApplicationLogic application) {
super(application);
}
public JSONObject status(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
if(user != null) {
ARConn arConn = user.agrirouter();
SecureOnboardingContext soc = user.getSecureOnboardingContext();
JSONObject out = new JSONObject()
.put("pendingEndpoints", user.getPendingEndpoints() != null)
.put("onboarding", soc != null && soc.isReadyToOnboard());
if(arConn != null) {
out
.put("onboarded", true)
.put("qa", arConn.isQA())
.put("mqtt", arConn.isMQTT())
.put("expireDays", Duration.between(Instant.now(), arConn.getExpirationDate()).toDays());
} else {
out
.put("onboarded", false)
.put("qa", false)
.put("mqtt", false);
}
return out;
}
else return new JSONObject();
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject reconnect(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("reconnect: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
application.agrirouter.reconnect(user);
return new JSONObject().put("success", true);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject reonboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("reonboard: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
return new JSONObject().put("success", true).put("redirectUrl", application.agrirouter.reonboard(user).toString());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject startSecureOnboarding(HttpServletRequest req, boolean qa, boolean mqtt) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("StartSecureOnboarding: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else {
return new JSONObject().put("success", true).put("redirectUrl", application.agrirouter.startSecureOnboarding(user, qa, mqtt).toString());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSecureOnboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSecureOnboard: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else {
boolean ok = application.agrirouter.secureOnboard(user);
if(ok) application.logInfo(user, "Onboarded to agrirouter account " + user.agrirouter().getAccountId()
+ " as endpoint " + user.agrirouter().getOwnEndpointId());
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterOffboard(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterOffboard: user(" + (user != null ? user.getName() : "none") + ") onboarded("
+ (user != null ? user.agrirouter() != null : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = application.agrirouter.offboard(user);
if(ok) application.logInfo(user, "Onboarding revoked");
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private JSONObject endpointToJson(AREndpoint ep) {
if(ep == null) return new JSONObject();
JSONArray accepts = ep.getCapabilities() == null ? new JSONArray() : ep.getCapabilities().stream()
.filter(cap -> cap.getDirection() != ARDirection.SEND)
.map(cap -> cap.getType().technicalMessageType())
.collect(Util.toJSONArray());
return new JSONObject()
.put("id", ep.getId())
.put("name", ep.getName())
.put("type", ep.getType())
.put("active", ep.isActive())
.put("accepts", accepts);
}
public JSONObject listEndpoints(HttpServletRequest req, boolean update) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("listEndpoints: user(" + (user != null ? user.getName() : "none")
+ ") onboarding(" + (user != null ? user.agrirouter() != null : "none") + ") update(" + update + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
try {
List<AREndpoint> endpointLists = update ?
application.agrirouter.readEndpoints(user).join()
: application.agrirouter.getCachedEndpoints(user);
final User finaluser = user;
return new JSONObject()
.put("all", endpointLists.stream()
.filter(e -> !e.getId().equals(finaluser.agrirouter().getOwnEndpointId()) &&
(e.getType().equals("application") || e.getType().equals("pairedAccount")
|| e.getType().equals("machine") || e.getType().equals("virtualCU")))
.map(this::endpointToJson)
.collect(Util.toJSONArray()))
.put("receiver", endpointLists.stream()
.filter(AREndpoint::canReceive)
.map(this::endpointToJson)
.collect(Util.toJSONArray()));
} catch (CompletionException e) {
throw e.getCause();
}
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private CompletableFuture<Boolean> sendFile(final User user, String fileid, boolean publish, String[] targets)
throws SDSDException, IOException, ARException {
ObjectId fid = new ObjectId(fileid);
if(!application.list.files.exists(user, fid)) throw new SDSDException("File not found");
final File file = application.list.files.get(user, fid);
final List<String> targetlist = Arrays.asList(targets);
return application.agrirouter.sendFile(user, file, publish, targetlist)
.handle((v, e) -> {
try {
StringBuilder sb = new StringBuilder("Send file \"")
.append(file.getFilename())
.append("\" to ")
.append(targetlist.stream()
.map(id -> application.list.endpoints.get(user, id).getName())
.collect(Collectors.joining("\", \"")))
.append("\": ");
String error = null;
if (e != null) {
if (e.getCause() != null)
error = e.getCause().getMessage();
else
error = e.getMessage();
application.logError(user, sb.append(error).toString());
}
else if(v != null && v)
application.logInfo(user, sb.append("Successful").toString());
else
return false;
return true;
} catch (Throwable e1) {
e1.printStackTrace();
return false;
}
});
}
public JSONObject sendFiles(HttpServletRequest req, String[] files, String[] targets, boolean wait) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("sendFiles: user(" + (user != null ? user.getName() : "none") + ") files("
+ String.join(", ", files) + ") targets(" + String.join(", ", targets) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = true;
if(files.length > 0 && targets.length > 0) {
ArrayList<CompletableFuture<Boolean>> futures = new ArrayList<CompletableFuture<Boolean>>(files.length);
for (String file : files) {
futures.add(sendFile(user, file, false, targets));
}
if(wait) {
for (CompletableFuture<Boolean> f : futures) {
ok &= f.join();
}
}
}
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject publishFiles(HttpServletRequest req, String[] files, String[] targets, boolean wait) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("publishFiles: user(" + (user != null ? user.getName() : "none") + ") files("
+ String.join(", ", files) + ") targets(" + String.join(", ", targets) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = true;
if(files.length > 0) {
ArrayList<CompletableFuture<Boolean>> futures = new ArrayList<CompletableFuture<Boolean>>(files.length);
for (String file : files) {
futures.add(sendFile(user, file, true, targets));
}
if(wait) {
for (CompletableFuture<Boolean> f : futures) {
ok &= f.join();
}
}
}
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject receiveFiles(HttpServletRequest req, boolean recent) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
try {
ARMsgHeaderResult headers = recent
? application.agrirouter.readMessageHeaders(user, Instant.now().truncatedTo(ChronoUnit.DAYS), Instant.now()).join()
: application.agrirouter.readAllMessageHeaders(user).join();
List<ARMsgHeader> complete = headers.stream()
.filter(h -> !h.getIds().isEmpty() && h.isComplete())
.collect(Collectors.toList());
System.out.println("receiveFiles: user(" + (user != null ? user.getName() : "none")
+ ") recent(" + recent + ") found " + headers.size() + " new messages, "
+ complete.size() + " of these are complete and valid.");
application.logInfo(user, headers.size() + (recent ? " recent" : " new") + " messages available");
if(complete.size() < headers.size())
application.logInfo(user, "There are " + (headers.size() - complete.size())
+ " incomplete messages, that won't be downloaded now.");
int messagesReceived = receiveFiles(user, complete);
System.out.println("receiveFiles: user(" + (user != null ? user.getName() : "none")
+ ") recent(" + recent + ") received " + messagesReceived + " new messages.");
return new JSONObject().put("received", messagesReceived)
.put("moreMessagesAvailable", headers.getSingleMessageCount() < headers.getTotalMessagesInQuery());
} catch(CompletionException e) {
throw e.getCause();
}
}
} catch (Throwable e) {
throw createError(user, e);
}
}
private int receiveFiles(User user, List<ARMsgHeader> headers) {
if(headers.isEmpty()) return 0;
int received = 0;
try {
List<ReceivedMessageResult> results = application.agrirouter.receiveMessages(user, headers).join();
for(int i = 0; i < results.size(); ++i) {
ReceivedMessageResult res = results.get(i);
if(res.isSaved()) {
if(res.isNew())
application.logInfo(user, "Received file: \"" + res.getName() + "\" from "
+ application.list.endpoints.get(user, headers.get(i).getSender()).getName());
++received;
}
else if(res.isError())
throw res.getError();
else {
System.out.println("ARReceive: Discarded file because of missing storage task.");
application.logInfo(user, "Discarded file because of missing storage task");
}
}
} catch (Throwable e) {
if(e instanceof CompletionException) e = e.getCause();
createError(user, e);
}
return received;
}
public JSONObject agrirouterClearFeeds(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterClearFeeds: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
long count = 0;
try {
Messages msgs = application.agrirouter.clearFeed(user).join();
count = msgs.getMessagesList().stream()
.filter(msg -> "VAL_000209".equals(msg.getMessageCode()))
.count();
application.logInfo(user, "Deleted " + count + " messages in the agrirouter feed");
} catch (CompletionException e) {
throw e.getCause();
}
return new JSONObject()
.put("success", true)
.put("count", count);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSubList(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSubList: user(" + (user != null ? user.getName() : "none") +
") onboarding(" + (user != null ? user.agrirouter() != null : "none") + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
return new JSONObject().put("subs", new JSONArray());
else {
Set<ARMessageType> subs = user.agrirouter().getSubscriptions();
ARCaps caps = application.list.capabilities.get(user, user.username);
JSONArray array = caps.getCapabilities().stream()
.sorted()
.filter(ARCapability::isReceive)
.map(cap -> artype(cap.getType())
.put("active", subs.contains(cap.getType())))
.collect(Util.toJSONArray());
return new JSONObject().put("subs", array);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject agrirouterSetSubs(HttpServletRequest req, String[] subs) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("agrirouterSetSubs: user(" + (user != null ? user.getName() : "none")
+ ") subs(" + String.join(", ", subs) + ")");
if (user == null)
throw new NoLoginException();
else if (user.agrirouter() == null)
throw new NoOnboardingException();
else {
boolean ok = application.agrirouter.setSubscriptions(user, subs);
if(ok) application.logInfo(user, "Set agrirouter subscriptions to " + String.join(", ", subs));
return new JSONObject().put("success", ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject listCapabilities(HttpServletRequest req) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.println("listCapabilities: user(" + (user != null ? user.getName() : "none") + ")");
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
ARCaps caps = application.list.capabilities.get(user, user.username);
JSONArray array = new JSONArray();
for(ARMessageType t : ARMessageType.values()) {
if(t.technicalMessageType().isEmpty()) continue;
if(t == ARMessageType.OTHER && !user.agrirouter().isQA()) continue;
JSONObject cap = artype(t);
ARDirection dir = caps.getCapability(t);
if(dir != null) cap.put("direction", dir.number());
array.put(cap);
}
return new JSONObject().put("capabilities", array)
.put("pushNotifications", caps.getPushNotification().getNumber());
}
} catch (Throwable e) {
throw createError(user, e);
}
}
public JSONObject setCapabilities(HttpServletRequest req, JSONArray capabilities, int pushNotifications) throws JsonRpcException {
User user = null;
try {
user = application.getUser(getSessionId(req));
System.out.format("setCapabilities: user(%s) capabilities(%d) pushNotifications(%d)\n",
user != null ? user.getName() : "none", capabilities.length(), pushNotifications);
if (user == null)
throw new NoLoginException();
else if(user.agrirouter() == null)
throw new NoOnboardingException();
else {
Map<ARMessageType, ARDirection> capMap = new HashMap<>(capabilities.length());
for(int i = 0; i < capabilities.length(); ++i) {
JSONObject cap = capabilities.getJSONObject(i);
ARDirection dir = ARDirection.from(cap.optInt("direction", -1));
if(dir == null) continue;
ARMessageType type = ARMessageType.from(cap.getString("type"));
capMap.put(type, dir);
}
PushNotification push = PushNotification.forNumber(pushNotifications);
if(push == null) throw new SDSDException("Unknown pushNotifications value: " + pushNotifications);
boolean ok = application.agrirouter.setCapabilities(user, capMap, push);
if(ok) application.logInfo(user, "Set %d agrirouter capabilities and pushnotification %s",
capabilities.length(), push.name());
return success(ok);
}
} catch (Throwable e) {
throw createError(user, e);
}
}
}
| 19,228 | 0.662098 | 0.660801 | 540 | 34.672222 | 30.073275 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.966667 | false | false | 0 |
1aae9112380a91e6192306402dc3c32cb3ad5c08 | 798,863,930,779 | e4974a2fd037afa2c1dd62e4ed52977c34d3d5ce | /app/src/main/java/com/example/android/chart_v3/MainActivity.java | ca8a82d583b50f0916071521f286d03fdf2897b4 | []
| no_license | conghuy1992/Chart_v3 | https://github.com/conghuy1992/Chart_v3 | 475cb0812e9da5ebf56a990c73d8ddeefd623722 | 5976e9933e3342e09d2890d4e0063ac3b9ae287c | refs/heads/master | 2021-04-06T09:25:01.448000 | 2018-03-11T12:15:42 | 2018-03-11T12:15:42 | 124,750,305 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.chart_v3;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.charts.CombinedChart.DrawOrder;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private CombinedChart mChart;
private final int itemcount = 12;
protected float getRandom(float range, float startsfrom) {
return (float) (Math.random() * range) + startsfrom;
}
protected String[] mMonths = new String[]{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.content_main);
mChart = (CombinedChart) findViewById(R.id.chart1);
mChart.getDescription().setEnabled(false);
mChart.setHighlightFullBarEnabled(false);
mChart.setBackgroundColor(Color.WHITE);
mChart.setDrawGridBackground(false);
mChart.setDrawBarShadow(false);
// combinedChart.setDrawValueAboveBar(false);
mChart.getXAxis().setDrawGridLines(false);
// combinedChart.getXAxis().setEnabled(false);
// combinedChart.getAxisLeft().setDrawAxisLine(false);
mChart.getAxisRight().setDrawAxisLine(false);
mChart.getAxisRight().setDrawLabels(false);
// draw bars behind lines
mChart.setDrawOrder(new DrawOrder[]{
DrawOrder.BAR, DrawOrder.LINE
});
Legend l = mChart.getLegend();
l.setWordWrapEnabled(true);
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mMonths[(int) value % mMonths.length];
}
});
CombinedData data = new CombinedData();
data.setData(generateLineData());
data.setData(generateBarData());
// data.setData(generateBubbleData());
// data.setData(generateScatterData());
// data.setData(generateCandleData());
float xAxisPadding = 0.45f;
xAxis.setAxisMinimum(-xAxisPadding);
xAxis.setAxisMaximum(data.getXMax() + xAxisPadding);
// mChart.xAxis.axisMinimum = -xAxisPadding
// mChart.xAxis.axisMaximum = combinedChartData.xMax + xAxisPadding
mChart.setData(data);
mChart.invalidate();
Bitmap starBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
mChart.setRenderer(new ImageBarChartRenderer(mChart, mChart.getAnimator(), mChart.getViewPortHandler(), starBitmap));
}
private LineData generateLineData() {
LineData d = new LineData();
ArrayList<Entry> entries = new ArrayList<Entry>();
for (int index = 0; index < itemcount; index++)
entries.add(new Entry(index , getRandom(15, 5)));
LineDataSet set = new LineDataSet(entries, "Line DataSet");
set.setColor(Color.rgb(240, 238, 70));
set.setCircleColor(Color.rgb(240, 238, 70));
set.setCircleRadius(5f);
set.setFillColor(Color.rgb(240, 238, 70));
set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setDrawValues(true);
set.setValueTextSize(10f);
set.setValueTextColor(Color.rgb(240, 238, 70));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
d.addDataSet(set);
return d;
}
private BarData generateBarData() {
ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
for (int index = 0; index < mMonths.length; index++)
entries1.add(new BarEntryDto(index, getRandom(15, 5), index + 2));
BarDataSet set1 = new BarDataSet(entries1, "Bar 1");
// set1.setColors(ColorTemplate.COLORFUL_COLORS);
set1.setValueTextColor(Color.rgb(60, 220, 78));
// set1.setValueTextSize(10f);
// set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//
//
// float barWidth = 0.45f; // x2 dataset
// (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"
BarData d = new BarData(set1);
// BarData d = new BarData(set1);
// d.setBarWidth(barWidth);
return d;
}
protected ScatterData generateScatterData() {
ScatterData d = new ScatterData();
ArrayList<Entry> entries = new ArrayList<Entry>();
for (float index = 0; index < itemcount; index += 0.5f)
entries.add(new Entry(index + 0.25f, getRandom(10, 55)));
ScatterDataSet set = new ScatterDataSet(entries, "Scatter DataSet");
set.setColors(ColorTemplate.MATERIAL_COLORS);
set.setScatterShapeSize(7.5f);
set.setDrawValues(false);
set.setValueTextSize(10f);
d.addDataSet(set);
return d;
}
protected CandleData generateCandleData() {
CandleData d = new CandleData();
ArrayList<CandleEntry> entries = new ArrayList<CandleEntry>();
for (int index = 0; index < itemcount; index += 2)
entries.add(new CandleEntry(index + 1f, 90, 70, 85, 75f));
CandleDataSet set = new CandleDataSet(entries, "Candle DataSet");
set.setDecreasingColor(Color.rgb(142, 150, 175));
set.setShadowColor(Color.DKGRAY);
set.setBarSpace(0.3f);
set.setValueTextSize(10f);
set.setDrawValues(false);
d.addDataSet(set);
return d;
}
protected BubbleData generateBubbleData() {
BubbleData bd = new BubbleData();
ArrayList<BubbleEntry> entries = new ArrayList<BubbleEntry>();
for (int index = 0; index < itemcount; index++) {
float y = getRandom(10, 40);
float size = getRandom(100, 105);
Log.d(TAG, "size:" + size);
entries.add(new BubbleEntry(index, y, size));
}
BubbleDataSet set = new BubbleDataSet(entries, "Bubble DataSet");
set.setColors(ColorTemplate.VORDIPLOM_COLORS);
// set.setValueTextSize(10f);
// set.setValueTextColor(Color.WHITE);
// set.setHighlightCircleWidth(1.5f);
// set.setDrawValues(true);
bd.addDataSet(set);
return bd;
}
}
| UTF-8 | Java | 8,719 | java | MainActivity.java | Java | [
{
"context": "rting.charts.CombinedChart;\nimport com.github.mikephil.charting.charts.CombinedChart.DrawOrder;\nimport c",
"end": 417,
"score": 0.5683260560035706,
"start": 413,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "ts.CombinedChart.DrawOrder;\nimport com.github.mikephil.charting.components.AxisBase;\nimport com.github.m",
"end": 485,
"score": 0.5835071802139282,
"start": 481,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "arting.components.AxisBase;\nimport com.github.mikephil.charting.components.Legend;\nimport com.github.mik",
"end": 542,
"score": 0.5221012830734253,
"start": 538,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "charting.components.Legend;\nimport com.github.mikephil.charting.components.XAxis;\nimport com.github.mike",
"end": 597,
"score": 0.6355119943618774,
"start": 593,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "onents.XAxis.XAxisPosition;\nimport com.github.mikephil.charting.components.YAxis;\nimport com.github.mike",
"end": 719,
"score": 0.6061958074569702,
"start": 715,
"tag": "USERNAME",
"value": "phil"
},
{
"context": ".charting.components.YAxis;\nimport com.github.mikephil.charting.data.BarData;\nimport com.github.mikephil",
"end": 773,
"score": 0.5606794357299805,
"start": 769,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "l.charting.data.BubbleData;\nimport com.github.mikephil.charting.data.BubbleDataSet;\nimport com.github.mi",
"end": 980,
"score": 0.5606966018676758,
"start": 976,
"tag": "USERNAME",
"value": "phil"
},
{
"context": ".charting.data.CandleEntry;\nimport com.github.mikephil.charting.data.CombinedData;\nimport com.github.mik",
"end": 1253,
"score": 0.5219119787216187,
"start": 1249,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "charting.data.CombinedData;\nimport com.github.mikephil.charting.data.Entry;\nimport com.github.mikephil.c",
"end": 1308,
"score": 0.5297151207923889,
"start": 1304,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "kephil.charting.data.Entry;\nimport com.github.mikephil.charting.data.LineData;\nimport com.github.mikephi",
"end": 1356,
"score": 0.5834676027297974,
"start": 1352,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "hil.charting.data.LineData;\nimport com.github.mikephil.charting.data.LineDataSet;\nimport com.github.mike",
"end": 1407,
"score": 0.5141755938529968,
"start": 1403,
"tag": "USERNAME",
"value": "phil"
},
{
"context": "g.interfaces.datasets.IDataSet;\nimport com.github.mikephil.charting.utils.ColorTemplate;\n\nimport java.util.A",
"end": 1705,
"score": 0.9979715943336487,
"start": 1697,
"tag": "USERNAME",
"value": "mikephil"
}
]
| null | []
| package com.example.android.chart_v3;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.charts.CombinedChart.DrawOrder;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.XAxis.XAxisPosition;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private CombinedChart mChart;
private final int itemcount = 12;
protected float getRandom(float range, float startsfrom) {
return (float) (Math.random() * range) + startsfrom;
}
protected String[] mMonths = new String[]{
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.content_main);
mChart = (CombinedChart) findViewById(R.id.chart1);
mChart.getDescription().setEnabled(false);
mChart.setHighlightFullBarEnabled(false);
mChart.setBackgroundColor(Color.WHITE);
mChart.setDrawGridBackground(false);
mChart.setDrawBarShadow(false);
// combinedChart.setDrawValueAboveBar(false);
mChart.getXAxis().setDrawGridLines(false);
// combinedChart.getXAxis().setEnabled(false);
// combinedChart.getAxisLeft().setDrawAxisLine(false);
mChart.getAxisRight().setDrawAxisLine(false);
mChart.getAxisRight().setDrawLabels(false);
// draw bars behind lines
mChart.setDrawOrder(new DrawOrder[]{
DrawOrder.BAR, DrawOrder.LINE
});
Legend l = mChart.getLegend();
l.setWordWrapEnabled(true);
l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
l.setDrawInside(false);
YAxis rightAxis = mChart.getAxisRight();
rightAxis.setDrawGridLines(false);
rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
YAxis leftAxis = mChart.getAxisLeft();
leftAxis.setDrawGridLines(false);
leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
XAxis xAxis = mChart.getXAxis();
xAxis.setPosition(XAxisPosition.BOTH_SIDED);
xAxis.setAxisMinimum(0f);
xAxis.setGranularity(1f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return mMonths[(int) value % mMonths.length];
}
});
CombinedData data = new CombinedData();
data.setData(generateLineData());
data.setData(generateBarData());
// data.setData(generateBubbleData());
// data.setData(generateScatterData());
// data.setData(generateCandleData());
float xAxisPadding = 0.45f;
xAxis.setAxisMinimum(-xAxisPadding);
xAxis.setAxisMaximum(data.getXMax() + xAxisPadding);
// mChart.xAxis.axisMinimum = -xAxisPadding
// mChart.xAxis.axisMaximum = combinedChartData.xMax + xAxisPadding
mChart.setData(data);
mChart.invalidate();
Bitmap starBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
mChart.setRenderer(new ImageBarChartRenderer(mChart, mChart.getAnimator(), mChart.getViewPortHandler(), starBitmap));
}
private LineData generateLineData() {
LineData d = new LineData();
ArrayList<Entry> entries = new ArrayList<Entry>();
for (int index = 0; index < itemcount; index++)
entries.add(new Entry(index , getRandom(15, 5)));
LineDataSet set = new LineDataSet(entries, "Line DataSet");
set.setColor(Color.rgb(240, 238, 70));
set.setCircleColor(Color.rgb(240, 238, 70));
set.setCircleRadius(5f);
set.setFillColor(Color.rgb(240, 238, 70));
set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setDrawValues(true);
set.setValueTextSize(10f);
set.setValueTextColor(Color.rgb(240, 238, 70));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
d.addDataSet(set);
return d;
}
private BarData generateBarData() {
ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
for (int index = 0; index < mMonths.length; index++)
entries1.add(new BarEntryDto(index, getRandom(15, 5), index + 2));
BarDataSet set1 = new BarDataSet(entries1, "Bar 1");
// set1.setColors(ColorTemplate.COLORFUL_COLORS);
set1.setValueTextColor(Color.rgb(60, 220, 78));
// set1.setValueTextSize(10f);
// set1.setAxisDependency(YAxis.AxisDependency.LEFT);
//
//
// float barWidth = 0.45f; // x2 dataset
// (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"
BarData d = new BarData(set1);
// BarData d = new BarData(set1);
// d.setBarWidth(barWidth);
return d;
}
protected ScatterData generateScatterData() {
ScatterData d = new ScatterData();
ArrayList<Entry> entries = new ArrayList<Entry>();
for (float index = 0; index < itemcount; index += 0.5f)
entries.add(new Entry(index + 0.25f, getRandom(10, 55)));
ScatterDataSet set = new ScatterDataSet(entries, "Scatter DataSet");
set.setColors(ColorTemplate.MATERIAL_COLORS);
set.setScatterShapeSize(7.5f);
set.setDrawValues(false);
set.setValueTextSize(10f);
d.addDataSet(set);
return d;
}
protected CandleData generateCandleData() {
CandleData d = new CandleData();
ArrayList<CandleEntry> entries = new ArrayList<CandleEntry>();
for (int index = 0; index < itemcount; index += 2)
entries.add(new CandleEntry(index + 1f, 90, 70, 85, 75f));
CandleDataSet set = new CandleDataSet(entries, "Candle DataSet");
set.setDecreasingColor(Color.rgb(142, 150, 175));
set.setShadowColor(Color.DKGRAY);
set.setBarSpace(0.3f);
set.setValueTextSize(10f);
set.setDrawValues(false);
d.addDataSet(set);
return d;
}
protected BubbleData generateBubbleData() {
BubbleData bd = new BubbleData();
ArrayList<BubbleEntry> entries = new ArrayList<BubbleEntry>();
for (int index = 0; index < itemcount; index++) {
float y = getRandom(10, 40);
float size = getRandom(100, 105);
Log.d(TAG, "size:" + size);
entries.add(new BubbleEntry(index, y, size));
}
BubbleDataSet set = new BubbleDataSet(entries, "Bubble DataSet");
set.setColors(ColorTemplate.VORDIPLOM_COLORS);
// set.setValueTextSize(10f);
// set.setValueTextColor(Color.WHITE);
// set.setHighlightCircleWidth(1.5f);
// set.setDrawValues(true);
bd.addDataSet(set);
return bd;
}
}
| 8,719 | 0.676912 | 0.660167 | 243 | 34.880657 | 25.329397 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.872428 | false | false | 0 |
41992da1effe6d556bb35b7e35ceddab7d1821a5 | 26,989,574,501,069 | b90a6a1621c0bfad07757f566400dca60f78c25f | /UltimateRecyclerView/ultimaterecyclerview/src/main/java/com/marshalchen/ultimaterecyclerview/expanx/Util/easyTemplateChild.java | 5b1cade223774d285e4f5f8ca970de1b68b033e8 | [
"Apache-2.0"
]
| permissive | wmrob/UltimateRecyclerView | https://github.com/wmrob/UltimateRecyclerView | 5c46990e636bda6fc2d2c624c2246932df83771c | 4b6f763a317e6171daf7531d155c68d1efebb1b4 | refs/heads/master | 2021-01-15T19:58:54.622000 | 2020-09-10T09:19:44 | 2020-09-10T09:19:44 | 52,889,397 | 0 | 0 | Apache-2.0 | true | 2020-09-10T09:19:45 | 2016-03-01T15:53:31 | 2016-03-01T15:53:34 | 2020-09-10T09:19:44 | 8,042 | 0 | 0 | 0 | Java | false | false | package com.marshalchen.ultimaterecyclerview.expanx.Util;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.expanx.ExpandableItemData;
/**
* on 16/7/15.
* ultimate created by jjHesk
* based on library https://github.com/jjhesk/BringItBackAdvanceSlidingMenu
*/
public abstract class easyTemplateChild<T extends ExpandableItemData, B extends TextView, H extends RelativeLayout> extends child<T> {
public B text;
public H relativeLayout;
private int offsetMargin, itemMargin;
private boolean capitalized = false;
private boolean countenabled = true;
public easyTemplateChild(View itemView, int itemMargin, int expandSize) {
this(itemView);
this.itemMargin = itemMargin;
this.offsetMargin = expandSize;
}
public easyTemplateChild(View itemView) {
super(itemView);
text = (B) itemView.findViewById(R.id.exp_section_title);
relativeLayout = (H) itemView.findViewById(R.id.exp_section_ripple_wrapper_click);
itemMargin = itemView.getContext().getResources()
.getDimensionPixelSize(R.dimen.item_margin);
offsetMargin = itemView.getContext().getResources()
.getDimensionPixelSize(R.dimen.expand_size);
}
protected void forceTitleCapitalized(boolean b) {
capitalized = b;
}
@Override
public void bindView(final T itemData, int position) {
if (capitalized) {
text.setText(itemData.getText().toUpperCase());
} else {
text.setText(itemData.getText());
}
text.setLayoutParams(getParamsLayoutOffset(text, itemData));
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// item = itemData;
onChildItemClick(itemData.getText(), itemData.getPath());
}
});
}
@Override
public void onChildItemClick(String title, String path) {
String[] v = path.split("/");
if (v.length > 1) {
request_api(v, title);
}
}
protected void request_api(final String[] n, final String title) {
}
}
| UTF-8 | Java | 2,322 | java | easyTemplateChild.java | Java | [
{
"context": "emData;\n\n/**\n * on 16/7/15.\n * ultimate created by jjHesk\n * based on library https://github.com/jjhesk/Bri",
"end": 323,
"score": 0.9997573494911194,
"start": 317,
"tag": "USERNAME",
"value": "jjHesk"
},
{
"context": " by jjHesk\n * based on library https://github.com/jjhesk/BringItBackAdvanceSlidingMenu\n */\npublic abstract",
"end": 369,
"score": 0.9994438290596008,
"start": 363,
"tag": "USERNAME",
"value": "jjhesk"
}
]
| null | []
| package com.marshalchen.ultimaterecyclerview.expanx.Util;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.marshalchen.ultimaterecyclerview.R;
import com.marshalchen.ultimaterecyclerview.expanx.ExpandableItemData;
/**
* on 16/7/15.
* ultimate created by jjHesk
* based on library https://github.com/jjhesk/BringItBackAdvanceSlidingMenu
*/
public abstract class easyTemplateChild<T extends ExpandableItemData, B extends TextView, H extends RelativeLayout> extends child<T> {
public B text;
public H relativeLayout;
private int offsetMargin, itemMargin;
private boolean capitalized = false;
private boolean countenabled = true;
public easyTemplateChild(View itemView, int itemMargin, int expandSize) {
this(itemView);
this.itemMargin = itemMargin;
this.offsetMargin = expandSize;
}
public easyTemplateChild(View itemView) {
super(itemView);
text = (B) itemView.findViewById(R.id.exp_section_title);
relativeLayout = (H) itemView.findViewById(R.id.exp_section_ripple_wrapper_click);
itemMargin = itemView.getContext().getResources()
.getDimensionPixelSize(R.dimen.item_margin);
offsetMargin = itemView.getContext().getResources()
.getDimensionPixelSize(R.dimen.expand_size);
}
protected void forceTitleCapitalized(boolean b) {
capitalized = b;
}
@Override
public void bindView(final T itemData, int position) {
if (capitalized) {
text.setText(itemData.getText().toUpperCase());
} else {
text.setText(itemData.getText());
}
text.setLayoutParams(getParamsLayoutOffset(text, itemData));
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// item = itemData;
onChildItemClick(itemData.getText(), itemData.getPath());
}
});
}
@Override
public void onChildItemClick(String title, String path) {
String[] v = path.split("/");
if (v.length > 1) {
request_api(v, title);
}
}
protected void request_api(final String[] n, final String title) {
}
}
| 2,322 | 0.660207 | 0.657623 | 75 | 29.959999 | 28.091963 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52 | false | false | 0 |
0933ffce440e720bf8b3ee60dc09bcce06973146 | 5,617,817,265,892 | 823fe39d137a2b72159499e5b3ff9c700fc51180 | /Inteligentes_Extra/src/control/ReadJSON.java | 349d6060feaee1e6de88f2dda5ec466ba0aa83ce | []
| no_license | Kirkuss/Inteligentes | https://github.com/Kirkuss/Inteligentes | 2211f045f9b08e8a0fc4fb2743a90648908bf192 | 02b180e0bd6716409920f395b0d3786ca271d454 | refs/heads/master | 2020-04-24T08:51:06.170000 | 2019-06-05T18:04:34 | 2019-06-05T18:04:34 | 171,843,888 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package control;
import java.io.BufferedReader;
import java.io.FileReader;
import com.google.gson.Gson;
public class ReadJSON {
public static Problem Read(String jsonFile) {
Problem init = new Problem();
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(jsonFile));
init = gson.fromJson(br, Problem.class);
}catch(Exception e) {
e.printStackTrace();
}
return init;
}
}
| UTF-8 | Java | 452 | java | ReadJSON.java | Java | []
| null | []
| package control;
import java.io.BufferedReader;
import java.io.FileReader;
import com.google.gson.Gson;
public class ReadJSON {
public static Problem Read(String jsonFile) {
Problem init = new Problem();
Gson gson = new Gson();
try {
BufferedReader br = new BufferedReader(new FileReader(jsonFile));
init = gson.fromJson(br, Problem.class);
}catch(Exception e) {
e.printStackTrace();
}
return init;
}
}
| 452 | 0.674779 | 0.674779 | 21 | 19.523809 | 17.77269 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.666667 | false | false | 0 |
4f4f824f4d06ecba471a46b4312314958790602e | 25,125,558,683,069 | 40472fdd939bd31c07e227811cfa566e80a64f46 | /src/cn/ksource/mapper/dicData/SysDicDataSqlProvider.java | cb575fc06e5867828f7f1e0b4624cb688de3a958 | []
| no_license | chenlong11/dev-demo | https://github.com/chenlong11/dev-demo | 87b300d6911990775d4e86c889c71d32fb9edacf | 3104a42925eff836965ddd7add1ec899d7d1d5dc | refs/heads/master | 2020-03-28T17:13:26.158000 | 2018-12-29T02:54:25 | 2018-12-29T02:54:25 | 148,769,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.ksource.mapper.dicData;
import cn.ksource.domain.dicData.SysDicData;
import cn.ksource.domain.dicData.SysDicDataExample.Criteria;
import cn.ksource.domain.dicData.SysDicDataExample.Criterion;
import cn.ksource.domain.dicData.SysDicDataExample;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
public class SysDicDataSqlProvider {
public String countByExample(SysDicDataExample example) {
SQL sql = new SQL();
sql.SELECT("count(*)").FROM("sys_dic_data");
applyWhere(sql, example, false);
return sql.toString();
}
public String deleteByExample(SysDicDataExample example) {
SQL sql = new SQL();
sql.DELETE_FROM("sys_dic_data");
applyWhere(sql, example, false);
return sql.toString();
}
public String insertSelective(SysDicData record) {
SQL sql = new SQL();
sql.INSERT_INTO("sys_dic_data");
if (record.getId() != null) {
sql.VALUES("id", "#{id,jdbcType=BIGINT}");
}
if (record.getDicId() != null) {
sql.VALUES("dic_id", "#{dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.VALUES("data_code", "#{dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.VALUES("data_val", "#{dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.VALUES("sn", "#{sn,jdbcType=SMALLINT}");
}
return sql.toString();
}
public String selectByExample(SysDicDataExample example) {
SQL sql = new SQL();
if (example != null && example.isDistinct()) {
sql.SELECT_DISTINCT("id");
} else {
sql.SELECT("id");
}
sql.SELECT("dic_id");
sql.SELECT("data_code");
sql.SELECT("data_val");
sql.SELECT("sn");
sql.FROM("sys_dic_data");
applyWhere(sql, example, false);
if (example != null && example.getOrderByClause() != null) {
sql.ORDER_BY(example.getOrderByClause());
}
return sql.toString();
}
public String updateByExampleSelective(Map<String, Object> parameter) {
SysDicData record = (SysDicData) parameter.get("record");
SysDicDataExample example = (SysDicDataExample) parameter.get("example");
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
if (record.getId() != null) {
sql.SET("id = #{record.id,jdbcType=BIGINT}");
}
if (record.getDicId() != null) {
sql.SET("dic_id = #{record.dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.SET("data_code = #{record.dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.SET("data_val = #{record.dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.SET("sn = #{record.sn,jdbcType=SMALLINT}");
}
applyWhere(sql, example, true);
return sql.toString();
}
public String updateByExample(Map<String, Object> parameter) {
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
sql.SET("id = #{record.id,jdbcType=BIGINT}");
sql.SET("dic_id = #{record.dicId,jdbcType=BIGINT}");
sql.SET("data_code = #{record.dataCode,jdbcType=VARCHAR}");
sql.SET("data_val = #{record.dataVal,jdbcType=VARCHAR}");
sql.SET("sn = #{record.sn,jdbcType=SMALLINT}");
SysDicDataExample example = (SysDicDataExample) parameter.get("example");
applyWhere(sql, example, true);
return sql.toString();
}
public String updateByPrimaryKeySelective(SysDicData record) {
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
if (record.getDicId() != null) {
sql.SET("dic_id = #{dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.SET("data_code = #{dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.SET("data_val = #{dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.SET("sn = #{sn,jdbcType=SMALLINT}");
}
sql.WHERE("id = #{id,jdbcType=BIGINT}");
return sql.toString();
}
protected void applyWhere(SQL sql, SysDicDataExample example, boolean includeExamplePhrase) {
if (example == null) {
return;
}
String parmPhrase1;
String parmPhrase1_th;
String parmPhrase2;
String parmPhrase2_th;
String parmPhrase3;
String parmPhrase3_th;
if (includeExamplePhrase) {
parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
} else {
parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
}
StringBuilder sb = new StringBuilder();
List<Criteria> oredCriteria = example.getOredCriteria();
boolean firstCriteria = true;
for (int i = 0; i < oredCriteria.size(); i++) {
Criteria criteria = oredCriteria.get(i);
if (criteria.isValid()) {
if (firstCriteria) {
firstCriteria = false;
} else {
sb.append(" or ");
}
sb.append('(');
List<Criterion> criterions = criteria.getAllCriteria();
boolean firstCriterion = true;
for (int j = 0; j < criterions.size(); j++) {
Criterion criterion = criterions.get(j);
if (firstCriterion) {
firstCriterion = false;
} else {
sb.append(" and ");
}
if (criterion.isNoValue()) {
sb.append(criterion.getCondition());
} else if (criterion.isSingleValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
} else {
sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j,criterion.getTypeHandler()));
}
} else if (criterion.isBetweenValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
} else {
sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
}
} else if (criterion.isListValue()) {
sb.append(criterion.getCondition());
sb.append(" (");
List<?> listItems = (List<?>) criterion.getValue();
boolean comma = false;
for (int k = 0; k < listItems.size(); k++) {
if (comma) {
sb.append(", ");
} else {
comma = true;
}
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase3, i, j, k));
} else {
sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
}
}
sb.append(')');
}
}
sb.append(')');
}
}
if (sb.length() > 0) {
sql.WHERE(sb.toString());
}
}
} | UTF-8 | Java | 9,343 | java | SysDicDataSqlProvider.java | Java | []
| null | []
| package cn.ksource.mapper.dicData;
import cn.ksource.domain.dicData.SysDicData;
import cn.ksource.domain.dicData.SysDicDataExample.Criteria;
import cn.ksource.domain.dicData.SysDicDataExample.Criterion;
import cn.ksource.domain.dicData.SysDicDataExample;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
public class SysDicDataSqlProvider {
public String countByExample(SysDicDataExample example) {
SQL sql = new SQL();
sql.SELECT("count(*)").FROM("sys_dic_data");
applyWhere(sql, example, false);
return sql.toString();
}
public String deleteByExample(SysDicDataExample example) {
SQL sql = new SQL();
sql.DELETE_FROM("sys_dic_data");
applyWhere(sql, example, false);
return sql.toString();
}
public String insertSelective(SysDicData record) {
SQL sql = new SQL();
sql.INSERT_INTO("sys_dic_data");
if (record.getId() != null) {
sql.VALUES("id", "#{id,jdbcType=BIGINT}");
}
if (record.getDicId() != null) {
sql.VALUES("dic_id", "#{dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.VALUES("data_code", "#{dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.VALUES("data_val", "#{dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.VALUES("sn", "#{sn,jdbcType=SMALLINT}");
}
return sql.toString();
}
public String selectByExample(SysDicDataExample example) {
SQL sql = new SQL();
if (example != null && example.isDistinct()) {
sql.SELECT_DISTINCT("id");
} else {
sql.SELECT("id");
}
sql.SELECT("dic_id");
sql.SELECT("data_code");
sql.SELECT("data_val");
sql.SELECT("sn");
sql.FROM("sys_dic_data");
applyWhere(sql, example, false);
if (example != null && example.getOrderByClause() != null) {
sql.ORDER_BY(example.getOrderByClause());
}
return sql.toString();
}
public String updateByExampleSelective(Map<String, Object> parameter) {
SysDicData record = (SysDicData) parameter.get("record");
SysDicDataExample example = (SysDicDataExample) parameter.get("example");
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
if (record.getId() != null) {
sql.SET("id = #{record.id,jdbcType=BIGINT}");
}
if (record.getDicId() != null) {
sql.SET("dic_id = #{record.dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.SET("data_code = #{record.dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.SET("data_val = #{record.dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.SET("sn = #{record.sn,jdbcType=SMALLINT}");
}
applyWhere(sql, example, true);
return sql.toString();
}
public String updateByExample(Map<String, Object> parameter) {
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
sql.SET("id = #{record.id,jdbcType=BIGINT}");
sql.SET("dic_id = #{record.dicId,jdbcType=BIGINT}");
sql.SET("data_code = #{record.dataCode,jdbcType=VARCHAR}");
sql.SET("data_val = #{record.dataVal,jdbcType=VARCHAR}");
sql.SET("sn = #{record.sn,jdbcType=SMALLINT}");
SysDicDataExample example = (SysDicDataExample) parameter.get("example");
applyWhere(sql, example, true);
return sql.toString();
}
public String updateByPrimaryKeySelective(SysDicData record) {
SQL sql = new SQL();
sql.UPDATE("sys_dic_data");
if (record.getDicId() != null) {
sql.SET("dic_id = #{dicId,jdbcType=BIGINT}");
}
if (record.getDataCode() != null) {
sql.SET("data_code = #{dataCode,jdbcType=VARCHAR}");
}
if (record.getDataVal() != null) {
sql.SET("data_val = #{dataVal,jdbcType=VARCHAR}");
}
if (record.getSn() != null) {
sql.SET("sn = #{sn,jdbcType=SMALLINT}");
}
sql.WHERE("id = #{id,jdbcType=BIGINT}");
return sql.toString();
}
protected void applyWhere(SQL sql, SysDicDataExample example, boolean includeExamplePhrase) {
if (example == null) {
return;
}
String parmPhrase1;
String parmPhrase1_th;
String parmPhrase2;
String parmPhrase2_th;
String parmPhrase3;
String parmPhrase3_th;
if (includeExamplePhrase) {
parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
} else {
parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
}
StringBuilder sb = new StringBuilder();
List<Criteria> oredCriteria = example.getOredCriteria();
boolean firstCriteria = true;
for (int i = 0; i < oredCriteria.size(); i++) {
Criteria criteria = oredCriteria.get(i);
if (criteria.isValid()) {
if (firstCriteria) {
firstCriteria = false;
} else {
sb.append(" or ");
}
sb.append('(');
List<Criterion> criterions = criteria.getAllCriteria();
boolean firstCriterion = true;
for (int j = 0; j < criterions.size(); j++) {
Criterion criterion = criterions.get(j);
if (firstCriterion) {
firstCriterion = false;
} else {
sb.append(" and ");
}
if (criterion.isNoValue()) {
sb.append(criterion.getCondition());
} else if (criterion.isSingleValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
} else {
sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j,criterion.getTypeHandler()));
}
} else if (criterion.isBetweenValue()) {
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
} else {
sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
}
} else if (criterion.isListValue()) {
sb.append(criterion.getCondition());
sb.append(" (");
List<?> listItems = (List<?>) criterion.getValue();
boolean comma = false;
for (int k = 0; k < listItems.size(); k++) {
if (comma) {
sb.append(", ");
} else {
comma = true;
}
if (criterion.getTypeHandler() == null) {
sb.append(String.format(parmPhrase3, i, j, k));
} else {
sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
}
}
sb.append(')');
}
}
sb.append(')');
}
}
if (sb.length() > 0) {
sql.WHERE(sb.toString());
}
}
} | 9,343 | 0.505833 | 0.502836 | 238 | 38.260506 | 30.188612 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.802521 | false | false | 0 |
de978be234fc11fa5b3ed59cca50f4dc78163032 | 2,199,023,259,738 | e76d56f97654e62e586a94e000bc50d6e28e2927 | /src/leetcode/programmers/소수찾기.java | 2a7a87e51038aeb5f4255d8ae5e84257f62c602d | []
| no_license | DONGCHULCHOI/algorithm | https://github.com/DONGCHULCHOI/algorithm | d3eda742faf301bf9f2a70813f26969a775b969b | a031e34bcb4d4334155fb1e51fc7cf7ea7647b1a | refs/heads/master | 2023-04-07T18:22:32.379000 | 2021-04-13T15:45:25 | 2021-04-13T15:45:25 | 263,896,434 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package leetcode.programmers;
import com.company.Pair;
import java.util.HashSet;
import java.util.Set;
public class 소수찾기 {
// Brute force(backtracking):
/*
문제 설명
한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
제한사항
numbers는 길이 1 이상 7 이하인 문자열입니다.
numbers는 0~9까지 숫자만으로 이루어져 있습니다.
"013"은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.
입출력 예
numbers return
"17" 3
"011" 2
입출력 예 설명
예제 #1
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.
예제 #2
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.
11과 011은 같은 숫자로 취급합니다.
*/
private int answer = 0;
private Set<Pair<Integer, Character>> setForVisited = new HashSet<>();
private Set<Integer> setForRes = new HashSet<>();
public int solution(String numbers) {
char[] nums = numbers.toCharArray();
backtracking(new StringBuilder(), nums);
return answer;
}
private void backtracking(StringBuilder assignment, char[] domain) {
if(assignment.length() == domain.length) {
return;
}
for(int i = 0; i < domain.length; i++) {
if (!setForVisited.contains(new Pair<>(i, domain[i]))) {
assignment.append(domain[i]);
setForVisited.add(new Pair<>(i, domain[i]));
backtracking(assignment, domain);
int num = Integer.parseInt(assignment.toString());
if(!setForRes.contains(num)) {
if(isPrime(num)) {
answer++;
}
setForRes.add(num);
}
assignment.deleteCharAt(assignment.length() - 1);
setForVisited.remove(new Pair<>(i, domain[i]));
}
}
}
private boolean isPrime(int num) {
if(num == 0 || num == 1) {
return false;
}
if(num == 2) {
return true;
}
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
}
| UTF-8 | Java | 2,627 | java | 소수찾기.java | Java | []
| null | []
| package leetcode.programmers;
import com.company.Pair;
import java.util.HashSet;
import java.util.Set;
public class 소수찾기 {
// Brute force(backtracking):
/*
문제 설명
한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때, 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
제한사항
numbers는 길이 1 이상 7 이하인 문자열입니다.
numbers는 0~9까지 숫자만으로 이루어져 있습니다.
"013"은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.
입출력 예
numbers return
"17" 3
"011" 2
입출력 예 설명
예제 #1
[1, 7]으로는 소수 [7, 17, 71]를 만들 수 있습니다.
예제 #2
[0, 1, 1]으로는 소수 [11, 101]를 만들 수 있습니다.
11과 011은 같은 숫자로 취급합니다.
*/
private int answer = 0;
private Set<Pair<Integer, Character>> setForVisited = new HashSet<>();
private Set<Integer> setForRes = new HashSet<>();
public int solution(String numbers) {
char[] nums = numbers.toCharArray();
backtracking(new StringBuilder(), nums);
return answer;
}
private void backtracking(StringBuilder assignment, char[] domain) {
if(assignment.length() == domain.length) {
return;
}
for(int i = 0; i < domain.length; i++) {
if (!setForVisited.contains(new Pair<>(i, domain[i]))) {
assignment.append(domain[i]);
setForVisited.add(new Pair<>(i, domain[i]));
backtracking(assignment, domain);
int num = Integer.parseInt(assignment.toString());
if(!setForRes.contains(num)) {
if(isPrime(num)) {
answer++;
}
setForRes.add(num);
}
assignment.deleteCharAt(assignment.length() - 1);
setForVisited.remove(new Pair<>(i, domain[i]));
}
}
}
private boolean isPrime(int num) {
if(num == 0 || num == 1) {
return false;
}
if(num == 2) {
return true;
}
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
}
| 2,627 | 0.515718 | 0.494305 | 87 | 24.229885 | 22.558073 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 0 |
34d2d07e55eb6d7b0cde9df9bf098515213c6b09 | 29,815,663,007,591 | 3b95e2b4e1cbbea9838588a3e161532dddd066de | /org/rem/dao/hibernate/RegistroAfpHibernateDao.java | 4d717b78b7d104ac725a07dc79547fde5af83400 | []
| no_license | jguerrero-tival/remuneraciones | https://github.com/jguerrero-tival/remuneraciones | 18bce723ea7709b4ef6d6c6b1c27854c6d4f23f3 | aaaf83536b891c654d4d8307102d3b81cda3a285 | refs/heads/master | 2021-01-21T07:53:59.234000 | 2014-01-21T02:33:35 | 2014-01-21T02:33:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.rem.dao.hibernate;
import org.rem.dao.RegistroAfpDao;
import org.rem.model.informes.RegistroAfp;
import java.util.*;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
public class RegistroAfpHibernateDao extends GenericHibernateDao<RegistroAfp, Long, RegistroAfpDao>
implements RegistroAfpDao {
@SuppressWarnings("unchecked")
@Override
public List<RegistroAfp> findAll() {
Criteria crit = getSession().createCriteria(getPersistentClass());
crit.addOrder(Order.asc("rutTrabajador"));
return crit.list();
}
} | UTF-8 | Java | 553 | java | RegistroAfpHibernateDao.java | Java | []
| null | []
| package org.rem.dao.hibernate;
import org.rem.dao.RegistroAfpDao;
import org.rem.model.informes.RegistroAfp;
import java.util.*;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
public class RegistroAfpHibernateDao extends GenericHibernateDao<RegistroAfp, Long, RegistroAfpDao>
implements RegistroAfpDao {
@SuppressWarnings("unchecked")
@Override
public List<RegistroAfp> findAll() {
Criteria crit = getSession().createCriteria(getPersistentClass());
crit.addOrder(Order.asc("rutTrabajador"));
return crit.list();
}
} | 553 | 0.790235 | 0.790235 | 20 | 26.700001 | 24.769135 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15 | false | false | 0 |
13ed220a133650dd7ad9c975d4ab9e4c2911bda8 | 29,815,663,006,983 | 9b103f5dfadb756a38b4ed460293151b868574af | /JDBC/proj0416_20/view/InputView.java | e4cba6569800ce7746bccbaefd46024060bf649e | []
| no_license | musemy4/pubilc | https://github.com/musemy4/pubilc | 06226d0ef66ab3ae1d5ffdea2d94469acbc3fc76 | 52e4faabe263a6f889f36c2c9b965a8974e41aab | refs/heads/master | 2021-05-23T16:35:46.099000 | 2020-09-09T07:34:08 | 2020-09-09T07:34:08 | 253,383,291 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package swingMvc_h2.proj0416_20.view;
import java.awt.Color;
import javax.swing.*;
public class InputView extends View {
JPanel inputPane = new JPanel();
public InputView() {
display();
}
@Override
void display() {
JLabel lbl_name = new JLabel("회원명 :");
lbl_name.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_name.setBounds(12, 53, 89, 28);
inputPane.add(lbl_name);
JLabel lbl_phone = new JLabel("전화번호 :");
lbl_phone.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_phone.setBounds(12, 85, 89, 28);
inputPane.add(lbl_phone);
JLabel lbl_designer = new JLabel("담당디자이너:");
lbl_designer.setHorizontalAlignment(SwingConstants.RIGHT);
inputPane.add(lbl_designer);
lbl_designer.setBounds(12, 143, 89, 28);
tf_name.setBounds(110, 57, 116, 21);
inputPane.add(tf_name);
tf_name.setColumns(10);
tf_phone.setColumns(10);
tf_phone.setBounds(110, 89, 116, 21);
inputPane.add(tf_phone);
JLabel lbl_ismember = new JLabel("회원/비회원 :");
lbl_ismember.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_ismember.setBounds(12, 22, 89, 28);
inputPane.add(lbl_ismember);
JRadioButton rb_new = new JRadioButton("new");
rb_new.setBounds(110, 24, 56, 25);
inputPane.add(rb_new);
JRadioButton rb_member = new JRadioButton("member");
rb_member.setBounds(173, 24, 73, 25);
inputPane.add(rb_member);
JComboBox cb_hair = new JComboBox();
cb_hair.setBounds(110, 183, 115, 24);
inputPane.add(cb_hair);
JLabel lbl_hair = new JLabel("시술명 :");
lbl_hair.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_hair.setBounds(12, 181, 89, 28);
inputPane.add(lbl_hair);
JList designerlist = new JList();
designerlist.setBounds(113, 149, 116, 21);
inputPane.add(designerlist);
JLabel lbl_hair2 = new JLabel("서비스 :");
lbl_hair2.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_hair2.setBounds(12, 219, 89, 28);
inputPane.add(lbl_hair2);
JComboBox cb_hair2 = new JComboBox();
cb_hair2.setBounds(110, 217, 115, 24);
inputPane.add(cb_hair2);
JLabel lbl_pay = new JLabel("금액 :");
lbl_pay.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_pay.setBounds(12, 272, 89, 28);
inputPane.add(lbl_pay);
tf_pay.setColumns(10);
tf_pay.setBounds(110, 276, 116, 21);
inputPane.add(tf_pay);
JLabel lbl_point = new JLabel("포인트 :");
lbl_point.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_point.setBounds(12, 307, 89, 28);
inputPane.add(lbl_point);
tf_point.setColumns(10);
tf_point.setBounds(110, 311, 116, 21);
inputPane.add(tf_point);
}
@Override
void evt() {
}
}
| UTF-8 | Java | 2,779 | java | InputView.java | Java | []
| null | []
| package swingMvc_h2.proj0416_20.view;
import java.awt.Color;
import javax.swing.*;
public class InputView extends View {
JPanel inputPane = new JPanel();
public InputView() {
display();
}
@Override
void display() {
JLabel lbl_name = new JLabel("회원명 :");
lbl_name.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_name.setBounds(12, 53, 89, 28);
inputPane.add(lbl_name);
JLabel lbl_phone = new JLabel("전화번호 :");
lbl_phone.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_phone.setBounds(12, 85, 89, 28);
inputPane.add(lbl_phone);
JLabel lbl_designer = new JLabel("담당디자이너:");
lbl_designer.setHorizontalAlignment(SwingConstants.RIGHT);
inputPane.add(lbl_designer);
lbl_designer.setBounds(12, 143, 89, 28);
tf_name.setBounds(110, 57, 116, 21);
inputPane.add(tf_name);
tf_name.setColumns(10);
tf_phone.setColumns(10);
tf_phone.setBounds(110, 89, 116, 21);
inputPane.add(tf_phone);
JLabel lbl_ismember = new JLabel("회원/비회원 :");
lbl_ismember.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_ismember.setBounds(12, 22, 89, 28);
inputPane.add(lbl_ismember);
JRadioButton rb_new = new JRadioButton("new");
rb_new.setBounds(110, 24, 56, 25);
inputPane.add(rb_new);
JRadioButton rb_member = new JRadioButton("member");
rb_member.setBounds(173, 24, 73, 25);
inputPane.add(rb_member);
JComboBox cb_hair = new JComboBox();
cb_hair.setBounds(110, 183, 115, 24);
inputPane.add(cb_hair);
JLabel lbl_hair = new JLabel("시술명 :");
lbl_hair.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_hair.setBounds(12, 181, 89, 28);
inputPane.add(lbl_hair);
JList designerlist = new JList();
designerlist.setBounds(113, 149, 116, 21);
inputPane.add(designerlist);
JLabel lbl_hair2 = new JLabel("서비스 :");
lbl_hair2.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_hair2.setBounds(12, 219, 89, 28);
inputPane.add(lbl_hair2);
JComboBox cb_hair2 = new JComboBox();
cb_hair2.setBounds(110, 217, 115, 24);
inputPane.add(cb_hair2);
JLabel lbl_pay = new JLabel("금액 :");
lbl_pay.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_pay.setBounds(12, 272, 89, 28);
inputPane.add(lbl_pay);
tf_pay.setColumns(10);
tf_pay.setBounds(110, 276, 116, 21);
inputPane.add(tf_pay);
JLabel lbl_point = new JLabel("포인트 :");
lbl_point.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_point.setBounds(12, 307, 89, 28);
inputPane.add(lbl_point);
tf_point.setColumns(10);
tf_point.setBounds(110, 311, 116, 21);
inputPane.add(tf_point);
}
@Override
void evt() {
}
}
| 2,779 | 0.658214 | 0.590592 | 105 | 23.914286 | 18.61137 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.780952 | false | false | 0 |
6f07421bd857c70eab17aa0f1ac63fcaef43f82d | 11,665,131,216,035 | fd9ab52e4f498bcdd92b2178daa7aa5e555db158 | /src/main/java/com/bonatone/common/message/service/IMessageService.java | 7b4d3bb7d999cb4624d12aaee874d1d7f2d465d7 | []
| no_license | 13535534071/bnt | https://github.com/13535534071/bnt | 79ec303cc7b09cbc26bb7124455c33880aa91aa2 | a296d26ec19e5613737f79a44e11ec30f03f19b6 | refs/heads/master | 2018-07-12T16:25:11.486000 | 2018-03-02T02:40:34 | 2018-03-02T02:41:36 | 123,527,975 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bonatone.common.message.service;
import java.util.Map;
import com.bonatone.eweb.exception.ServiceException;
/**
* 消息服务
* @author uatleixg
* @version 1.0
*/
public interface IMessageService {
String BEAN_ID = "messageService";
/**
* 查询消息列表
* @param param
* @param offset
* @param pageSize
* @return 对象数组,数组第一位为当前页数据集合,第二位为消息总记录
* @throws ServiceException
*/
Object[] getMessageList(Map<String, Object> param, int offset, int pageSize) throws ServiceException;
/**
* 查询消息接收明细列表
* @param param
* @param offset
* @param pageSize
* @return 对象数组,数组第一位为当前页数据集合,第二位为消息总记录
* @throws ServiceException
*/
Object[] getMessageReciversList(Map<String, Object> param, int offset, int pageSize) throws ServiceException;
}
| UTF-8 | Java | 914 | java | IMessageService.java | Java | [
{
"context": "xception.ServiceException;\n\n/**\n * 消息服务\n * @author uatleixg\n * @version 1.0\n */\npublic interface IMessageServ",
"end": 154,
"score": 0.9996258020401001,
"start": 146,
"tag": "USERNAME",
"value": "uatleixg"
}
]
| null | []
| package com.bonatone.common.message.service;
import java.util.Map;
import com.bonatone.eweb.exception.ServiceException;
/**
* 消息服务
* @author uatleixg
* @version 1.0
*/
public interface IMessageService {
String BEAN_ID = "messageService";
/**
* 查询消息列表
* @param param
* @param offset
* @param pageSize
* @return 对象数组,数组第一位为当前页数据集合,第二位为消息总记录
* @throws ServiceException
*/
Object[] getMessageList(Map<String, Object> param, int offset, int pageSize) throws ServiceException;
/**
* 查询消息接收明细列表
* @param param
* @param offset
* @param pageSize
* @return 对象数组,数组第一位为当前页数据集合,第二位为消息总记录
* @throws ServiceException
*/
Object[] getMessageReciversList(Map<String, Object> param, int offset, int pageSize) throws ServiceException;
}
| 914 | 0.71916 | 0.716535 | 34 | 21.411764 | 25.422451 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.970588 | false | false | 0 |
ca6e12d99fa83c84e240b530f7035cbbe291bdd9 | 30,296,699,338,165 | df974882ec4240f4b8bd6c7debc8f17d8881fdff | /src/main/java/com/shixinke/utils/web/annotation/RequestContentType.java | f370a39602c7cb8226e57a6904c6dc073e95da84 | [
"Apache-2.0"
]
| permissive | shixinke/web-utils | https://github.com/shixinke/web-utils | a01e6e697572ffd4be39fe0c28ab2218a68f89b8 | 9d8d6dec9bd6a54d70d37257a89b3a8062e35b81 | refs/heads/master | 2022-06-21T05:20:28.189000 | 2019-07-25T09:17:27 | 2019-07-25T09:17:27 | 177,094,485 | 1 | 0 | Apache-2.0 | false | 2022-06-21T01:06:30 | 2019-03-22T07:42:47 | 2019-09-30T00:43:17 | 2022-06-21T01:06:30 | 135 | 1 | 0 | 7 | Java | false | false | package com.shixinke.utils.web.annotation;
/**
* request content type
* @author shixinke
* @version 1.0
* created 19-2-22 下午3:27
*/
public enum RequestContentType {
/**
* JSON
*/
JSON,
/**
* www-form-urlencoded
*/
FORM,
/**
* get the format by Content-Type in header
*/
AUTO
}
| UTF-8 | Java | 341 | java | RequestContentType.java | Java | [
{
"context": "nnotation;\n\n/**\n * request content type\n * @author shixinke\n * @version 1.0\n * created 19-2-22 下午3:27\n */\npub",
"end": 91,
"score": 0.9996026158332825,
"start": 83,
"tag": "USERNAME",
"value": "shixinke"
}
]
| null | []
| package com.shixinke.utils.web.annotation;
/**
* request content type
* @author shixinke
* @version 1.0
* created 19-2-22 下午3:27
*/
public enum RequestContentType {
/**
* JSON
*/
JSON,
/**
* www-form-urlencoded
*/
FORM,
/**
* get the format by Content-Type in header
*/
AUTO
}
| 341 | 0.557863 | 0.52819 | 22 | 14.318182 | 12.725731 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.136364 | false | false | 0 |
7937d42c51a185a43b692baa8dd5c0ce4ac6fda1 | 29,515,015,298,010 | ffebb06e54e3f760b5ab9c78218af44b6ae48dac | /Cuenta/tests/cuenta/creditotest.java | 92c93f6741f5dde1087f7945ae08af4154333150 | []
| no_license | javier471/repoTests | https://github.com/javier471/repoTests | 23a74dd6467cbeb230da136452229cb0ecf3fd80 | 6133a6f368e3b55579881504ed8640b6bd743c28 | refs/heads/master | 2023-05-08T02:12:01.236000 | 2021-05-21T11:55:51 | 2021-05-21T11:55:51 | 360,837,599 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cuenta;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class creditotest {
private Credito c1;
@BeforeEach
public void init() {
c1=new Credito("21212","Paco",null,500.00);
}
@Test
void testRetirar() throws Exception {
c1.retirar(100.00);
assertEquals(400.00,c1.getCreditoDisponible());
}
@Test
void testIngresar() {
fail("Not yet implemented");
}
@Test
void testPagoEnEstablecimiento() {
fail("Not yet implemented");
}
@Test
void getSaldo() {
fail("Not yet implemented");
}
}
| UTF-8 | Java | 603 | java | creditotest.java | Java | []
| null | []
| package cuenta;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class creditotest {
private Credito c1;
@BeforeEach
public void init() {
c1=new Credito("21212","Paco",null,500.00);
}
@Test
void testRetirar() throws Exception {
c1.retirar(100.00);
assertEquals(400.00,c1.getCreditoDisponible());
}
@Test
void testIngresar() {
fail("Not yet implemented");
}
@Test
void testPagoEnEstablecimiento() {
fail("Not yet implemented");
}
@Test
void getSaldo() {
fail("Not yet implemented");
}
}
| 603 | 0.696517 | 0.656716 | 37 | 15.297297 | 15.903195 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.216216 | false | false | 0 |
e06a1e11fe847cd27a88741f659f3cb3306ab194 | 15,642,270,938,752 | c36aaecf79c7be6151924c86fb42033f1c7f4cdf | /Casino/src/texas/Player.java | c8ff8b0f9b134f362e139d24abac36387c16eee6 | []
| no_license | jingol/Casino | https://github.com/jingol/Casino | 10a3dc474409aaad49f5a293d54cbe54716932ca | b42b11a7df4c56d1ab35085fe0ad0481dab1ea79 | refs/heads/master | 2020-12-31T06:08:45.029000 | 2017-03-27T09:21:03 | 2017-03-27T09:21:03 | 80,647,195 | 0 | 0 | null | false | 2017-03-03T16:28:59 | 2017-02-01T17:54:39 | 2017-02-02T17:27:02 | 2017-03-03T16:28:59 | 11,528 | 0 | 0 | 0 | Java | null | null | package texas;
//Ray
import java.util.ArrayList;
public class Player extends DealtHand{
private int money;
private int x;
private int y;
private int width;
private int height;
private int playernum;
private boolean isPlaying;
public Player(int x, int y, int width, int height, int money, int playernum) {
this.money = money;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.playernum = playernum;
isPlaying = true;
}
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean isPlaying) {
this.isPlaying = isPlaying;
}
public int getPlayerNum(){
return playernum;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public ArrayList<Integer> getTieHand() {
//the array this method will return has the first index as the value of the win hand
//aka if bomb then return the numeric value of the bomb
//checks the best win condition of the hand
ArrayList<Integer> tHand = new ArrayList<Integer>();
ArrayList<PlayingCard> cardHand = getHand();
int hand = getWinHand();
String[] suitArr = getSuits();
int[] values = getFaceValues();
int a = 0;
int b = 0;
String suit = "";
switch(hand){
//if its a bomb
case 7:
for(int i = 0; i<values.length-4; i++){
if(values[i] == values[i+1] && values[i+1] == values[i+2] && values[i+2] == values[i+3]){
a = values[i];
break;
}
}
tHand.add(a);
for(int i = values.length-1; i>-1; i--){
if(values[i] != a)
tHand.add(values[i]);
}
return tHand;
//if full house
case 6:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1] && values[i-1] == values[i-2]){
a = values[i];
break;
}
}
tHand.add(a);
for(int i = values.length-1; i>0; i--){
if(values[i] != a && values[i] == values[i-1]){
b = values[i];
break;
}
}
tHand.add(b);
for(int i = values.length-1; i>-1; i--){
if(values[i] != a && values[i] != b)
tHand.add(values[i]);
}
return tHand;
//if flush
case 5:
for(int i = 0; i<suitArr.length-4; i++){
if(suitArr[i].equals(suitArr[i+1]) && suitArr[i+1].equals(suitArr[i+2]) && suitArr[i+2].equals(suitArr[i+3]) && suitArr[i+3].equals(suitArr[i+4]))
suit = suitArr[i];
}
int count = 0;
for(int i = cardHand.size()-1; i>-1; i--){
if(count<5 && cardHand.get(i).getSuit().equals(suit)){
tHand.add(cardHand.get(i).getCardValue());
}
}
for(int i = cardHand.size()-1; i>-1; i--){
if(!cardHand.get(i).getSuit().equals(suit))
tHand.add(cardHand.get(i).getCardValue());
}
return tHand;
//if straight
case 4:
for(int i = values.length-1; i>3; i--){
if(values[i] == values[i-1]+1 && values[i-1] == values[i-2]+1 && values[i-2] == values[i-3]+1 && values[i-3] == values[i-4]+1){
for(int j = 0; j<5; j++){
tHand.add(values[i]-j);
}
}
}
return tHand;
//if triple
case 3:
for(int i = values.length-1; i>2; i--){
if(values[i] == values[i-1] && values[i-1] == values[i-2]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>-1; j--){
if(values[j] != a)
tHand.add(values[j]);
}
return tHand;
//if two pair
case 2:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>1; j--){
if(values[j] != a && values[j] == values[j-1]){
b = values[j];
}
}
tHand.add(b);
for(int k = values.length-1; k>-1; k--){
if(values[k] != a && values[k] != b)
tHand.add(values[k]);
}
return tHand;
//if double
case 1:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>-1; j--){
if(values[j] != a)
tHand.add(values[j]);
}
return tHand;
//if hi card
case 0:
for(int i = values.length-1; i>-1; i--){
tHand.add(values[i]);
}
return tHand;
default: return tHand;
}
}
}
| UTF-8 | Java | 4,663 | java | Player.java | Java | []
| null | []
| package texas;
//Ray
import java.util.ArrayList;
public class Player extends DealtHand{
private int money;
private int x;
private int y;
private int width;
private int height;
private int playernum;
private boolean isPlaying;
public Player(int x, int y, int width, int height, int money, int playernum) {
this.money = money;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.playernum = playernum;
isPlaying = true;
}
public boolean isPlaying() {
return isPlaying;
}
public void setPlaying(boolean isPlaying) {
this.isPlaying = isPlaying;
}
public int getPlayerNum(){
return playernum;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public ArrayList<Integer> getTieHand() {
//the array this method will return has the first index as the value of the win hand
//aka if bomb then return the numeric value of the bomb
//checks the best win condition of the hand
ArrayList<Integer> tHand = new ArrayList<Integer>();
ArrayList<PlayingCard> cardHand = getHand();
int hand = getWinHand();
String[] suitArr = getSuits();
int[] values = getFaceValues();
int a = 0;
int b = 0;
String suit = "";
switch(hand){
//if its a bomb
case 7:
for(int i = 0; i<values.length-4; i++){
if(values[i] == values[i+1] && values[i+1] == values[i+2] && values[i+2] == values[i+3]){
a = values[i];
break;
}
}
tHand.add(a);
for(int i = values.length-1; i>-1; i--){
if(values[i] != a)
tHand.add(values[i]);
}
return tHand;
//if full house
case 6:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1] && values[i-1] == values[i-2]){
a = values[i];
break;
}
}
tHand.add(a);
for(int i = values.length-1; i>0; i--){
if(values[i] != a && values[i] == values[i-1]){
b = values[i];
break;
}
}
tHand.add(b);
for(int i = values.length-1; i>-1; i--){
if(values[i] != a && values[i] != b)
tHand.add(values[i]);
}
return tHand;
//if flush
case 5:
for(int i = 0; i<suitArr.length-4; i++){
if(suitArr[i].equals(suitArr[i+1]) && suitArr[i+1].equals(suitArr[i+2]) && suitArr[i+2].equals(suitArr[i+3]) && suitArr[i+3].equals(suitArr[i+4]))
suit = suitArr[i];
}
int count = 0;
for(int i = cardHand.size()-1; i>-1; i--){
if(count<5 && cardHand.get(i).getSuit().equals(suit)){
tHand.add(cardHand.get(i).getCardValue());
}
}
for(int i = cardHand.size()-1; i>-1; i--){
if(!cardHand.get(i).getSuit().equals(suit))
tHand.add(cardHand.get(i).getCardValue());
}
return tHand;
//if straight
case 4:
for(int i = values.length-1; i>3; i--){
if(values[i] == values[i-1]+1 && values[i-1] == values[i-2]+1 && values[i-2] == values[i-3]+1 && values[i-3] == values[i-4]+1){
for(int j = 0; j<5; j++){
tHand.add(values[i]-j);
}
}
}
return tHand;
//if triple
case 3:
for(int i = values.length-1; i>2; i--){
if(values[i] == values[i-1] && values[i-1] == values[i-2]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>-1; j--){
if(values[j] != a)
tHand.add(values[j]);
}
return tHand;
//if two pair
case 2:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>1; j--){
if(values[j] != a && values[j] == values[j-1]){
b = values[j];
}
}
tHand.add(b);
for(int k = values.length-1; k>-1; k--){
if(values[k] != a && values[k] != b)
tHand.add(values[k]);
}
return tHand;
//if double
case 1:
for(int i = values.length-1; i>1; i--){
if(values[i] == values[i-1]){
a = values[i];
break;
}
}
tHand.add(a);
for(int j = values.length-1; j>-1; j--){
if(values[j] != a)
tHand.add(values[j]);
}
return tHand;
//if hi card
case 0:
for(int i = values.length-1; i>-1; i--){
tHand.add(values[i]);
}
return tHand;
default: return tHand;
}
}
}
| 4,663 | 0.521767 | 0.504396 | 224 | 18.816965 | 20.86088 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.120536 | false | false | 0 |
ed6ce33d239acd3e96ed5f0d24782eb05ce1cb7d | 15,642,270,938,999 | cca69b02a4cc67064df23f6a669812bdb0769b04 | /src/main/java/top/itlq/algorithms/TopKFrequent.java | 9bb82233706dc340c527e2ac052d03853671bce0 | []
| no_license | dlmu-lq/algorithms | https://github.com/dlmu-lq/algorithms | 6c25d0dcf270f425ccb1023326fce290119516bf | 3811109895fdf6f887c5beaf92f203a0e4873df7 | refs/heads/master | 2020-06-12T23:14:53.405000 | 2020-04-20T12:43:43 | 2020-04-20T12:43:43 | 194,457,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package top.itlq.algorithms;
import java.util.*;
public class TopKFrequent {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num:nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
Map<Integer, List<Integer>> timesValuesMap = new HashMap<>();
for(Map.Entry<Integer, Integer> entry:map.entrySet()){
List<Integer> list = timesValuesMap.get(entry.getValue());
if(list == null){
list = new ArrayList<>();
timesValuesMap.put(entry.getValue(), list);
}
list.add(entry.getKey());
}
Set<Integer> times = timesValuesMap.keySet();
TreeSet<Integer> sortedTimes = new TreeSet<>(Comparator.reverseOrder());
sortedTimes.addAll(times);
List<Integer> re = new ArrayList<>();
for(Integer i:sortedTimes){
if(k-- > 0){
re.addAll(timesValuesMap.get(i));
}
}
return re;
}
public static void main(String[] args) {
System.out.println(new TopKFrequent().topKFrequent(new int[]{
1,1,1,2,2,3
}, 2));
}
} | UTF-8 | Java | 1,226 | java | TopKFrequent.java | Java | []
| null | []
| package top.itlq.algorithms;
import java.util.*;
public class TopKFrequent {
public List<Integer> topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for(int num:nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
Map<Integer, List<Integer>> timesValuesMap = new HashMap<>();
for(Map.Entry<Integer, Integer> entry:map.entrySet()){
List<Integer> list = timesValuesMap.get(entry.getValue());
if(list == null){
list = new ArrayList<>();
timesValuesMap.put(entry.getValue(), list);
}
list.add(entry.getKey());
}
Set<Integer> times = timesValuesMap.keySet();
TreeSet<Integer> sortedTimes = new TreeSet<>(Comparator.reverseOrder());
sortedTimes.addAll(times);
List<Integer> re = new ArrayList<>();
for(Integer i:sortedTimes){
if(k-- > 0){
re.addAll(timesValuesMap.get(i));
}
}
return re;
}
public static void main(String[] args) {
System.out.println(new TopKFrequent().topKFrequent(new int[]{
1,1,1,2,2,3
}, 2));
}
} | 1,226 | 0.544046 | 0.535889 | 38 | 31.289474 | 23.235531 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.763158 | false | false | 0 |
8d5597d58dbc5282ebd896618f415344004deb3e | 26,096,221,344,297 | c4b799c5f554c761f43373d2202b7b923ff246dc | /src/main/java/hotTopic/weiboGrabber/service/OauthService.java | ed66dfbde2c980781bb0225c46cf4095b768339e | []
| no_license | phaedo/weiboGrabber | https://github.com/phaedo/weiboGrabber | 847f1fd9369afcf4e385de801ef958e1f8a648d3 | 12b8b882d5a3c44b0e1df03e0ed24febe2f59e3f | refs/heads/master | 2019-06-16T22:43:08.726000 | 2014-09-21T13:02:57 | 2014-09-21T13:02:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hotTopic.weiboGrabber.service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import hotTopic.weiboGrabber.model.AccessToken;
import hotTopic.weiboGrabber.model.User;
import hotTopic.weiboGrabber.model.WeiboException;
import hotTopic.weiboGrabber.util.HttpUtils;
import hotTopic.weiboGrabber.util.WeiboConfig;
public class OauthService {
/**
* POST user和passwd获取授权后计算code
* @param user
* @param passwd
* @return
* @throws IOException
* @throws InterruptedException
*/
public String getCode(String user, String passwd) throws IOException, InterruptedException {
String code = null;
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("action", "submit");
paramMap.put("client_id", WeiboConfig.getValue("client_ID"));
paramMap.put("redirect_uri", WeiboConfig.getValue("redirect_URI"));
paramMap.put("userId", user);
paramMap.put("passwd", passwd);
Map<String, String> headMap = new HashMap<String, String>();
String refUrl = WeiboConfig.getValue("authorizeURL")
+ "?redirect_uri=" + WeiboConfig.getValue("redirect_URI")
+ "&response_type=code&client_id=" + WeiboConfig.getValue("client_ID");
headMap.put("Referer", refUrl);
headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
String location = HttpUtils.postHeaderFromUrl("https://api.weibo.com/oauth2/authorize", paramMap, headMap)
.get("Location").get(0);
code = location.substring(location.indexOf('=')+1, location.length());
return code;
}
/**
* 利用code获取授权token
* @param code
* @return
* @throws WeiboException
* @throws IOException
*/
public AccessToken getAccessTokenByCode(String code) throws WeiboException, IOException {
String result = null;
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("client_id", WeiboConfig.getValue("client_ID").trim());
paramMap.put("client_secret", WeiboConfig.getValue("client_SERCRET").trim());
paramMap.put("grant_type", "authorization_code");
paramMap.put("code", code);
paramMap.put("redirect_uri", WeiboConfig.getValue("redirect_URI"));
result = HttpUtils.postDataFromUrl(WeiboConfig.getValue("accessTokenURL"), paramMap, null);
return new AccessToken(result);
}
} | UTF-8 | Java | 2,336 | java | OauthService.java | Java | [
{
"context": "mMap.put(\"userId\", user);\n\t\tparamMap.put(\"passwd\", passwd);\n\t\tMap<String, String> headMap = new HashMap<Str",
"end": 939,
"score": 0.9982852339744568,
"start": 933,
"tag": "PASSWORD",
"value": "passwd"
}
]
| null | []
| package hotTopic.weiboGrabber.service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import hotTopic.weiboGrabber.model.AccessToken;
import hotTopic.weiboGrabber.model.User;
import hotTopic.weiboGrabber.model.WeiboException;
import hotTopic.weiboGrabber.util.HttpUtils;
import hotTopic.weiboGrabber.util.WeiboConfig;
public class OauthService {
/**
* POST user和passwd获取授权后计算code
* @param user
* @param passwd
* @return
* @throws IOException
* @throws InterruptedException
*/
public String getCode(String user, String passwd) throws IOException, InterruptedException {
String code = null;
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("action", "submit");
paramMap.put("client_id", WeiboConfig.getValue("client_ID"));
paramMap.put("redirect_uri", WeiboConfig.getValue("redirect_URI"));
paramMap.put("userId", user);
paramMap.put("passwd", <PASSWORD>);
Map<String, String> headMap = new HashMap<String, String>();
String refUrl = WeiboConfig.getValue("authorizeURL")
+ "?redirect_uri=" + WeiboConfig.getValue("redirect_URI")
+ "&response_type=code&client_id=" + WeiboConfig.getValue("client_ID");
headMap.put("Referer", refUrl);
headMap.put("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
String location = HttpUtils.postHeaderFromUrl("https://api.weibo.com/oauth2/authorize", paramMap, headMap)
.get("Location").get(0);
code = location.substring(location.indexOf('=')+1, location.length());
return code;
}
/**
* 利用code获取授权token
* @param code
* @return
* @throws WeiboException
* @throws IOException
*/
public AccessToken getAccessTokenByCode(String code) throws WeiboException, IOException {
String result = null;
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("client_id", WeiboConfig.getValue("client_ID").trim());
paramMap.put("client_secret", WeiboConfig.getValue("client_SERCRET").trim());
paramMap.put("grant_type", "authorization_code");
paramMap.put("code", code);
paramMap.put("redirect_uri", WeiboConfig.getValue("redirect_URI"));
result = HttpUtils.postDataFromUrl(WeiboConfig.getValue("accessTokenURL"), paramMap, null);
return new AccessToken(result);
}
} | 2,340 | 0.726603 | 0.716638 | 61 | 36.852459 | 28.889181 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.508197 | false | false | 0 |
c98c0e585e2caad25f22abcceac8388a6edfe7e4 | 28,913,719,883,172 | 51adf10e05b4a95c35da7c1675b3b31563ee6fbb | /app/src/main/java/examples/android/example/com/firebaseauthentication/adapters/ChatAdapter.java | d900d026a51c62e6087438e343fc4a1bb7c3c715 | []
| no_license | WolfMMD/FireBaseAuthentication-master | https://github.com/WolfMMD/FireBaseAuthentication-master | e0afecfc5869cfdaad6e22b2f2ca42ea01bec5c7 | a5346f05c5b749117acfd35d95390afe0154b94a | refs/heads/master | 2020-08-02T07:20:04.891000 | 2019-07-18T11:55:00 | 2019-07-18T11:55:00 | 211,274,162 | 1 | 0 | null | true | 2019-09-27T08:37:31 | 2019-09-27T08:37:30 | 2019-07-18T11:55:12 | 2019-07-18T11:55:11 | 569 | 0 | 0 | 0 | null | false | false | package examples.android.example.com.firebaseauthentication.adapters;
import android.icu.text.RelativeDateTimeFormatter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import examples.android.example.com.firebaseauthentication.data.Message;
import examples.android.example.com.firebaseauthentication.databinding.RecieverRecyclerItemsBinding;
import examples.android.example.com.firebaseauthentication.databinding.SenderRecyclerItemBinding;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
private List<Message> conversation;
public ChatAdapter(List<Message> conversation) {
this.conversation = conversation;
}
@NonNull
@Override
public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int senderReceiverType) {
if (senderReceiverType == 0) {
SenderRecyclerItemBinding senderRecyclerItemBinding = SenderRecyclerItemBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false);
return new SenderViewHolder(senderRecyclerItemBinding);
} else {
RecieverRecyclerItemsBinding recieverRecyclerItemsBinding = RecieverRecyclerItemsBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false);
return new ReceiverViewHolder(recieverRecyclerItemsBinding);
}
}
@Override
public void onBindViewHolder(@NonNull ChatViewHolder chatViewHolder, int i) {
chatViewHolder.bind(conversation.get(i));
}
@Override
public int getItemCount() {
return conversation.size();
}
@Override
public int getItemViewType(int position) {
return conversation.get(position).getSenderOrReceiverType();
}
abstract class ChatViewHolder extends RecyclerView.ViewHolder {
ChatViewHolder(@NonNull View itemView) {
super(itemView);
}
abstract void bind(Message conversationData);
}
public class SenderViewHolder extends ChatViewHolder {
SenderRecyclerItemBinding binding;
SenderViewHolder(SenderRecyclerItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
@Override
void bind(Message conversationData) {
if (conversationData.getType() == 0)
binding.message.setText(conversationData.getMessageBody());
else
//picasso for the image view
binding.message.setText("image here");
CharSequence ago = DateUtils.getRelativeTimeSpanString(conversationData.getTime().getSeconds() * 1000,
new Date().getTime(), DateUtils.MINUTE_IN_MILLIS);
if (ago.equals("0 minutes ago"))
ago = "just now";
binding.time.setText((ago));
}
}
public class ReceiverViewHolder extends ChatViewHolder {
RecieverRecyclerItemsBinding binding;
ReceiverViewHolder(RecieverRecyclerItemsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
@Override
void bind(Message conversationData) {
if (conversationData.getType() == 0)
binding.message.setText(conversationData.getMessageBody());
else
//picasso for the image view
binding.message.setText("image here");
CharSequence ago = DateUtils.getRelativeTimeSpanString(conversationData.getTime().getSeconds() * 1000, new Date().getTime(), DateUtils.MINUTE_IN_MILLIS);
if (ago.equals("0 minutes ago"))
ago = "just now";
binding.time.setText((ago));
}
}
public void setMessageList(List<Message> messageList) {
conversation.addAll(messageList);
notifyDataSetChanged();
}
}
| UTF-8 | Java | 4,177 | java | ChatAdapter.java | Java | []
| null | []
| package examples.android.example.com.firebaseauthentication.adapters;
import android.icu.text.RelativeDateTimeFormatter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import examples.android.example.com.firebaseauthentication.data.Message;
import examples.android.example.com.firebaseauthentication.databinding.RecieverRecyclerItemsBinding;
import examples.android.example.com.firebaseauthentication.databinding.SenderRecyclerItemBinding;
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ChatViewHolder> {
private List<Message> conversation;
public ChatAdapter(List<Message> conversation) {
this.conversation = conversation;
}
@NonNull
@Override
public ChatViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int senderReceiverType) {
if (senderReceiverType == 0) {
SenderRecyclerItemBinding senderRecyclerItemBinding = SenderRecyclerItemBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false);
return new SenderViewHolder(senderRecyclerItemBinding);
} else {
RecieverRecyclerItemsBinding recieverRecyclerItemsBinding = RecieverRecyclerItemsBinding.inflate(LayoutInflater.from(viewGroup.getContext()), viewGroup, false);
return new ReceiverViewHolder(recieverRecyclerItemsBinding);
}
}
@Override
public void onBindViewHolder(@NonNull ChatViewHolder chatViewHolder, int i) {
chatViewHolder.bind(conversation.get(i));
}
@Override
public int getItemCount() {
return conversation.size();
}
@Override
public int getItemViewType(int position) {
return conversation.get(position).getSenderOrReceiverType();
}
abstract class ChatViewHolder extends RecyclerView.ViewHolder {
ChatViewHolder(@NonNull View itemView) {
super(itemView);
}
abstract void bind(Message conversationData);
}
public class SenderViewHolder extends ChatViewHolder {
SenderRecyclerItemBinding binding;
SenderViewHolder(SenderRecyclerItemBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
@Override
void bind(Message conversationData) {
if (conversationData.getType() == 0)
binding.message.setText(conversationData.getMessageBody());
else
//picasso for the image view
binding.message.setText("image here");
CharSequence ago = DateUtils.getRelativeTimeSpanString(conversationData.getTime().getSeconds() * 1000,
new Date().getTime(), DateUtils.MINUTE_IN_MILLIS);
if (ago.equals("0 minutes ago"))
ago = "just now";
binding.time.setText((ago));
}
}
public class ReceiverViewHolder extends ChatViewHolder {
RecieverRecyclerItemsBinding binding;
ReceiverViewHolder(RecieverRecyclerItemsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
@Override
void bind(Message conversationData) {
if (conversationData.getType() == 0)
binding.message.setText(conversationData.getMessageBody());
else
//picasso for the image view
binding.message.setText("image here");
CharSequence ago = DateUtils.getRelativeTimeSpanString(conversationData.getTime().getSeconds() * 1000, new Date().getTime(), DateUtils.MINUTE_IN_MILLIS);
if (ago.equals("0 minutes ago"))
ago = "just now";
binding.time.setText((ago));
}
}
public void setMessageList(List<Message> messageList) {
conversation.addAll(messageList);
notifyDataSetChanged();
}
}
| 4,177 | 0.682068 | 0.678717 | 143 | 28.209789 | 33.955925 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.384615 | false | false | 0 |
5bab5625fcfcc8128c1c33ed22489df806290ecf | 16,724,602,690,415 | e680843db45c5e834ac94513d3724dda42a52c16 | /nlxr-sms/src/main/java/com/nlxr/sms/haier/SmsRequestBody.java | b5e5f1ad77b53f264274fcac5273dc8e6e3e557b | []
| no_license | nilvxingren/mall | https://github.com/nilvxingren/mall | 6046930c3148d56a26c44552e2cb01240aaf9a9a | 3af4b824cd04ffc6eb5aecd708d22b171040ad0a | refs/heads/master | 2016-04-21T21:35:16.696000 | 2016-03-13T15:13:10 | 2016-03-13T15:13:10 | 52,721,534 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.nlxr.sms.haier;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import lombok.Getter;
import lombok.Setter;
import org.joda.time.DateTime;
import java.util.List;
public class SmsRequestBody {
//默认的日期格式
private static final String DATE_PATTERN = "yyyyMMddHHmmss";
@Getter
@Setter
@XStreamAlias("SendTime")
private String sendTime;
@Getter
@Setter
@XStreamAlias("AppendID")
private String appendId;
@Getter
@Setter
@XStreamImplicit
private List<SmsRequestMessage> messageList;
public SmsRequestBody(List<SmsRequestMessage> messageList) {
this.appendId = "";
this.sendTime = getDateTime();
this.messageList = messageList;
}
public SmsRequestBody(String appendId, List<SmsRequestMessage> messageList) {
this.sendTime = getDateTime();
this.appendId = appendId;
this.messageList = messageList;
}
public SmsRequestBody(String sendTime, String appendId, List<SmsRequestMessage> messageList) {
this.sendTime = sendTime;
this.appendId = appendId;
this.messageList = messageList;
}
private String getDateTime() {
DateTime date = new DateTime();
return date.toString(DATE_PATTERN);
}
}
| UTF-8 | Java | 1,362 | java | SmsRequestBody.java | Java | []
| null | []
| package com.nlxr.sms.haier;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import lombok.Getter;
import lombok.Setter;
import org.joda.time.DateTime;
import java.util.List;
public class SmsRequestBody {
//默认的日期格式
private static final String DATE_PATTERN = "yyyyMMddHHmmss";
@Getter
@Setter
@XStreamAlias("SendTime")
private String sendTime;
@Getter
@Setter
@XStreamAlias("AppendID")
private String appendId;
@Getter
@Setter
@XStreamImplicit
private List<SmsRequestMessage> messageList;
public SmsRequestBody(List<SmsRequestMessage> messageList) {
this.appendId = "";
this.sendTime = getDateTime();
this.messageList = messageList;
}
public SmsRequestBody(String appendId, List<SmsRequestMessage> messageList) {
this.sendTime = getDateTime();
this.appendId = appendId;
this.messageList = messageList;
}
public SmsRequestBody(String sendTime, String appendId, List<SmsRequestMessage> messageList) {
this.sendTime = sendTime;
this.appendId = appendId;
this.messageList = messageList;
}
private String getDateTime() {
DateTime date = new DateTime();
return date.toString(DATE_PATTERN);
}
}
| 1,362 | 0.689169 | 0.689169 | 57 | 22.649122 | 22.448765 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.438596 | false | false | 0 |
ba717dcceb4d8000b91cdc4771d2a63dfedf0276 | 7,911,329,809,999 | 95040d72c2cd4d5f9ab70c50821991a4b7f4460c | /app/src/main/java/edu/kvcc/cis298/cis298assignment4/WineListActivity.java | 4eafa042edc12eaf3de74da6e12f219f69ef1676 | []
| no_license | kylegnally/SodaStandAndroidIntents | https://github.com/kylegnally/SodaStandAndroidIntents | 795056ad11d3d5ce11cb509ea9beaa1af60cdb59 | 0a3ab5fe7bc93793ff922543affede1265bb0b47 | refs/heads/master | 2020-04-13T01:56:39.861000 | 2017-12-10T11:26:31 | 2017-12-10T11:26:31 | 162,887,985 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
CIS298
Kyle Nally
CIS298 ASSIGNMENT 3: WINELIST APPLICATION
This application displays a list of wines, their product IDs, and their prices to a user.
The list is loaded from a CSV which contains the each wine's id, name, pack, price, and
status as active or inactive. The main list display on the first application screen displays
only the name,Id, and price.
Touching any wine on the main screen loads a detail screen, on which the user may edit any of the pieces
of information shown. This information persists on screen rotation, and any changes to the three pieces of
information shown on the main screen are displayed there when the user touches the "back" button on their
device.
Additionally, on the detail page, the user is able to swipe left or right to move to the next item in the
list. If the user presses the back button on their device at any time, the list will be shown at the
location in the list the user was viewing when they first entered the details page.
This application uses a RecyclerView to display the main wine list, fragments to store each list item,
and a ViewPager to handle swipe events on the details pages.
*/
package edu.kvcc.cis298.cis298assignment4;
import android.support.v4.app.Fragment;
/**
* Created by kyleg on 11/9/2017.
*/
public class WineListActivity extends SingleFragmentActivity {
// create a new WineListFragment and return it
@Override
protected Fragment createFragment() {
return new WineListFragment();
}
}
| UTF-8 | Java | 1,504 | java | WineListActivity.java | Java | [
{
"context": "/*\nCIS298\nKyle Nally\nCIS298 ASSIGNMENT 3: WINELIST APPLICATION\n\nThis a",
"end": 20,
"score": 0.9998420476913452,
"start": 10,
"tag": "NAME",
"value": "Kyle Nally"
},
{
"context": "ndroid.support.v4.app.Fragment;\n\n/**\n * Created by kyleg on 11/9/2017.\n */\n\npublic class WineListActivity ",
"end": 1264,
"score": 0.9996544718742371,
"start": 1259,
"tag": "USERNAME",
"value": "kyleg"
}
]
| null | []
| /*
CIS298
<NAME>
CIS298 ASSIGNMENT 3: WINELIST APPLICATION
This application displays a list of wines, their product IDs, and their prices to a user.
The list is loaded from a CSV which contains the each wine's id, name, pack, price, and
status as active or inactive. The main list display on the first application screen displays
only the name,Id, and price.
Touching any wine on the main screen loads a detail screen, on which the user may edit any of the pieces
of information shown. This information persists on screen rotation, and any changes to the three pieces of
information shown on the main screen are displayed there when the user touches the "back" button on their
device.
Additionally, on the detail page, the user is able to swipe left or right to move to the next item in the
list. If the user presses the back button on their device at any time, the list will be shown at the
location in the list the user was viewing when they first entered the details page.
This application uses a RecyclerView to display the main wine list, fragments to store each list item,
and a ViewPager to handle swipe events on the details pages.
*/
package edu.kvcc.cis298.cis298assignment4;
import android.support.v4.app.Fragment;
/**
* Created by kyleg on 11/9/2017.
*/
public class WineListActivity extends SingleFragmentActivity {
// create a new WineListFragment and return it
@Override
protected Fragment createFragment() {
return new WineListFragment();
}
}
| 1,500 | 0.771277 | 0.756649 | 44 | 33.18182 | 39.086891 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.409091 | false | false | 0 |
ddcce345da85d1869a8b3901f126b76b94f25b8b | 20,804,821,633,289 | 5591190509962cac061a5cbd7689a0c10cce6849 | /modernJavaInActionSample/build/benchmarks/benchmarks/sources/chap07/generated/ParallelStreamBenchmark_jmhType.java | 6943a6c64c4edc70b944b423fac49dddad09292f | []
| no_license | khpproud/AndroidStudy-Kotlin- | https://github.com/khpproud/AndroidStudy-Kotlin- | 46e255aad4c84f7fad902f7765aece31ff721eb2 | 23a29ebd532540a4bfe9a1f4b0ce5f4bccabc2f9 | refs/heads/master | 2022-06-27T18:57:12.801000 | 2020-02-02T07:23:14 | 2020-02-02T07:23:14 | 156,101,069 | 0 | 0 | null | false | 2022-06-20T22:41:42 | 2018-11-04T16:19:26 | 2019-07-10T13:19:24 | 2022-06-20T22:41:42 | 22,535 | 0 | 0 | 2 | Kotlin | false | false | package chap07.generated;
public class ParallelStreamBenchmark_jmhType extends ParallelStreamBenchmark_jmhType_B3 {
}
| UTF-8 | Java | 119 | java | ParallelStreamBenchmark_jmhType.java | Java | []
| null | []
| package chap07.generated;
public class ParallelStreamBenchmark_jmhType extends ParallelStreamBenchmark_jmhType_B3 {
}
| 119 | 0.857143 | 0.831933 | 3 | 38.333332 | 37.142368 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
8e4aa9f82d92bf27098df400dffc0913096fb457 | 17,712,445,183,316 | edf3dddd8b04c65ca48533cdba2e7fa40d67dfdb | /src/main/java/ru/netology/domain/ContentPostsInfo.java | 7cc1d0eb04594690d7b56d5d5610737b6d13afa2 | []
| no_license | GrebenkovaMaria/JavaForQA_HW_VK | https://github.com/GrebenkovaMaria/JavaForQA_HW_VK | 7c2adc1bcae90e0e33c8a85268f43248f44c8635 | 2c135bf0b7a641e484ffdf695b9d451437ecc415 | refs/heads/master | 2023-01-18T23:51:17.192000 | 2020-12-06T20:07:03 | 2020-12-06T20:07:03 | 317,986,585 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.netology.domain;
public class ContentPostsInfo {
private String id;
private String postUrl;
private boolean image; // в посте может быть картинка, может отсутствовать
private boolean soundtrack; // в посте может быть звуковая дорожка, может отсутствовать
private boolean quize; // в посте может быть опрос, может отсутствовать
private boolean video;// в посте может быть видео, может отсутствовать
private boolean hashTag; // в посте могут быть хештеги, может отсутствовать
private boolean userMark; // в посте может быть отмечен пользователь, может отсутствовать
private String imageUrl;
private String soundtrackUrl;
private String singerId;
private String quizeUrl;
private String videoUrl;
private String hashtagUrl;
private String text;
private String userMarkUrl; // если boolean userMark true
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPostUrl() {
return postUrl;
}
public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}
public boolean isImage() {
return image;
}
public void setImage(boolean image) {
this.image = image;
}
public boolean isSoundtrack() {
return soundtrack;
}
public void setSoundtrack(boolean soundtrack) {
this.soundtrack = soundtrack;
}
public boolean isQuize() {
return quize;
}
public void setQuize(boolean quize) {
this.quize = quize;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public boolean isHashTag() {
return hashTag;
}
public void setHashTag(boolean hashTag) {
this.hashTag = hashTag;
}
public boolean isUserMark() {
return userMark;
}
public void setUserMark(boolean userMark) {
this.userMark = userMark;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getSoundtrackUrl() {
return soundtrackUrl;
}
public void setSoundtrackUrl(String soundtrackUrl) {
this.soundtrackUrl = soundtrackUrl;
}
public String getSingerId() {
return singerId;
}
public void setSingerId(String singerId) {
this.singerId = singerId;
}
public String getQuizeUrl() {
return quizeUrl;
}
public void setQuizeUrl(String quizeUrl) {
this.quizeUrl = quizeUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public String getHashtagUrl() {
return hashtagUrl;
}
public void setHashtagUrl(String hashtagUrl) {
this.hashtagUrl = hashtagUrl;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUserMarkUrl() {
return userMarkUrl;
}
public void setUserMarkUrl(String userMarkUrl) {
this.userMarkUrl = userMarkUrl;
}
}
| UTF-8 | Java | 3,555 | java | ContentPostsInfo.java | Java | [
{
"context": "erMark(boolean userMark) {\n this.userMark = userMark;\n }\n\n public String getImageUrl() {\n ",
"end": 2012,
"score": 0.8993797898292542,
"start": 2008,
"tag": "NAME",
"value": "user"
},
{
"context": "k(boolean userMark) {\n this.userMark = userMark;\n }\n\n public String getImageUrl() {\n ",
"end": 2016,
"score": 0.5541746616363525,
"start": 2012,
"tag": "NAME",
"value": "Mark"
}
]
| null | []
| package ru.netology.domain;
public class ContentPostsInfo {
private String id;
private String postUrl;
private boolean image; // в посте может быть картинка, может отсутствовать
private boolean soundtrack; // в посте может быть звуковая дорожка, может отсутствовать
private boolean quize; // в посте может быть опрос, может отсутствовать
private boolean video;// в посте может быть видео, может отсутствовать
private boolean hashTag; // в посте могут быть хештеги, может отсутствовать
private boolean userMark; // в посте может быть отмечен пользователь, может отсутствовать
private String imageUrl;
private String soundtrackUrl;
private String singerId;
private String quizeUrl;
private String videoUrl;
private String hashtagUrl;
private String text;
private String userMarkUrl; // если boolean userMark true
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPostUrl() {
return postUrl;
}
public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}
public boolean isImage() {
return image;
}
public void setImage(boolean image) {
this.image = image;
}
public boolean isSoundtrack() {
return soundtrack;
}
public void setSoundtrack(boolean soundtrack) {
this.soundtrack = soundtrack;
}
public boolean isQuize() {
return quize;
}
public void setQuize(boolean quize) {
this.quize = quize;
}
public boolean isVideo() {
return video;
}
public void setVideo(boolean video) {
this.video = video;
}
public boolean isHashTag() {
return hashTag;
}
public void setHashTag(boolean hashTag) {
this.hashTag = hashTag;
}
public boolean isUserMark() {
return userMark;
}
public void setUserMark(boolean userMark) {
this.userMark = userMark;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getSoundtrackUrl() {
return soundtrackUrl;
}
public void setSoundtrackUrl(String soundtrackUrl) {
this.soundtrackUrl = soundtrackUrl;
}
public String getSingerId() {
return singerId;
}
public void setSingerId(String singerId) {
this.singerId = singerId;
}
public String getQuizeUrl() {
return quizeUrl;
}
public void setQuizeUrl(String quizeUrl) {
this.quizeUrl = quizeUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public String getHashtagUrl() {
return hashtagUrl;
}
public void setHashtagUrl(String hashtagUrl) {
this.hashtagUrl = hashtagUrl;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUserMarkUrl() {
return userMarkUrl;
}
public void setUserMarkUrl(String userMarkUrl) {
this.userMarkUrl = userMarkUrl;
}
}
| 3,555 | 0.633576 | 0.633576 | 148 | 21.256756 | 20.53577 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.371622 | false | false | 0 |
72a21ec5d6d1c53d5b39c902fe53cbc15eed0477 | 3,350,074,554,360 | 1b7ebd3409dfca48ef6afc9986d47b744d7cfe84 | /MyEclipse_2017_CI/spring03/src/com/hdquan/servlet/AirportServlet.java | fbbbee3c8a44931fe99efdee3f55b92aa2c4bd22 | []
| no_license | hedingquan/javaForHdquan | https://github.com/hedingquan/javaForHdquan | dc1471702abb2212143cc180a7299c3746605e08 | 971d4877d3bcbfb8ad90644251e36400233d1bd0 | refs/heads/master | 2021-03-07T21:57:29.262000 | 2020-03-10T13:37:33 | 2020-03-10T13:37:33 | 246,299,378 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hdquan.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.hdquan.service.AirportService;
import com.hdquan.service.impl.AirportServiceImpl;
@WebServlet("/airport")
public class AirportServlet extends HttpServlet{
private AirportService airportService;
public void init() throws ServletException {
//对service实例化
// ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//spring和web整合后所有信息都存放在webApplicationContext
ServletContext servletContext = getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
airportService=ac.getBean("airportService",AirportServiceImpl.class);
}
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setAttribute("list",airportService.show());
req.getRequestDispatcher("index.jsp").forward(req, res);
}
}
| UTF-8 | Java | 1,511 | java | AirportServlet.java | Java | []
| null | []
| package com.hdquan.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.hdquan.service.AirportService;
import com.hdquan.service.impl.AirportServiceImpl;
@WebServlet("/airport")
public class AirportServlet extends HttpServlet{
private AirportService airportService;
public void init() throws ServletException {
//对service实例化
// ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
//spring和web整合后所有信息都存放在webApplicationContext
ServletContext servletContext = getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
airportService=ac.getBean("airportService",AirportServiceImpl.class);
}
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setAttribute("list",airportService.show());
req.getRequestDispatcher("index.jsp").forward(req, res);
}
}
| 1,511 | 0.842461 | 0.842461 | 38 | 37.921051 | 29.239826 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.236842 | false | false | 0 |
9f4b893e4eb3e4bab7e572ba625200f1eeef41b9 | 23,665,269,860,338 | 9b005e352e47c774fdc6254a2790eba269cf3714 | /app/src/main/java/com/example/mysteryhunt/HuntSuccess.java | 89bebcf88806f751437e6c5f0619530bda4446ee | []
| no_license | christopherpease/MysteryHunt | https://github.com/christopherpease/MysteryHunt | f3c18d2864370f8a1bf5c11427b859f0b4807e76 | 38e031d06e2c4f63b9083d107f447c886895b94a | refs/heads/master | 2019-01-11T10:33:55.791000 | 2017-12-02T14:40:42 | 2017-12-02T14:40:42 | 74,382,402 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mysteryhunt;
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.TextView;
public class HuntSuccess extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hunt_success);
Intent intent = getIntent();
String huntName = intent.getStringExtra(HuntsList.HUNT_NAME);
TextView textViewName = (TextView) findViewById(R.id.hunt_title);
textViewName.setText(huntName);
}
public void ListButton(View view) {
//Intent intent = new Intent(this, HuntsList.class);
//startActivity(intent);
exit();
}
private void exit() {
Intent intent = new Intent();
intent.putExtra("exit",true);
setResult(RESULT_OK, intent);
finish();
}
}
| UTF-8 | Java | 1,006 | java | HuntSuccess.java | Java | []
| null | []
| package com.example.mysteryhunt;
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.TextView;
public class HuntSuccess extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hunt_success);
Intent intent = getIntent();
String huntName = intent.getStringExtra(HuntsList.HUNT_NAME);
TextView textViewName = (TextView) findViewById(R.id.hunt_title);
textViewName.setText(huntName);
}
public void ListButton(View view) {
//Intent intent = new Intent(this, HuntsList.class);
//startActivity(intent);
exit();
}
private void exit() {
Intent intent = new Intent();
intent.putExtra("exit",true);
setResult(RESULT_OK, intent);
finish();
}
}
| 1,006 | 0.683897 | 0.682903 | 35 | 27.742857 | 21.111057 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.657143 | false | false | 0 |
9d6be38ef3ffdac84c1f4badea68ecd5ef4b8e0e | 23,665,269,860,299 | 7201a64a8f2380d4ec58edfa0f4c3526c9c3b0fe | /app/src/main/java/com/jc/ui/KeyBoardActivity.java | 1a8b53a79cda9c8867756e4c86406994104c9307 | []
| no_license | bsty2015/hsdandroid | https://github.com/bsty2015/hsdandroid | 3a37a729eb025e563e6beb2927dfbff82b7fcb79 | 8f16c356c5be0481e023c49e3a02d6afb51c9776 | refs/heads/master | 2021-01-10T12:54:06.555000 | 2015-11-27T08:01:17 | 2015-11-27T08:01:17 | 46,967,090 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jc.ui;
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.widget.EditText;
/**
* Created by lrh on 18/8/15.
*/
public class KeyBoardActivity extends Activity {
public final static int CodeDelete = -5;
public final static int CodeSpace = -4;
public int index = 0;
private EditText[] inputET = new EditText[6];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.jc.R.layout.keyboard_layout);
inputET[0] = (EditText) findViewById(com.jc.R.id.yz1);
inputET[0].setInputType(InputType.TYPE_NULL);
inputET[1] = (EditText) findViewById(com.jc.R.id.yz2);
inputET[1].setInputType(InputType.TYPE_NULL);
inputET[2] = (EditText) findViewById(com.jc.R.id.yz3);
inputET[2].setInputType(InputType.TYPE_NULL);
inputET[3] = (EditText) findViewById(com.jc.R.id.yz4);
inputET[3].setInputType(InputType.TYPE_NULL);
inputET[4] = (EditText) findViewById(com.jc.R.id.yz5);
inputET[4].setInputType(InputType.TYPE_NULL);
inputET[5] = (EditText) findViewById(com.jc.R.id.yz6);
inputET[5].setInputType(InputType.TYPE_NULL);
Keyboard mKeyboard= new Keyboard(this, com.jc.R.xml.keyboard);
// Lookup the KeyboardView
KeyboardView mKeyboardView= (KeyboardView)findViewById(com.jc.R.id.keyboardview);
// Attach the keyboard to the view
mKeyboardView.setKeyboard(mKeyboard);
mKeyboardView.setPreviewEnabled(false);
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
}
private KeyboardView.OnKeyboardActionListener mOnKeyboardActionListener = new KeyboardView.OnKeyboardActionListener() {
@Override public void onKey(int primaryCode, int[] keyCodes) {
if(primaryCode == CodeSpace){
return;
}
// Handle key
if( primaryCode==CodeDelete ) {
if(index != 0 ){
index--;
}
EditText edittext = (EditText) inputET[index];
Editable editable = edittext.getText();
if( editable!=null ) editable.clear();
} else {// Insert character
if(index == 6){
index = 5;
}
EditText edittext = (EditText) inputET[index];
Editable editable = edittext.getText();
if( editable!=null ) editable.clear();
int start = edittext.getSelectionStart();
editable.insert(start, Character.toString((char) primaryCode));
index++;
}
}
@Override public void onPress(int arg0) {
}
@Override public void onRelease(int primaryCode) {
}
@Override public void onText(CharSequence text) {
}
@Override public void swipeDown() {
}
@Override public void swipeLeft() {
}
@Override public void swipeRight() {
}
@Override public void swipeUp() {
}
};
}
| UTF-8 | Java | 3,314 | java | KeyBoardActivity.java | Java | [
{
"context": "import android.widget.EditText;\n\n/**\n * Created by lrh on 18/8/15.\n */\npublic class KeyBoardActivity ext",
"end": 282,
"score": 0.9996086359024048,
"start": 279,
"tag": "USERNAME",
"value": "lrh"
}
]
| null | []
| package com.jc.ui;
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.widget.EditText;
/**
* Created by lrh on 18/8/15.
*/
public class KeyBoardActivity extends Activity {
public final static int CodeDelete = -5;
public final static int CodeSpace = -4;
public int index = 0;
private EditText[] inputET = new EditText[6];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.jc.R.layout.keyboard_layout);
inputET[0] = (EditText) findViewById(com.jc.R.id.yz1);
inputET[0].setInputType(InputType.TYPE_NULL);
inputET[1] = (EditText) findViewById(com.jc.R.id.yz2);
inputET[1].setInputType(InputType.TYPE_NULL);
inputET[2] = (EditText) findViewById(com.jc.R.id.yz3);
inputET[2].setInputType(InputType.TYPE_NULL);
inputET[3] = (EditText) findViewById(com.jc.R.id.yz4);
inputET[3].setInputType(InputType.TYPE_NULL);
inputET[4] = (EditText) findViewById(com.jc.R.id.yz5);
inputET[4].setInputType(InputType.TYPE_NULL);
inputET[5] = (EditText) findViewById(com.jc.R.id.yz6);
inputET[5].setInputType(InputType.TYPE_NULL);
Keyboard mKeyboard= new Keyboard(this, com.jc.R.xml.keyboard);
// Lookup the KeyboardView
KeyboardView mKeyboardView= (KeyboardView)findViewById(com.jc.R.id.keyboardview);
// Attach the keyboard to the view
mKeyboardView.setKeyboard(mKeyboard);
mKeyboardView.setPreviewEnabled(false);
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
}
private KeyboardView.OnKeyboardActionListener mOnKeyboardActionListener = new KeyboardView.OnKeyboardActionListener() {
@Override public void onKey(int primaryCode, int[] keyCodes) {
if(primaryCode == CodeSpace){
return;
}
// Handle key
if( primaryCode==CodeDelete ) {
if(index != 0 ){
index--;
}
EditText edittext = (EditText) inputET[index];
Editable editable = edittext.getText();
if( editable!=null ) editable.clear();
} else {// Insert character
if(index == 6){
index = 5;
}
EditText edittext = (EditText) inputET[index];
Editable editable = edittext.getText();
if( editable!=null ) editable.clear();
int start = edittext.getSelectionStart();
editable.insert(start, Character.toString((char) primaryCode));
index++;
}
}
@Override public void onPress(int arg0) {
}
@Override public void onRelease(int primaryCode) {
}
@Override public void onText(CharSequence text) {
}
@Override public void swipeDown() {
}
@Override public void swipeLeft() {
}
@Override public void swipeRight() {
}
@Override public void swipeUp() {
}
};
}
| 3,314 | 0.608027 | 0.598672 | 103 | 31.174757 | 26.037848 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456311 | false | false | 0 |
0e2810a25a91ace708567017b164d4cbb0eebfe6 | 22,651,657,581,150 | c1844a783533bb58c6b8345fe438415d4aae8c9b | /mystylezxcamera/src/main/java/com/example/mystylezxcamera/MainActivity.java | 170b01b967dabe107c8d08083efa4e88c4019941 | []
| no_license | HWJson/MyDemoCamera | https://github.com/HWJson/MyDemoCamera | 5579e84da6986d96b8c910199c0c4d194c919642 | 5556738219bbbe1b9b7fbe55202aa98ae02093e9 | refs/heads/master | 2020-03-16T21:26:19.980000 | 2018-05-11T06:34:08 | 2018-05-11T06:34:08 | 132,998,959 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.mystylezxcamera;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_scanner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_scanner= findViewById(R.id.btn_scanner);
btn_scanner.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_scanner: //扫一扫
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
//权限还没有授予 ,需要这里写申请权限的代码
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},60);
}else{ //权限授予,直接写要执行的相应方法
}
break;
}
}
}
| UTF-8 | Java | 1,352 | java | MainActivity.java | Java | []
| null | []
| package com.example.mystylezxcamera;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button btn_scanner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_scanner= findViewById(R.id.btn_scanner);
btn_scanner.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_scanner: //扫一扫
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
//权限还没有授予 ,需要这里写申请权限的代码
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},60);
}else{ //权限授予,直接写要执行的相应方法
}
break;
}
}
}
| 1,352 | 0.652276 | 0.648352 | 43 | 28.627907 | 24.375954 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44186 | false | false | 0 |
43ff2a62860f8c7993041d0f71654b7beee6af90 | 19,447,611,983,573 | 916bd5bef0a86cb34663d6295c9db07131f2b92d | /SiteMonitor/Sources/ru/demax/sitemonitor/Selenium.java | 4e12b869f3b20688cd34789707d56fe365984401 | []
| no_license | plotters/website-monitor-demo | https://github.com/plotters/website-monitor-demo | 371871c05d865b9cfb112a87761ae1134b94debf | 9d8faefd5d36696d2db02fcd9396c5c89de29803 | refs/heads/master | 2021-01-25T08:28:26.059000 | 2009-06-16T15:00:11 | 2009-06-16T15:00:11 | 32,231,069 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.demax.sitemonitor;
import ru.demax.sitemonitor.checking.WebsiteChecker;
import ru.demax.sitemonitor.model.Website;
import com.webobjects.appserver.WOActionResults;
import com.webobjects.appserver.WORequest;
import er.selenium.SeleniumAction;
public class Selenium extends SeleniumAction {
public Selenium(WORequest request) {
super(request);
}
public WOActionResults cleanupAction() {
new WebsiteBuilder().cleanup();
return success();
}
public WOActionResults createExampleWebsiteAction() {
new WebsiteBuilder().build();
return success();
}
public WOActionResults listWithExampleWebsiteAction() {
new WebsiteBuilder().build();
return Factory.smFactory().listWebsites(session());
}
public WOActionResults checkSiteWithRedirectAction() {
Website website = new WebsiteBuilder().withUrl("http://apple.com").build();
return new WebsiteChecker().check(session(), website);
}
}
| UTF-8 | Java | 934 | java | Selenium.java | Java | []
| null | []
| package ru.demax.sitemonitor;
import ru.demax.sitemonitor.checking.WebsiteChecker;
import ru.demax.sitemonitor.model.Website;
import com.webobjects.appserver.WOActionResults;
import com.webobjects.appserver.WORequest;
import er.selenium.SeleniumAction;
public class Selenium extends SeleniumAction {
public Selenium(WORequest request) {
super(request);
}
public WOActionResults cleanupAction() {
new WebsiteBuilder().cleanup();
return success();
}
public WOActionResults createExampleWebsiteAction() {
new WebsiteBuilder().build();
return success();
}
public WOActionResults listWithExampleWebsiteAction() {
new WebsiteBuilder().build();
return Factory.smFactory().listWebsites(session());
}
public WOActionResults checkSiteWithRedirectAction() {
Website website = new WebsiteBuilder().withUrl("http://apple.com").build();
return new WebsiteChecker().check(session(), website);
}
}
| 934 | 0.759101 | 0.759101 | 40 | 22.35 | 22.765709 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.375 | false | false | 0 |
1ed3d313c4a2aa206d8a7ddb3d6864d4f22d4841 | 28,321,014,351,317 | 1b190785f08f9d1af9e28ea750d85c87b1a55724 | /src/main/java/com/common/web/interceptor/CommonInterceptor.java | faf637bea39e5172afa1d0e7e292b374fe0f64c1 | []
| no_license | shilun/common | https://github.com/shilun/common | 60a06328963e8b70930eccbd275e6060f37e77e3 | 174ab56baedc7da07a5982011d0be6134d601c84 | refs/heads/1.1.4 | 2022-08-20T08:52:46.753000 | 2018-08-17T10:56:11 | 2018-08-17T10:56:11 | 143,596,062 | 1 | 1 | null | false | 2022-06-25T07:28:15 | 2018-08-05T08:29:30 | 2019-11-09T09:44:39 | 2022-06-25T07:28:13 | 445 | 1 | 1 | 6 | Java | false | false | //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.common.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class CommonInterceptor implements HandlerInterceptor {
private Logger log = Logger.getLogger(CommonInterceptor.class);
public CommonInterceptor() {
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
| UTF-8 | Java | 1,005 | java | CommonInterceptor.java | Java | []
| null | []
| //
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.common.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class CommonInterceptor implements HandlerInterceptor {
private Logger log = Logger.getLogger(CommonInterceptor.class);
public CommonInterceptor() {
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
| 1,005 | 0.79204 | 0.791045 | 29 | 33.655174 | 41.283108 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.551724 | false | false | 0 |
64a641fc2d5268e054bc404c389b16dad9b4a39f | 23,304,492,610,936 | c7ff12cd085f7a9860641bf959d24a58407083e8 | /src/main/java/nau/bachelor/diploma/zaka/core/view/button/OvalButton.java | 0120645bb0641f777789ac530e0293c56df5f0de | []
| no_license | bito4ek/zaka-diploma | https://github.com/bito4ek/zaka-diploma | 7de49269b770e9992d853fcc672b048a8fdf0160 | 7994171e27714a6466ef0dbea92eabfde5b6a160 | refs/heads/master | 2016-09-08T16:39:50.540000 | 2015-02-17T20:01:00 | 2015-02-17T20:01:00 | 30,160,334 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nau.bachelor.diploma.zaka.core.view.button;
import nau.bachelor.diploma.zaka.core.pattern.command.Shape;
import nau.bachelor.diploma.zaka.core.pattern.command.shapes.Oval;
import nau.bachelor.diploma.zaka.core.util.MessageConstants;
import nau.bachelor.diploma.zaka.core.util.ResourceUtil;
import javax.swing.*;
import java.awt.*;
/**
* File {@link OvalButton}
* Created date 02.02.15 23:48.
*
* @author Artem Telizhenko
*/
public class OvalButton extends AbstractButton {
public OvalButton(ImageIcon icon, JPanel panel) {
super(icon, panel);
}
/**
* Creates a button with no set text or icon.
*/
public OvalButton() {
super();
}
@Override
public Shape getShape(Graphics graphics) {
return new Oval(graphics, 120, 80, 120, 150);
}
@Override
public String getShapeText() {
return ResourceUtil.getMessage(MessageConstants.OVAL_TEXT);
}
}
| UTF-8 | Java | 942 | java | OvalButton.java | Java | [
{
"context": "ton}\n * Created date 02.02.15 23:48.\n *\n * @author Artem Telizhenko\n */\npublic class OvalButton extends AbstractButto",
"end": 435,
"score": 0.9998367428779602,
"start": 419,
"tag": "NAME",
"value": "Artem Telizhenko"
}
]
| null | []
| package nau.bachelor.diploma.zaka.core.view.button;
import nau.bachelor.diploma.zaka.core.pattern.command.Shape;
import nau.bachelor.diploma.zaka.core.pattern.command.shapes.Oval;
import nau.bachelor.diploma.zaka.core.util.MessageConstants;
import nau.bachelor.diploma.zaka.core.util.ResourceUtil;
import javax.swing.*;
import java.awt.*;
/**
* File {@link OvalButton}
* Created date 02.02.15 23:48.
*
* @author <NAME>
*/
public class OvalButton extends AbstractButton {
public OvalButton(ImageIcon icon, JPanel panel) {
super(icon, panel);
}
/**
* Creates a button with no set text or icon.
*/
public OvalButton() {
super();
}
@Override
public Shape getShape(Graphics graphics) {
return new Oval(graphics, 120, 80, 120, 150);
}
@Override
public String getShapeText() {
return ResourceUtil.getMessage(MessageConstants.OVAL_TEXT);
}
}
| 932 | 0.687898 | 0.665605 | 39 | 23.153847 | 22.514427 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.435897 | false | false | 0 |
ad9068823d55df03bb28b7c4035c0ccf5fdc999d | 26,963,804,700,944 | ef95f5da61bb4196ca99e2ebe8f60fb49e73eb27 | /Cap4_Joyce/src/Excercise2/Billing.java | 48c6d222a2dc917a3c945a053f4d7af5340186e7 | []
| no_license | Felipesorsilv/Capitulo-4-Joyce | https://github.com/Felipesorsilv/Capitulo-4-Joyce | 4be01b6d1e80e8b7f57002b0f0f8734d5af13367 | 05e9851661faef5479f38d5551a697d55c5c242f | refs/heads/main | 2023-03-17T08:24:54.767000 | 2021-03-01T20:03:22 | 2021-03-01T20:03:22 | 342,984,180 | 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 Excercise2;
/**
*
* @author felipe
*/
public class Billing {
public static double computeBill(int a){
return ((a*.08 + a)) ;
}
public static double computeBill(int a, int b){
return ((a*b) + (a*.08 + a)) ;
}
public static double computeBill(int a, int b, int c){
return ((a*b)*(c*.5)+ (a*.08 + a) ) ;
}
public static void main(String[] args) {
System.out.println(computeBill(3));
System.out.println(computeBill(3,4));
System.out.println(computeBill(3,4,3));
}
}
| UTF-8 | Java | 796 | java | Billing.java | Java | [
{
"context": ".\r\n */\r\npackage Excercise2;\r\n\r\n/**\r\n *\r\n * @author felipe\r\n */\r\npublic class Billing {\r\n \r\n public s",
"end": 239,
"score": 0.8189888000488281,
"start": 233,
"tag": "NAME",
"value": "felipe"
}
]
| 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 Excercise2;
/**
*
* @author felipe
*/
public class Billing {
public static double computeBill(int a){
return ((a*.08 + a)) ;
}
public static double computeBill(int a, int b){
return ((a*b) + (a*.08 + a)) ;
}
public static double computeBill(int a, int b, int c){
return ((a*b)*(c*.5)+ (a*.08 + a) ) ;
}
public static void main(String[] args) {
System.out.println(computeBill(3));
System.out.println(computeBill(3,4));
System.out.println(computeBill(3,4,3));
}
}
| 796 | 0.562814 | 0.545226 | 31 | 23.67742 | 22.291887 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false | 0 |
0d9db17632564eedfc88c51c7bb5081f8a850b78 | 31,696,858,706,581 | b481557b5d0e85a057195d8e2ed85555aaf6b4e7 | /src/main/java/com/jlee/leetcodesolutions/LeetCode0101.java | 4871a3e8b50c8eb8039814744fefeee4a2ce94ac | []
| no_license | jlee301/leetcodesolutions | https://github.com/jlee301/leetcodesolutions | b9c61d7fbe96bcb138a2727b69b3a39bbe153911 | 788ac8c1c95eb78eda27b21ecb7b29eea1c7b5a4 | refs/heads/master | 2021-06-05T12:27:42.795000 | 2019-08-11T23:04:07 | 2019-08-11T23:04:07 | 113,272,040 | 0 | 1 | null | false | 2020-10-12T23:39:27 | 2017-12-06T05:16:39 | 2019-08-11T23:04:17 | 2020-10-12T23:39:26 | 2,957 | 0 | 1 | 1 | Java | false | false | package com.jlee.leetcodesolutions;
import com.jlee.leetcodesolutions.TreeNode;
public class LeetCode0101 {
/*
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric
* around its center).
*
* Input: [1,2,2,3,4,4,3]
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
* Output: true
*
* Input: [1,2,2,null,3,null,3]
* 1
* / \
* 2 2
* \ \
* 3 3
*
* Output: false
*
* https://leetcode.com/problems/symmetric-tree/description/
*/
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode node1, TreeNode node2) {
if(node1 == null && node2 == null)
return true;
else if(node1 == null || node2 == null)
return false;
else
return node1.val == node2.val && isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left);
}
}
| UTF-8 | Java | 1,011 | java | LeetCode0101.java | Java | []
| null | []
| package com.jlee.leetcodesolutions;
import com.jlee.leetcodesolutions.TreeNode;
public class LeetCode0101 {
/*
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric
* around its center).
*
* Input: [1,2,2,3,4,4,3]
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
* Output: true
*
* Input: [1,2,2,null,3,null,3]
* 1
* / \
* 2 2
* \ \
* 3 3
*
* Output: false
*
* https://leetcode.com/problems/symmetric-tree/description/
*/
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode node1, TreeNode node2) {
if(node1 == null && node2 == null)
return true;
else if(node1 == null || node2 == null)
return false;
else
return node1.val == node2.val && isSymmetric(node1.left, node2.right) && isSymmetric(node1.right, node2.left);
}
}
| 1,011 | 0.56182 | 0.522255 | 44 | 21.977272 | 23.372953 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.613636 | false | false | 0 |
866aa7171d665ffdb6a807fcb6e1c6d7666a2171 | 29,515,015,321,831 | db04601e7850a0fa3365acc4cc76d73aa0b99f49 | /src/dao/general/DaoDatoDeportivo.java | 6b145f335ac2c577c19092d2720d674f178be3df | []
| no_license | Competencias/fundalara | https://github.com/Competencias/fundalara | 132288afdb129b391f5a2bb0014cde4afbe4616a | 8140503145c846c5a4c656e151fbdbc71e7c4af5 | refs/heads/master | 2020-05-29T11:02:01.014000 | 2012-02-16T18:05:45 | 2012-02-16T18:05:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao.general;
import dao.generico.GenericDao;
public class DaoDatoDeportivo extends GenericDao {
}
| UTF-8 | Java | 116 | java | DaoDatoDeportivo.java | Java | []
| null | []
| package dao.general;
import dao.generico.GenericDao;
public class DaoDatoDeportivo extends GenericDao {
}
| 116 | 0.758621 | 0.758621 | 7 | 14.571428 | 18.42248 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.285714 | false | false | 0 |
30d50f940624ecba1f59be0844b3a87715b2d499 | 29,042,568,893,576 | 85a4a746a8f2541fd4c40e96d6457a5015ede24b | /src/main/java/info/velial/support/dao/ProviderDAO.java | 40d58803b6a461546997aaa8afec8ebf81dfde3c | []
| no_license | velial/ContactManager | https://github.com/velial/ContactManager | 3b5e2be32a3726a1d0124bd491c07aa86214924e | 9ccd1fd10335e85f553b2e0842050bf2c62c4746 | refs/heads/master | 2016-09-06T07:16:33.965000 | 2014-10-03T16:26:53 | 2014-10-03T16:26:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package info.velial.support.dao;
import info.velial.support.domain.Provider;
import java.util.List;
/**
* Created by Igor on 20.03.2014.
*/
public interface ProviderDAO {
public List<Provider> providersList();
public Provider getProviderById(Integer providerId);
}
| UTF-8 | Java | 280 | java | ProviderDAO.java | Java | [
{
"context": "ovider;\n\nimport java.util.List;\n\n/**\n * Created by Igor on 20.03.2014.\n */\npublic interface ProviderDAO {",
"end": 125,
"score": 0.986910879611969,
"start": 121,
"tag": "NAME",
"value": "Igor"
}
]
| null | []
| package info.velial.support.dao;
import info.velial.support.domain.Provider;
import java.util.List;
/**
* Created by Igor on 20.03.2014.
*/
public interface ProviderDAO {
public List<Provider> providersList();
public Provider getProviderById(Integer providerId);
}
| 280 | 0.742857 | 0.714286 | 15 | 17.666666 | 19.293062 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 0 |
e495448898905ce556b8f93ef6538d064bf63122 | 5,738,076,359,496 | d86782037a6ef1d7efef59bb47e9203ccb1de420 | /src/com/algorithm/技巧和数学/链表随机节点.java | abfc70ffd2fd52e6ef290060e1b6f21968524122 | []
| no_license | a8520238/algorithm_catogory | https://github.com/a8520238/algorithm_catogory | 31538cba2aa2066118fd6b899e95e23e53a30977 | 00370a97df3d7cfdbef3e4485dfdcfbcf0027b8a | refs/heads/main | 2023-03-06T11:38:59.115000 | 2021-02-14T02:09:12 | 2021-02-14T02:09:12 | 329,965,683 | 0 | 0 | null | false | 2021-01-16T07:03:29 | 2021-01-15T16:31:22 | 2021-01-16T06:59:21 | 2021-01-16T07:03:29 | 390 | 0 | 0 | 0 | Java | false | false | package com.algorithm.技巧和数学;
import java.util.Random;
/*
* 给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
solution.getRandom();
* */
public class 链表随机节点 {
ListNode head;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public 链表随机节点(ListNode head) {
this.head = head;
}
/** Returns a random node's value. */
public int getRandom() {
Random r = new Random();
int res = 0;
int index = 0;
ListNode cur = head;
while (cur != null) {
//洗牌算法,第一个数为1,每次有1/i的概率替换,r.nextInt(++index) == 0即为1/i.
//最后总的概率,(此时 1 被保留的概率为 1 * 1/2 * 2/3 * ... * (n-1)/n
if (r.nextInt(++index) == 0) {
res = cur.val;
}
cur = cur.next;
}
return res;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
} | UTF-8 | Java | 1,563 | java | 链表随机节点.java | Java | []
| null | []
| package com.algorithm.技巧和数学;
import java.util.Random;
/*
* 给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
solution.getRandom();
* */
public class 链表随机节点 {
ListNode head;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public 链表随机节点(ListNode head) {
this.head = head;
}
/** Returns a random node's value. */
public int getRandom() {
Random r = new Random();
int res = 0;
int index = 0;
ListNode cur = head;
while (cur != null) {
//洗牌算法,第一个数为1,每次有1/i的概率替换,r.nextInt(++index) == 0即为1/i.
//最后总的概率,(此时 1 被保留的概率为 1 * 1/2 * 2/3 * ... * (n-1)/n
if (r.nextInt(++index) == 0) {
res = cur.val;
}
cur = cur.next;
}
return res;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
} | 1,563 | 0.57651 | 0.557486 | 52 | 22.26923 | 19.239498 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.461538 | false | false | 0 |
c00053f3e7176a4c5889d85a6b2d9c5549bb738b | 6,717,328,912,137 | c185d1dfa498825d0761bcaa9dac2c9d6dadca1d | /src/library/daos/MemberMapDAO.java | 1ea1969c9a48b6ce5127a4729400c6368fb2ff77 | []
| no_license | KieranGlazier/ITC205_Dynamic_Testing | https://github.com/KieranGlazier/ITC205_Dynamic_Testing | 9af97c1f8dff1d38720776fd12d9041b5f955caf | 18b76fc33babb8c8f63c540aad7b2e4a2b1993a1 | refs/heads/master | 2018-12-29T01:59:13.695000 | 2015-10-05T00:19:55 | 2015-10-05T00:19:55 | 42,418,003 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package library.daos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import library.interfaces.daos.IMemberDAO;
import library.interfaces.daos.IMemberHelper;
import library.interfaces.entities.IMember;
public class MemberMapDAO implements IMemberDAO {
private Map<Integer, IMember> memberMap_;
private int nextID_;
private IMemberHelper helper_;
public MemberMapDAO(IMemberHelper helper) throws IllegalArgumentException {
if (helper == null) {
throw new IllegalArgumentException("Helper cannot be null");
} else {
memberMap_ = new HashMap<Integer, IMember>();
nextID_ = 1;
helper_ = helper;
}
}
public MemberMapDAO(IMemberHelper helper, Map<Integer,IMember> memberMap) throws IllegalArgumentException {
if (helper == null) {
throw new IllegalArgumentException("Helper cannot be null");
} else {
memberMap_ = memberMap;
nextID_ = memberMap.size() + 1;
helper_ = helper;
}
}
@Override
public IMember addMember(String firstName, String lastName, String contactPhone, String emailAddress) {
IMember member = helper_.makeMember(firstName, lastName, contactPhone, emailAddress, nextID_);
memberMap_.put(nextID_, member);
getNextID();
return member;
}
@Override
public IMember getMemberByID(int id) {
if (memberMap_.containsKey(id)) {
return memberMap_.get(id);
} else {
return null;
}
}
@Override
public List<IMember> listMembers() {
return new ArrayList<IMember>(memberMap_.values());
}
@Override
public List<IMember> findMembersByLastName(String lastName) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
// IMember member = memberMap_.get(i);
if (member.getLastName().toLowerCase().matches(lastName.toLowerCase())) {
members.add(member);
}
}
return members;
}
@Override
public List<IMember> findMembersByEmailAddress(String emailAddress) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
//IMember member = memberMap_.get(i);
if (member.getEmailAddress().toLowerCase().matches(emailAddress.toLowerCase())) {
members.add(member);
}
}
return members;
}
@Override
public List<IMember> findMembersByNames(String firstName, String lastName) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
//IMember member = memberMap_.get(i);
if (member.getLastName().toLowerCase().matches(lastName.toLowerCase())
&& member.getFirstName().toLowerCase().matches(firstName.toLowerCase())) {
members.add(member);
}
}
return members;
}
private int getNextID() {
nextID_ = memberMap_.size() + 1;
return nextID_;
}
}
| UTF-8 | Java | 2,886 | java | MemberMapDAO.java | Java | []
| null | []
| package library.daos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import library.interfaces.daos.IMemberDAO;
import library.interfaces.daos.IMemberHelper;
import library.interfaces.entities.IMember;
public class MemberMapDAO implements IMemberDAO {
private Map<Integer, IMember> memberMap_;
private int nextID_;
private IMemberHelper helper_;
public MemberMapDAO(IMemberHelper helper) throws IllegalArgumentException {
if (helper == null) {
throw new IllegalArgumentException("Helper cannot be null");
} else {
memberMap_ = new HashMap<Integer, IMember>();
nextID_ = 1;
helper_ = helper;
}
}
public MemberMapDAO(IMemberHelper helper, Map<Integer,IMember> memberMap) throws IllegalArgumentException {
if (helper == null) {
throw new IllegalArgumentException("Helper cannot be null");
} else {
memberMap_ = memberMap;
nextID_ = memberMap.size() + 1;
helper_ = helper;
}
}
@Override
public IMember addMember(String firstName, String lastName, String contactPhone, String emailAddress) {
IMember member = helper_.makeMember(firstName, lastName, contactPhone, emailAddress, nextID_);
memberMap_.put(nextID_, member);
getNextID();
return member;
}
@Override
public IMember getMemberByID(int id) {
if (memberMap_.containsKey(id)) {
return memberMap_.get(id);
} else {
return null;
}
}
@Override
public List<IMember> listMembers() {
return new ArrayList<IMember>(memberMap_.values());
}
@Override
public List<IMember> findMembersByLastName(String lastName) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
// IMember member = memberMap_.get(i);
if (member.getLastName().toLowerCase().matches(lastName.toLowerCase())) {
members.add(member);
}
}
return members;
}
@Override
public List<IMember> findMembersByEmailAddress(String emailAddress) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
//IMember member = memberMap_.get(i);
if (member.getEmailAddress().toLowerCase().matches(emailAddress.toLowerCase())) {
members.add(member);
}
}
return members;
}
@Override
public List<IMember> findMembersByNames(String firstName, String lastName) {
List<IMember> members = new ArrayList<>();
//for (int i = 0; i < memberMap_.size(); i++) {
for (IMember member : memberMap_.values()) {
//IMember member = memberMap_.get(i);
if (member.getLastName().toLowerCase().matches(lastName.toLowerCase())
&& member.getFirstName().toLowerCase().matches(firstName.toLowerCase())) {
members.add(member);
}
}
return members;
}
private int getNextID() {
nextID_ = memberMap_.size() + 1;
return nextID_;
}
}
| 2,886 | 0.697505 | 0.695426 | 105 | 26.485714 | 25.971821 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.152381 | false | false | 0 |
4429148f17152d4d774d046f1fbbb902d8331620 | 22,574,348,175,315 | 688fb62a620014d9f198f8c843f16329671776ae | /src/main/java/org/fundacionjala/pivotal/pages/project/DeleteProjectAlert.java | a3a2dd2073ccd8184643cca39cb4519c78bf1f08 | []
| no_license | SeleniumCourse/pivotal-ui-test-team2 | https://github.com/SeleniumCourse/pivotal-ui-test-team2 | 9769a534d9d7f5db540ebac1c543e5170bb0d964 | 113bf484a670e632a8741d164c913d8cb6e91b5b | refs/heads/develop | 2021-06-14T12:24:24.027000 | 2017-05-06T14:53:37 | 2017-05-06T14:53:37 | 62,178,899 | 0 | 11 | null | false | 2017-05-06T14:53:38 | 2016-06-28T22:41:20 | 2017-04-03T01:29:28 | 2017-05-06T14:53:38 | 9,233 | 0 | 11 | 0 | Java | null | null | package org.fundacionjala.pivotal.pages.project;
import org.fundacionjala.pivotal.pages.BasePage;
import org.fundacionjala.pivotal.pages.dashboard.Dashboard;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import static org.fundacionjala.pivotal.framework.util.CommonMethods.clickWebElement;
/**
* Class that lets us confirm the deletion
* of the project on the browser popup.
*/
public class DeleteProjectAlert extends BasePage {
@FindBy(css = ".delete.inline_dialog")
private WebElement deleteAlertContainer;
@FindBy(id = "confirm_delete")
private WebElement deleteProjectBtn;
/**
* Method that clicks the delete button inside the
* project delete container.
*
* @return the Dashboard instance
*/
public Dashboard confirmDeleteProject() {
wait.until(ExpectedConditions.visibilityOf(deleteAlertContainer));
clickWebElement(deleteProjectBtn);
return new Dashboard();
}
}
| UTF-8 | Java | 1,049 | java | DeleteProjectAlert.java | Java | []
| null | []
| package org.fundacionjala.pivotal.pages.project;
import org.fundacionjala.pivotal.pages.BasePage;
import org.fundacionjala.pivotal.pages.dashboard.Dashboard;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import static org.fundacionjala.pivotal.framework.util.CommonMethods.clickWebElement;
/**
* Class that lets us confirm the deletion
* of the project on the browser popup.
*/
public class DeleteProjectAlert extends BasePage {
@FindBy(css = ".delete.inline_dialog")
private WebElement deleteAlertContainer;
@FindBy(id = "confirm_delete")
private WebElement deleteProjectBtn;
/**
* Method that clicks the delete button inside the
* project delete container.
*
* @return the Dashboard instance
*/
public Dashboard confirmDeleteProject() {
wait.until(ExpectedConditions.visibilityOf(deleteAlertContainer));
clickWebElement(deleteProjectBtn);
return new Dashboard();
}
}
| 1,049 | 0.749285 | 0.749285 | 34 | 29.852942 | 23.901922 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 4 |
73f881cc38f2e6a3df84dbb2a945be472a1af9e8 | 10,685,878,696,184 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /data/libgdx/Body_getWorldPointToOut.java | 6abc82f71be302570c40d2fad12b03c1506d6695 | []
| no_license | GabeOchieng/ggnn.tensorflow | https://github.com/GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278000 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public final void getWorldPointToOut(Vec2 localPoint, Vec2 out) {
Transform.mulToOut(m_xf, localPoint, out);
}
| UTF-8 | Java | 115 | java | Body_getWorldPointToOut.java | Java | []
| null | []
| public final void getWorldPointToOut(Vec2 localPoint, Vec2 out) {
Transform.mulToOut(m_xf, localPoint, out);
}
| 115 | 0.756522 | 0.73913 | 3 | 37.333332 | 26.836956 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 4 |
6f1a29de3b08ec008a3f4a065440929e0849b299 | 17,609,365,962,643 | 33ac45a3be157a1d6c4638d344aef4a9309740ca | /Gladiaattoripeli/src/gladiaattoripeli/domain/Hirvio.java | c23b3cd3944ec624c658b37ed6dbb3baefb64368 | []
| no_license | emleri/Javalabra | https://github.com/emleri/Javalabra | ce8bf3b17b24f7569bf6425ad561dc3c902d0777 | 9992c1557a42d6fd67ebc664a515b9762115f57e | refs/heads/master | 2021-01-10T21:42:05.226000 | 2013-02-22T19:55:38 | 2013-02-22T19:55:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gladiaattoripeli.domain;
import gladiaattoripeli.utilities.Pelitilanne;
/**
* Pelin vastustajia kuvaava luokka, joka laajentaa Hahmon toiminnallisuutta.
* Luokka lisää hahmolle tekoälyn, joka ohjaa sitä taistelemaan gladiaattoria
* vastaan.
*/
public class Hirvio extends Hahmo {
/**
* Konstruktori välittää vain parametrit eteenpäin yläluokan
* konstruktorille.
*
* @param osumapisteet hirviön osumapisteet
* @param keho viite hirviölle annettavaan kehoon
* @param ase viite hirviölle annettavaan aseeseen
*/
public Hirvio(int osumapisteet, Keho keho, Ase ase) {
super("Hirviö", new Koordinaatit(0, 0), keho, ase, osumapisteet, 7, 13);
}
/**
* Hirviön (kehnon) tekoälyn toteuttava metodi.
*
* Mikäli hirviö ei ole gladiaattorin viereisessä ruudussa, se siirtyy
* siihen viereiseen ruutuun, joka vie sen lähimmäksi gladiaattoria. Mikäli
* kyseinen ruutu on varattu, se ottaa askeleen satunnaiseen vapaaseen
* suuntaan. Mikäli tilaa liikkua mihinkään suuntaan ei ole, hirviö pysyy
* paikallaan.
*
* Mikäli hirviö on gladiaattorin viereisessä ruudussa, se kutsuu hyökkää-
* metodiaan kohteena gladiaattori.
*
* @param gladiaattori viite gladiaattoriin
* @param tilanne tilanne tapahtumien raportointia varten
* @param areena areena sijaintien tarkistamiseen
*/
public void liiku(Gladiaattori gladiaattori, Pelitilanne tilanne, Areena areena) {
if (this.getSijainti().onVieressa(gladiaattori.getSijainti())) {
areena.lisaaEfekti(this.getHyokkaysefekti(gladiaattori.getSijainti()));
this.hyokkaa(gladiaattori, tilanne);
} else {
Koordinaatit kohderuutu = this.getSijainti().getViereinenRuutuKohtiKoordinaatteja(gladiaattori.getSijainti());
if (!areena.onkoRuudussaHirviota(kohderuutu) && !areena.onkoRuudussaEstetta(kohderuutu)) {
this.siirry(kohderuutu);
} else {
int varmistus = 0;
while (true) {
kohderuutu = this.getSijainti().getSatunnainenRuutuVieressa();
if (!areena.onkoRuudussaHirviota(kohderuutu) && !areena.onkoRuudussaEstetta(kohderuutu)) {
this.siirry(kohderuutu);
break;
}
varmistus++;
if (varmistus > 50) {
break;
}
}
}
}
}
}
| UTF-8 | Java | 2,578 | java | Hirvio.java | Java | []
| null | []
| package gladiaattoripeli.domain;
import gladiaattoripeli.utilities.Pelitilanne;
/**
* Pelin vastustajia kuvaava luokka, joka laajentaa Hahmon toiminnallisuutta.
* Luokka lisää hahmolle tekoälyn, joka ohjaa sitä taistelemaan gladiaattoria
* vastaan.
*/
public class Hirvio extends Hahmo {
/**
* Konstruktori välittää vain parametrit eteenpäin yläluokan
* konstruktorille.
*
* @param osumapisteet hirviön osumapisteet
* @param keho viite hirviölle annettavaan kehoon
* @param ase viite hirviölle annettavaan aseeseen
*/
public Hirvio(int osumapisteet, Keho keho, Ase ase) {
super("Hirviö", new Koordinaatit(0, 0), keho, ase, osumapisteet, 7, 13);
}
/**
* Hirviön (kehnon) tekoälyn toteuttava metodi.
*
* Mikäli hirviö ei ole gladiaattorin viereisessä ruudussa, se siirtyy
* siihen viereiseen ruutuun, joka vie sen lähimmäksi gladiaattoria. Mikäli
* kyseinen ruutu on varattu, se ottaa askeleen satunnaiseen vapaaseen
* suuntaan. Mikäli tilaa liikkua mihinkään suuntaan ei ole, hirviö pysyy
* paikallaan.
*
* Mikäli hirviö on gladiaattorin viereisessä ruudussa, se kutsuu hyökkää-
* metodiaan kohteena gladiaattori.
*
* @param gladiaattori viite gladiaattoriin
* @param tilanne tilanne tapahtumien raportointia varten
* @param areena areena sijaintien tarkistamiseen
*/
public void liiku(Gladiaattori gladiaattori, Pelitilanne tilanne, Areena areena) {
if (this.getSijainti().onVieressa(gladiaattori.getSijainti())) {
areena.lisaaEfekti(this.getHyokkaysefekti(gladiaattori.getSijainti()));
this.hyokkaa(gladiaattori, tilanne);
} else {
Koordinaatit kohderuutu = this.getSijainti().getViereinenRuutuKohtiKoordinaatteja(gladiaattori.getSijainti());
if (!areena.onkoRuudussaHirviota(kohderuutu) && !areena.onkoRuudussaEstetta(kohderuutu)) {
this.siirry(kohderuutu);
} else {
int varmistus = 0;
while (true) {
kohderuutu = this.getSijainti().getSatunnainenRuutuVieressa();
if (!areena.onkoRuudussaHirviota(kohderuutu) && !areena.onkoRuudussaEstetta(kohderuutu)) {
this.siirry(kohderuutu);
break;
}
varmistus++;
if (varmistus > 50) {
break;
}
}
}
}
}
}
| 2,578 | 0.634865 | 0.631724 | 64 | 38.796875 | 31.485701 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 4 |
16df1c9fc77295c5602a0e9b027a7ed724121c62 | 17,609,365,960,995 | c24933f08bafdd429a0cef9499be6daa90927c9f | /HelloMvc.java | aa3a34edadca37894cc486d61dfc67d166ef1b4d | [
"MIT"
]
| permissive | yanfeipeng/hello | https://github.com/yanfeipeng/hello | dd40c81e5288f8d203e41ffb02b7cf0c20e1fc9c | 6b5d88b5ff271862733da07d4fa635462649515a | refs/heads/master | 2016-04-03T08:10:15.179000 | 2015-04-24T16:55:10 | 2015-04-24T16:55:10 | 34,530,479 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class HelloMvc {
}
| UTF-8 | Java | 29 | java | HelloMvc.java | Java | []
| null | []
|
public class HelloMvc {
}
| 29 | 0.655172 | 0.655172 | 3 | 8 | 10.614455 | 23 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | false | false | 4 |
4438947dfe92bf909188c390a75b563db84c0336 | 26,379,689,180,646 | 399198af197101dcf90cea5ee52cc5b83b19e6ec | /src/com/arctouch/swifttojava/swift/SwiftBinaryOp.java | a0f2f25fe26a4ee518868f956fbae78f74d8af8e | []
| no_license | bihai/swift-to-java | https://github.com/bihai/swift-to-java | 591994c09fa73243bf59a03caacdd71c863737b5 | e43bd3e0d59caa6e6aa7b6beee7343840cb96477 | refs/heads/master | 2021-01-21T07:44:58.794000 | 2014-09-07T23:49:14 | 2014-09-07T23:49:14 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.arctouch.swifttojava.swift;
public class SwiftBinaryOp implements SwiftExpression{
public SwiftExpression lvalue;
public SwiftExpression rvalue;
public String operator;
@Override
public String toString() {
return lvalue.toString() + " " + operator + " " + rvalue.toString();
}
}
| UTF-8 | Java | 302 | java | SwiftBinaryOp.java | Java | []
| null | []
| package com.arctouch.swifttojava.swift;
public class SwiftBinaryOp implements SwiftExpression{
public SwiftExpression lvalue;
public SwiftExpression rvalue;
public String operator;
@Override
public String toString() {
return lvalue.toString() + " " + operator + " " + rvalue.toString();
}
}
| 302 | 0.751656 | 0.751656 | 12 | 24.166666 | 21.721085 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.166667 | false | false | 4 |
dd2e1438aa0a4249c6836ef41830cf2517418d0b | 20,461,224,258,531 | 67f690d23c32a2cd487d5cfc29dc304bbd07de7a | /src/main/java/com/examble/services/MailService.java | ab6b861875d307933865de59af7d2eaa009b534d | []
| no_license | Mahmouddaood/SendMailWithSpringBoot | https://github.com/Mahmouddaood/SendMailWithSpringBoot | 93b94d6ed54f89dc09ed427c22fbf01bea1e968c | 79c90f44fcce080f1a3d741db270401612521966 | refs/heads/master | 2020-04-27T08:25:43.406000 | 2019-03-07T00:32:12 | 2019-03-07T00:32:12 | 174,170,887 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.examble.services;
public interface MailService {
void sendTo(String fAddress , String tAddress , String sub , String content) throws Exception;
void sendHtml(String fAddress , String tAddress , String sub , String content) throws Exception;
}
| UTF-8 | Java | 262 | java | MailService.java | Java | []
| null | []
| package com.examble.services;
public interface MailService {
void sendTo(String fAddress , String tAddress , String sub , String content) throws Exception;
void sendHtml(String fAddress , String tAddress , String sub , String content) throws Exception;
}
| 262 | 0.774809 | 0.774809 | 9 | 28.111111 | 38.100582 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.333333 | false | false | 4 |
f9c8158c01e08fa2738db51d99ddf446d09c3dde | 30,193,620,147,271 | 6862f7ff2f1eea708092f88c4e9c470c6b7c1619 | /src/wsu/cs558/roadmonitoring/view/AccelerometerViewActivity.java | 6cadbfd7bce535a4daa17b72516f1dd2816dcbac | []
| no_license | jenis23/CS558_Project | https://github.com/jenis23/CS558_Project | 760f84e3f7629fd22239f570c0829395f5c1e3a7 | bf1dd427d48c006e74af02f70719ed0e3a62685f | refs/heads/master | 2020-04-13T14:59:45.531000 | 2013-05-01T10:04:08 | 2013-05-01T10:04:08 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package wsu.cs558.roadmonitoring.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import wsu.cs558.roadmonitoring.bean.AccelLocData;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AccelerometerViewActivity extends Activity implements
SensorEventListener, OnClickListener {
private SensorManager sensorManager;
final String FILE_NAME = "SAMPLEFILE.txt";
final String TEST_STRING = new String("Hello Android");
private ArrayList<AccelLocData> sensorData;
private Button btnStart, btnStop, btnUpload;
private boolean started = false;
private LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = new TextView(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorData = new ArrayList<AccelLocData>();
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
// btnUpload = (Button) findViewById(R.id.btnUpload);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
// btnUpload.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
if (sensorData == null || sensorData.size() == 0) {
btnUpload.setEnabled(false);
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
if (started == true) {
sensorManager.unregisterListener(this);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/*
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
*/
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
// AccelData data = new AccelData(timestamp, x, y, z);
// sensorData.add(data);
}
/*
* if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return;
* float mSensorX, mSensorY; switch (mDisplay.getRotation()) { case
* Surface.ROTATION_0: mSensorX = event.values[0]; mSensorY =
* event.values[1]; break; case Surface.ROTATION_90: mSensorX =
* -event.values[1]; mSensorY = event.values[0]; break; case
* Surface.ROTATION_180: mSensorX = -event.values[0]; mSensorY =
* -event.values[1]; break; case Surface.ROTATION_270: mSensorX =
* event.values[1]; mSensorY = -event.values[0]; }
*
* if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return; else
* {
*
* // assign directions float x = event.values[0]; float y =
* event.values[1]; float z = event.values[2];
*
* xCoor.setText("X: " + x); yCoor.setText("Y: " + y);
* zCoor.setText("Z: " + z); }
*/
}
/* To add menu on left click
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.start:
System.out.println("Start called");
started = true;
return true;
case R.id.stop:
System.out.println("Stop called");
started = false;
sensorManager.unregisterListener(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnUpload.setEnabled(false);
sensorData = new ArrayList<AccelLocData>();
// save prev data if available
started = true;
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/download");
dir.mkdirs();
File sensorFile = new File(dir, "acc.txt");
// sensorFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(sensorFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
// myOutWriter.append(sensorData);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
Sensor accel = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
btnStart.setEnabled(true);
btnStop.setEnabled(false);
btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
layout.removeAllViews();
// don't need chart
// openChart();
// show data in chart
break;
// case R.id.btnUpload:
// break;
default:
break;
}
}
}
| UTF-8 | Java | 5,595 | java | AccelerometerViewActivity.java | Java | []
| null | []
| package wsu.cs558.roadmonitoring.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import wsu.cs558.roadmonitoring.bean.AccelLocData;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class AccelerometerViewActivity extends Activity implements
SensorEventListener, OnClickListener {
private SensorManager sensorManager;
final String FILE_NAME = "SAMPLEFILE.txt";
final String TEST_STRING = new String("Hello Android");
private ArrayList<AccelLocData> sensorData;
private Button btnStart, btnStop, btnUpload;
private boolean started = false;
private LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = new TextView(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorData = new ArrayList<AccelLocData>();
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
// btnUpload = (Button) findViewById(R.id.btnUpload);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
// btnUpload.setOnClickListener(this);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
if (sensorData == null || sensorData.size() == 0) {
btnUpload.setEnabled(false);
}
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
if (started == true) {
sensorManager.unregisterListener(this);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
/*
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
*/
public void onSensorChanged(SensorEvent event) {
if (started) {
double x = event.values[0];
double y = event.values[1];
double z = event.values[2];
long timestamp = System.currentTimeMillis();
// AccelData data = new AccelData(timestamp, x, y, z);
// sensorData.add(data);
}
/*
* if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return;
* float mSensorX, mSensorY; switch (mDisplay.getRotation()) { case
* Surface.ROTATION_0: mSensorX = event.values[0]; mSensorY =
* event.values[1]; break; case Surface.ROTATION_90: mSensorX =
* -event.values[1]; mSensorY = event.values[0]; break; case
* Surface.ROTATION_180: mSensorX = -event.values[0]; mSensorY =
* -event.values[1]; break; case Surface.ROTATION_270: mSensorX =
* event.values[1]; mSensorY = -event.values[0]; }
*
* if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) return; else
* {
*
* // assign directions float x = event.values[0]; float y =
* event.values[1]; float z = event.values[2];
*
* xCoor.setText("X: " + x); yCoor.setText("Y: " + y);
* zCoor.setText("Z: " + z); }
*/
}
/* To add menu on left click
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.start:
System.out.println("Start called");
started = true;
return true;
case R.id.stop:
System.out.println("Stop called");
started = false;
sensorManager.unregisterListener(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnStart:
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnUpload.setEnabled(false);
sensorData = new ArrayList<AccelLocData>();
// save prev data if available
started = true;
try {
File root = android.os.Environment
.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/download");
dir.mkdirs();
File sensorFile = new File(dir, "acc.txt");
// sensorFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(sensorFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
// myOutWriter.append(sensorData);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
Sensor accel = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accel,
SensorManager.SENSOR_DELAY_FASTEST);
break;
case R.id.btnStop:
btnStart.setEnabled(true);
btnStop.setEnabled(false);
btnUpload.setEnabled(true);
started = false;
sensorManager.unregisterListener(this);
layout.removeAllViews();
// don't need chart
// openChart();
// show data in chart
break;
// case R.id.btnUpload:
// break;
default:
break;
}
}
}
| 5,595 | 0.706881 | 0.701519 | 208 | 25.899038 | 20.145252 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.370192 | false | false | 4 |
a40a40a68521617e02d26ef1b5c910b6ced359bb | 23,338,852,355,480 | 3f6637f6b073232dcc873d17d23c74c8d822e676 | /EdlNsoCore/src/main/java/com/edlplan/nso/parser/LinesParser.java | 67144f183d2c53956635b1d14d30b888afb3b75c | []
| no_license | EdrowsLuo/osu-lab | https://github.com/EdrowsLuo/osu-lab | 6fcb432c45d982eec686b73e61a02e654a43754a | f23bda8234f128abb6d30537b81ca54443d7a21e | refs/heads/master | 2020-03-22T21:52:23.982000 | 2019-05-22T09:13:52 | 2019-05-22T09:14:57 | 140,718,644 | 11 | 6 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.edlplan.nso.parser;
import com.edlplan.nso.NsoException;
public interface LinesParser {
public boolean parse(String l) throws NsoException;
}
| UTF-8 | Java | 160 | java | LinesParser.java | Java | []
| null | []
| package com.edlplan.nso.parser;
import com.edlplan.nso.NsoException;
public interface LinesParser {
public boolean parse(String l) throws NsoException;
}
| 160 | 0.7875 | 0.7875 | 7 | 21.857143 | 20.138298 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
d981940fb8ffb70b14894376814ab92ea1726302 | 21,998,822,549,072 | fbadbeaf387c2f48487ca19ecade2b473a6f67d1 | /src/com/javaex/ex05/Depart.java | 8c0d186b3bd520c6d79add088b66f3a2d2f66522 | []
| no_license | pis5430/practice06 | https://github.com/pis5430/practice06 | 9c52398fce4540fcd5fe3f43bcd9b490d071d8fd | 979abad6a788ea88463d33aefedbc37f32fe5c64 | refs/heads/master | 2023-01-21T04:50:36.217000 | 2020-12-01T09:19:49 | 2020-12-01T09:19:49 | 317,455,664 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.javaex.ex05;
public class Depart extends Employee {
//필드
private String department;
//생산자
public Depart() {
super();
}
public Depart(String name, int salary, String department) {
super(name, salary);
this.department = department;
}
//일반 메소드
public void showInformation() {
System.out.println("이름:" + getName() + " 연봉:" + getSalary() + " 부서:" + department );
}
}
| UTF-8 | Java | 517 | java | Depart.java | Java | []
| null | []
| package com.javaex.ex05;
public class Depart extends Employee {
//필드
private String department;
//생산자
public Depart() {
super();
}
public Depart(String name, int salary, String department) {
super(name, salary);
this.department = department;
}
//일반 메소드
public void showInformation() {
System.out.println("이름:" + getName() + " 연봉:" + getSalary() + " 부서:" + department );
}
}
| 517 | 0.538144 | 0.534021 | 37 | 11.108109 | 18.840416 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.054054 | false | false | 4 |
8b7743d485f5bee4fcfe02c819f429e0f4b596ee | 20,993,800,208,965 | 7e8b06400936d52030c0cf6f5ae17fd2e86bf1c5 | /muistipeli/src/main/java/com/mipyykko/muistipeli/ui/javafx/ControlledRuutu.java | 5aabfd010dae917a9eb25ff89b61f14caf0bb565 | []
| no_license | mipyykko/muistipeli- | https://github.com/mipyykko/muistipeli- | 379f3a1c46db72dac222b610096895fead266902 | cb6a52141178fa9b7c2d391a3615696d033b0557 | refs/heads/master | 2021-01-11T18:37:39.957000 | 2017-03-05T18:47:28 | 2017-03-05T18:47:28 | 79,585,294 | 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 com.mipyykko.muistipeli.ui.javafx;
/**
*
* @author pyykkomi
*/
public interface ControlledRuutu {
public void asetaParent(IkkunaController ikkuna);
}
| UTF-8 | Java | 356 | java | ControlledRuutu.java | Java | [
{
"context": ".mipyykko.muistipeli.ui.javafx;\n\n/**\n *\n * @author pyykkomi\n */\npublic interface ControlledRuutu {\n \n p",
"end": 255,
"score": 0.9996172189712524,
"start": 247,
"tag": "USERNAME",
"value": "pyykkomi"
}
]
| 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 com.mipyykko.muistipeli.ui.javafx;
/**
*
* @author pyykkomi
*/
public interface ControlledRuutu {
public void asetaParent(IkkunaController ikkuna);
}
| 356 | 0.730337 | 0.730337 | 15 | 22.733334 | 25.034554 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
6b104ddf70ae96c517cbde883460f15036721789 | 8,443,905,769,928 | 9e30d93c373ae1eb28feb5d77637011b72519c74 | /web/src/com/oracle/happytrip/businesslayer/utilities/IDGenerator.java | 786b8fb146e0d8a979bd2762656dc86876872540 | []
| no_license | parthasm/Happytrip | https://github.com/parthasm/Happytrip | 0f7ea2d3e85247a46812bfabab8837fbaa97fedf | 1ba580c2e3cdd82d686e4bab693efbc2de98af33 | refs/heads/master | 2021-01-22T21:12:55.270000 | 2014-05-11T18:22:56 | 2014-05-11T18:22:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.oracle.happytrip.businesslayer.utilities;
public class IDGenerator
{
public static String paymentReferenceNoGenerator()
{
return "Happy"+((int)(Math.random()*100000000));
}
public static String passwordGenerator()
{
return "Happy"+((int)(Math.random()*10000.0))+"jnsbd"+((int)(Math.random()*100.0));
}
public static long idGenerator()
{
return (long)(Math.random()*100000000000l);
}
public static int idIntGenerator()
{
return (int)(Math.random()*10000000);
}
public static void main(String[] arg)
{
System.out.println(paymentReferenceNoGenerator());
String jshn = "djhbdh.hsjdhn.adghs";
System.out.println(jshn.lastIndexOf("."));
}
}
| UTF-8 | Java | 700 | java | IDGenerator.java | Java | [
{
"context": "\t\treturn \"Happy\"+((int)(Math.random()*10000.0))+\"jnsbd\"+((int)(Math.random()*100.0));\n\t}\n\t\n\tpublic stati",
"end": 301,
"score": 0.8686367273330688,
"start": 297,
"tag": "PASSWORD",
"value": "nsbd"
}
]
| null | []
| package com.oracle.happytrip.businesslayer.utilities;
public class IDGenerator
{
public static String paymentReferenceNoGenerator()
{
return "Happy"+((int)(Math.random()*100000000));
}
public static String passwordGenerator()
{
return "Happy"+((int)(Math.random()*10000.0))+"j<PASSWORD>"+((int)(Math.random()*100.0));
}
public static long idGenerator()
{
return (long)(Math.random()*100000000000l);
}
public static int idIntGenerator()
{
return (int)(Math.random()*10000000);
}
public static void main(String[] arg)
{
System.out.println(paymentReferenceNoGenerator());
String jshn = "djhbdh.hsjdhn.adghs";
System.out.println(jshn.lastIndexOf("."));
}
}
| 706 | 0.685714 | 0.63 | 37 | 17.918919 | 22.664865 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.324324 | false | false | 4 |
0866cee4a48131d20b282afadb1d7754c6a98f9e | 37,323,265,832,033 | 851500b2e12d9db6e4f33a465f044acc17a6134d | /src/homework5/task22/WingName.java | 5a66cf7930530efb164eec656e9f092cbc85b0e5 | []
| no_license | ruslanstetsenko/EPAM | https://github.com/ruslanstetsenko/EPAM | bcf3b310bcf7ad3b7af3674c03372303abb200ba | 152eb80add665fc1c89621a08f6761ae6ca72d84 | refs/heads/master | 2019-03-20T22:51:11.411000 | 2018-05-14T16:30:50 | 2018-05-14T16:30:50 | 124,026,576 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package homework5.task22;
public enum WingName {
LEFT, RIGHT
}
| UTF-8 | Java | 69 | java | WingName.java | Java | []
| null | []
| package homework5.task22;
public enum WingName {
LEFT, RIGHT
}
| 69 | 0.710145 | 0.666667 | 6 | 10.5 | 10.59481 | 25 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
663ebd388360b8bff465ba72f08bae281ade85a8 | 39,591,008,553,056 | 55060598129ed1c8f65d6244b52aae79e277c7f1 | /JavaTution/src/com/pratice/IdentifyQuadrent.java | b82cabf15948bf93095d3b868631e9a16c54e82f | []
| no_license | mahendrakishore/JavaTution | https://github.com/mahendrakishore/JavaTution | f1bfbe36144ca36dc76e5cbc424e634d5d09108b | a39ce0894bd2d744dea9db8f8aecf616bde0ccfa | refs/heads/master | 2021-01-22T10:26:49.120000 | 2017-06-04T14:25:31 | 2017-06-04T14:25:31 | 92,643,878 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pratice;
public class IdentifyQuadrent {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = - 3 , y= -4;
if(x>0 && y>0)
System.out.println("lies in the 1 st quad");
else if (x<0 && y>0){
System.out.println("lies in the 2nd quad");
}
else if(x<0 && y<0){
System.out.println(" lies in the 3rd quad");
}
else if(x>0 && y<0){
System.out.println("lies in the 4th quad");
}
else{
System.out.println("don'e lies anywhere");
}
}
}
| UTF-8 | Java | 512 | java | IdentifyQuadrent.java | Java | []
| null | []
| package com.pratice;
public class IdentifyQuadrent {
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = - 3 , y= -4;
if(x>0 && y>0)
System.out.println("lies in the 1 st quad");
else if (x<0 && y>0){
System.out.println("lies in the 2nd quad");
}
else if(x<0 && y<0){
System.out.println(" lies in the 3rd quad");
}
else if(x>0 && y<0){
System.out.println("lies in the 4th quad");
}
else{
System.out.println("don'e lies anywhere");
}
}
}
| 512 | 0.601563 | 0.574219 | 28 | 16.285715 | 17.478266 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.607143 | false | false | 4 |
ba22b9cbd72a6d422bb2936b838cdcfb94ef2292 | 35,055,523,127,417 | a173729fa3de2ddf959584683ca6bd798a0fa687 | /src/main/java/essilor/integrator/adapter/domain/owvalidation/ValidateQuotationResponse.java | 50613c9ee9cb3bc2ea49590ca24f6aa02e5f45a5 | []
| no_license | kepal4620/essilor-integrator | https://github.com/kepal4620/essilor-integrator | a8167508e9a2ba04fc3aef3a4eb2ff3ecf456783 | d2b9dfcf47b2a6b2e4e947cfe6f634fe57374098 | refs/heads/master | 2021-01-11T18:41:50.917000 | 2018-04-19T20:38:59 | 2018-04-19T20:38:59 | 79,602,969 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.10.03 at 09:46:51 PM CEST
//
package essilor.integrator.adapter.domain.owvalidation;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ValidateQuotationResult" type="{http://OpsysWeb.eu/}QuotationResults" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"validateQuotationResult"
})
@XmlRootElement(name = "ValidateQuotationResponse")
public class ValidateQuotationResponse {
@XmlElement(name = "ValidateQuotationResult")
protected QuotationResults validateQuotationResult;
/**
* Gets the value of the validateQuotationResult property.
*
* @return
* possible object is
* {@link QuotationResults }
*
*/
public QuotationResults getValidateQuotationResult() {
return validateQuotationResult;
}
/**
* Sets the value of the validateQuotationResult property.
*
* @param value
* allowed object is
* {@link QuotationResults }
*
*/
public void setValidateQuotationResult(QuotationResults value) {
this.validateQuotationResult = value;
}
}
| UTF-8 | Java | 2,067 | java | ValidateQuotationResponse.java | Java | []
| null | []
| //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.10.03 at 09:46:51 PM CEST
//
package essilor.integrator.adapter.domain.owvalidation;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ValidateQuotationResult" type="{http://OpsysWeb.eu/}QuotationResults" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"validateQuotationResult"
})
@XmlRootElement(name = "ValidateQuotationResponse")
public class ValidateQuotationResponse {
@XmlElement(name = "ValidateQuotationResult")
protected QuotationResults validateQuotationResult;
/**
* Gets the value of the validateQuotationResult property.
*
* @return
* possible object is
* {@link QuotationResults }
*
*/
public QuotationResults getValidateQuotationResult() {
return validateQuotationResult;
}
/**
* Sets the value of the validateQuotationResult property.
*
* @param value
* allowed object is
* {@link QuotationResults }
*
*/
public void setValidateQuotationResult(QuotationResults value) {
this.validateQuotationResult = value;
}
}
| 2,067 | 0.684567 | 0.67344 | 71 | 28.112677 | 28.090673 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.28169 | false | false | 4 |
1f1bd136423affa422819e18a495bfc523456e10 | 36,009,005,856,661 | 315a2677397a421285cd4ff9c088ae42a609c885 | /java/com/invizzble/SC/recipes/ShapedRecipes.java | 2f1d8c3f4406bac54e819d865d458c15846cd207 | []
| no_license | invizzble/ScientomicCraft | https://github.com/invizzble/ScientomicCraft | dbb3b297300bbf0a531a2f80c4267253a97be88c | 98c809361e55f4559152ae4fe40ac8a4cbd0dcdc | refs/heads/master | 2021-01-16T23:34:52.985000 | 2015-07-26T00:02:15 | 2015-07-26T00:02:15 | 15,623,760 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.invizzble.SC.recipes;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import com.invizzble.SC.item.ModItems;
import cpw.mods.fml.common.registry.GameRegistry;
public class ShapedRecipes {
public static void init(){
GameRegistry.addShapedRecipe(new ItemStack(ModItems.SciPad), "X "," "," ", 'X', Items.stick);
}
}
| UTF-8 | Java | 363 | java | ShapedRecipes.java | Java | []
| null | []
| package com.invizzble.SC.recipes;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import com.invizzble.SC.item.ModItems;
import cpw.mods.fml.common.registry.GameRegistry;
public class ShapedRecipes {
public static void init(){
GameRegistry.addShapedRecipe(new ItemStack(ModItems.SciPad), "X "," "," ", 'X', Items.stick);
}
}
| 363 | 0.741047 | 0.741047 | 16 | 21.6875 | 26.513485 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
92bc8a22643230fb6d567afb48bdb9f8b09180ab | 34,703,335,807,831 | 9cde83d5745b93f725eca98929320f7b7d002d9f | /bucketKurly/src/main/java/bucket/kurly/user/board/Board_reviewDAO.java | 7fb27e99f30f5d14a218eb946234513120fbcee5 | []
| no_license | gyungwonkim98/KG_4 | https://github.com/gyungwonkim98/KG_4 | d61dc4ee37e14e8fb9b2382dbd86b7422d30165e | 89296156cb9ce7000a5992ae16d75ed82f74bd20 | refs/heads/main | 2023-08-16T01:28:18.089000 | 2021-10-15T00:45:09 | 2021-10-15T00:45:09 | 395,204,642 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bucket.kurly.user.board;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class Board_reviewDAO {
@Autowired
SqlSessionTemplate sqlSessionTemplate;
public List<Board_reviewVO> selectBoard_review(String goods_sell_no) {
System.out.println("Board_reviewDAO - selectBoard_review() 실행");
return sqlSessionTemplate.selectList("board-mapping.selectBoard_review",goods_sell_no);
}
}
| UTF-8 | Java | 556 | java | Board_reviewDAO.java | Java | []
| null | []
| package bucket.kurly.user.board;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class Board_reviewDAO {
@Autowired
SqlSessionTemplate sqlSessionTemplate;
public List<Board_reviewVO> selectBoard_review(String goods_sell_no) {
System.out.println("Board_reviewDAO - selectBoard_review() 실행");
return sqlSessionTemplate.selectList("board-mapping.selectBoard_review",goods_sell_no);
}
}
| 556 | 0.804348 | 0.804348 | 19 | 28.052631 | 28.25909 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.947368 | false | false | 4 |
6b37d3764035463018bedf619094019c425e66a6 | 36,386,962,976,982 | 06c31fae211ad709ecd6459d40fcec5e6bcf1f95 | /data/src/main/java/com/huynh/xinh/data/repositories/exchange/cloud/ExchangeApi.java | 4078d267cb5f7427e90442f7c18d911e7ba50272 | [
"Apache-2.0"
]
| permissive | davicho2189/Clean-Architecture-Coin | https://github.com/davicho2189/Clean-Architecture-Coin | 0b242ce0954723851a9857c555dbe10a35777f51 | c8048511a8e463a145f129940ea55b1b8dfc8e7f | refs/heads/master | 2020-05-07T19:41:26.867000 | 2019-04-06T07:15:43 | 2019-04-06T07:15:43 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huynh.xinh.data.repositories.exchange.cloud;
import com.huynh.xinh.data.repositories.exchange.ListExchangeResponse;
import io.reactivex.Observable;
import retrofit2.http.GET;
/**
* Created by XinhHuynh on 2/28/2018.
*/
public interface ExchangeApi {
@GET("exchanges")
Observable<ListExchangeResponse> getListExchangeMarket();
}
| UTF-8 | Java | 354 | java | ExchangeApi.java | Java | [
{
"context": "ble;\nimport retrofit2.http.GET;\n\n/**\n * Created by XinhHuynh on 2/28/2018.\n */\n\npublic interface Excha",
"end": 209,
"score": 0.6506938934326172,
"start": 208,
"tag": "NAME",
"value": "X"
},
{
"context": "e;\nimport retrofit2.http.GET;\n\n/**\n * Created by XinhHuynh on 2/28/2018.\n */\n\npublic interface ExchangeApi ",
"end": 216,
"score": 0.5720863938331604,
"start": 209,
"tag": "USERNAME",
"value": "inhHuyn"
},
{
"context": "rt retrofit2.http.GET;\n\n/**\n * Created by XinhHuynh on 2/28/2018.\n */\n\npublic interface ExchangeApi {",
"end": 217,
"score": 0.6500654816627502,
"start": 216,
"tag": "NAME",
"value": "h"
}
]
| null | []
| package com.huynh.xinh.data.repositories.exchange.cloud;
import com.huynh.xinh.data.repositories.exchange.ListExchangeResponse;
import io.reactivex.Observable;
import retrofit2.http.GET;
/**
* Created by XinhHuynh on 2/28/2018.
*/
public interface ExchangeApi {
@GET("exchanges")
Observable<ListExchangeResponse> getListExchangeMarket();
}
| 354 | 0.776836 | 0.754237 | 15 | 22.6 | 23.750929 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 4 |
5d16c63952942fba018cfaaeae0c24e164e4023e | 16,192,026,770,195 | 94be71c7f3e4df3a6bfb2110b92dbef1c520d037 | /LifeCare/LifeCareApp/app/src/main/java/com/example/zziboo/lifecareapp/SetActivity.java | 6136091efdeaa5ca21eae8f4ee83e2794922ce3a | []
| no_license | zziboo/Android_LifeCare | https://github.com/zziboo/Android_LifeCare | 15512951e4105088f1b90e9e5b1a0eda20c0a4fe | 84ed2e9c7c1062808c67041b9f56dfc9a9a6fe2e | refs/heads/master | 2021-01-23T04:14:06.192000 | 2017-06-11T15:59:47 | 2017-06-11T15:59:47 | 92,920,478 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.zziboo.lifecareapp;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
import com.example.zziboo.lifecareapp.Service.GpsService;
import com.example.zziboo.lifecareapp.Service.SensorService;
public class SetActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
public static final String MESSAGE_DATA = "MESSAGE_DATA";
Switch stepSwitch, msgSwitch;
Intent sensorService;
Intent gpsService;
Button saveButton;
EditText timetxt, alarmMsgtxt;
public int timeset;
public String message;
SharedPreferences pref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
// service의 on/off를 위한 Intent
sensorService = new Intent(this, SensorService.class);
gpsService = new Intent(this, GpsService.class);
// 필요한 switch button 선언
stepSwitch = (Switch) findViewById(R.id.stepSwitch);
msgSwitch = (Switch) findViewById(R.id.msgSwitch);
// switch에 대한 리스너 등록
stepSwitch.setOnCheckedChangeListener(this);
msgSwitch.setOnCheckedChangeListener(this);
// 필요한 text와 button에 대한 선언
timetxt = (EditText) findViewById(R.id.alarmtxt);
alarmMsgtxt = (EditText) findViewById(R.id.alarmMsgtxt);
saveButton = (Button) findViewById(R.id.savebtn);
// SharedPreference를 사용하여 timeset 값과 Message String 값 저장
pref = getSharedPreferences(MESSAGE_DATA, MODE_PRIVATE);
editor = pref.edit();
timetxt.setText(pref.getInt("TIMESET", 30)+"");
alarmMsgtxt.setText(pref.getString("MSG", "다음과 같은 장소에서 현재 움직임이 없습니다."));
// service가 실행중인지 확인하는 구문
if(isMyServiceRunning(SensorService.class)){
Toast.makeText(this, "Step Service is Running..", Toast.LENGTH_SHORT).show();
stepSwitch.setChecked(true);
}
// service가 실행중인지 확인하는 구문
if(isMyServiceRunning(GpsService.class)){
Toast.makeText(this, "GPS Service is Running..", Toast.LENGTH_SHORT).show();
msgSwitch.setChecked(true);
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == false){
//v의 service 종료
switch (buttonView.getId()){
//msg service start
case R.id.msgSwitch:
stopService(gpsService);
Toast.makeText(this, buttonView.getText() + " off", Toast.LENGTH_SHORT).show();
break;
//step service start
case R.id.stepSwitch:
stopService(sensorService);
Toast.makeText(this, buttonView.getText() + " off", Toast.LENGTH_SHORT).show();
break;
}
return ;
}
switch (buttonView.getId()){
//msg service start
case R.id.msgSwitch:
startService(gpsService);
Toast.makeText(this, buttonView.getText() + " on", Toast.LENGTH_SHORT).show();
break;
//step service start
case R.id.stepSwitch:
startService(sensorService);
Toast.makeText(this, buttonView.getText() + " on", Toast.LENGTH_SHORT).show();
break;
}
}
// Service가 진행중인지 상태를 확인하는 method
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
// Activity를 종료하기위한 리스너
public void closeClick(View view){
finish();
}
// Message 송신을 위한 시간과 메세지 내용을 저장하기 위한 버튼 리스너
public void saveOnClick(View view){
timeset = Integer.parseInt(timetxt.getText().toString());
message = alarmMsgtxt.getText().toString();
editor.putInt("TIMESET", timeset);
editor.putString("MSG", message);
editor.commit();
Toast.makeText(getApplicationContext(), timeset + "분 이후 " + message + "가 송신됩니다.", Toast.LENGTH_SHORT).show();
}
}
| UTF-8 | Java | 5,236 | java | SetActivity.java | Java | []
| null | []
| package com.example.zziboo.lifecareapp;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
import com.example.zziboo.lifecareapp.Service.GpsService;
import com.example.zziboo.lifecareapp.Service.SensorService;
public class SetActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
public static final String MESSAGE_DATA = "MESSAGE_DATA";
Switch stepSwitch, msgSwitch;
Intent sensorService;
Intent gpsService;
Button saveButton;
EditText timetxt, alarmMsgtxt;
public int timeset;
public String message;
SharedPreferences pref;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set);
// service의 on/off를 위한 Intent
sensorService = new Intent(this, SensorService.class);
gpsService = new Intent(this, GpsService.class);
// 필요한 switch button 선언
stepSwitch = (Switch) findViewById(R.id.stepSwitch);
msgSwitch = (Switch) findViewById(R.id.msgSwitch);
// switch에 대한 리스너 등록
stepSwitch.setOnCheckedChangeListener(this);
msgSwitch.setOnCheckedChangeListener(this);
// 필요한 text와 button에 대한 선언
timetxt = (EditText) findViewById(R.id.alarmtxt);
alarmMsgtxt = (EditText) findViewById(R.id.alarmMsgtxt);
saveButton = (Button) findViewById(R.id.savebtn);
// SharedPreference를 사용하여 timeset 값과 Message String 값 저장
pref = getSharedPreferences(MESSAGE_DATA, MODE_PRIVATE);
editor = pref.edit();
timetxt.setText(pref.getInt("TIMESET", 30)+"");
alarmMsgtxt.setText(pref.getString("MSG", "다음과 같은 장소에서 현재 움직임이 없습니다."));
// service가 실행중인지 확인하는 구문
if(isMyServiceRunning(SensorService.class)){
Toast.makeText(this, "Step Service is Running..", Toast.LENGTH_SHORT).show();
stepSwitch.setChecked(true);
}
// service가 실행중인지 확인하는 구문
if(isMyServiceRunning(GpsService.class)){
Toast.makeText(this, "GPS Service is Running..", Toast.LENGTH_SHORT).show();
msgSwitch.setChecked(true);
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == false){
//v의 service 종료
switch (buttonView.getId()){
//msg service start
case R.id.msgSwitch:
stopService(gpsService);
Toast.makeText(this, buttonView.getText() + " off", Toast.LENGTH_SHORT).show();
break;
//step service start
case R.id.stepSwitch:
stopService(sensorService);
Toast.makeText(this, buttonView.getText() + " off", Toast.LENGTH_SHORT).show();
break;
}
return ;
}
switch (buttonView.getId()){
//msg service start
case R.id.msgSwitch:
startService(gpsService);
Toast.makeText(this, buttonView.getText() + " on", Toast.LENGTH_SHORT).show();
break;
//step service start
case R.id.stepSwitch:
startService(sensorService);
Toast.makeText(this, buttonView.getText() + " on", Toast.LENGTH_SHORT).show();
break;
}
}
// Service가 진행중인지 상태를 확인하는 method
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
// Activity를 종료하기위한 리스너
public void closeClick(View view){
finish();
}
// Message 송신을 위한 시간과 메세지 내용을 저장하기 위한 버튼 리스너
public void saveOnClick(View view){
timeset = Integer.parseInt(timetxt.getText().toString());
message = alarmMsgtxt.getText().toString();
editor.putInt("TIMESET", timeset);
editor.putString("MSG", message);
editor.commit();
Toast.makeText(getApplicationContext(), timeset + "분 이후 " + message + "가 송신됩니다.", Toast.LENGTH_SHORT).show();
}
}
| 5,236 | 0.641388 | 0.640783 | 136 | 35.455883 | 26.501905 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.698529 | false | false | 4 |
1f9ea2bae75b7b85c3e8602f310a5c9eb8460425 | 34,918,084,172,820 | b404826a9a3f0fee80d1c35ca6295f9248acad1d | /com/google/android/gms/auth/TokenData.java | cfb6ba461f4fa7f82140bf5f340d9a8e5870b265 | []
| no_license | cyberhorse208/SafetyNet | https://github.com/cyberhorse208/SafetyNet | 9690da910fb80a72f0858b0ffef378e9e1b1609b | f251566d00f9e79ff0205eaaa889d74102b4ebc4 | refs/heads/master | 2021-12-11T02:30:34.120000 | 2016-10-18T08:21:52 | 2016-10-18T08:21:52 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.google.android.gms.auth;
import android.os.Bundle;
import android.os.Parcel;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.google.android.gms.common.internal.zzw;
import com.google.android.gms.common.internal.zzx;
import java.util.List;
public class TokenData implements SafeParcelable {
public static final zzd CREATOR = new zzd();
final int mVersionCode;
private final String zzWX;
private final Long zzWY;
private final boolean zzWZ;
private final boolean zzXa;
private final List<String> zzXb;
public static class zza {
private String zzWX = null;
private Long zzWY = null;
private boolean zzWZ = false;
private boolean zzXa = false;
private List<String> zzXb = null;
public zza zzbq(String str) {
this.zzWX = str;
return this;
}
@Nullable
public TokenData zzkl() {
if (!this.zzXa || this.zzXb != null) {
return TextUtils.isEmpty(this.zzWX) ? null : new TokenData(1, this.zzWX, this.zzWY, this.zzWZ, this.zzXa, this.zzXb);
} else {
throw new IllegalStateException("Granted scopes must be set if the token is snowballed.");
}
}
}
TokenData(int versionCode, String token, Long expirationTimeSecs, boolean isCached, boolean isSnowballed, List<String> grantedScopes) {
this.mVersionCode = versionCode;
this.zzWX = zzx.zzcL(token);
this.zzWY = expirationTimeSecs;
this.zzWZ = isCached;
this.zzXa = isSnowballed;
this.zzXb = grantedScopes;
}
@Nullable
public static TokenData zzc(Bundle bundle, String str) {
bundle.setClassLoader(TokenData.class.getClassLoader());
Bundle bundle2 = bundle.getBundle(str);
if (bundle2 == null) {
return null;
}
bundle2.setClassLoader(TokenData.class.getClassLoader());
return (TokenData) bundle2.getParcelable("TokenData");
}
public int describeContents() {
return 0;
}
public boolean equals(Object o) {
if (!(o instanceof TokenData)) {
return false;
}
TokenData tokenData = (TokenData) o;
return TextUtils.equals(this.zzWX, tokenData.zzWX) && zzw.equal(this.zzWY, tokenData.zzWY) && this.zzWZ == tokenData.zzWZ && this.zzXa == tokenData.zzXa && zzw.equal(this.zzXb, tokenData.zzXb);
}
public String getToken() {
return this.zzWX;
}
public int hashCode() {
return zzw.hashCode(this.zzWX, this.zzWY, Boolean.valueOf(this.zzWZ), Boolean.valueOf(this.zzXa), this.zzXb);
}
public void writeToParcel(Parcel out, int flags) {
zzd.zza(this, out, flags);
}
@Nullable
public Long zzkh() {
return this.zzWY;
}
public boolean zzki() {
return this.zzWZ;
}
public boolean zzkj() {
return this.zzXa;
}
@Nullable
public List<String> zzkk() {
return this.zzXb;
}
}
| UTF-8 | Java | 3,145 | java | TokenData.java | Java | []
| null | []
| package com.google.android.gms.auth;
import android.os.Bundle;
import android.os.Parcel;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.google.android.gms.common.internal.zzw;
import com.google.android.gms.common.internal.zzx;
import java.util.List;
public class TokenData implements SafeParcelable {
public static final zzd CREATOR = new zzd();
final int mVersionCode;
private final String zzWX;
private final Long zzWY;
private final boolean zzWZ;
private final boolean zzXa;
private final List<String> zzXb;
public static class zza {
private String zzWX = null;
private Long zzWY = null;
private boolean zzWZ = false;
private boolean zzXa = false;
private List<String> zzXb = null;
public zza zzbq(String str) {
this.zzWX = str;
return this;
}
@Nullable
public TokenData zzkl() {
if (!this.zzXa || this.zzXb != null) {
return TextUtils.isEmpty(this.zzWX) ? null : new TokenData(1, this.zzWX, this.zzWY, this.zzWZ, this.zzXa, this.zzXb);
} else {
throw new IllegalStateException("Granted scopes must be set if the token is snowballed.");
}
}
}
TokenData(int versionCode, String token, Long expirationTimeSecs, boolean isCached, boolean isSnowballed, List<String> grantedScopes) {
this.mVersionCode = versionCode;
this.zzWX = zzx.zzcL(token);
this.zzWY = expirationTimeSecs;
this.zzWZ = isCached;
this.zzXa = isSnowballed;
this.zzXb = grantedScopes;
}
@Nullable
public static TokenData zzc(Bundle bundle, String str) {
bundle.setClassLoader(TokenData.class.getClassLoader());
Bundle bundle2 = bundle.getBundle(str);
if (bundle2 == null) {
return null;
}
bundle2.setClassLoader(TokenData.class.getClassLoader());
return (TokenData) bundle2.getParcelable("TokenData");
}
public int describeContents() {
return 0;
}
public boolean equals(Object o) {
if (!(o instanceof TokenData)) {
return false;
}
TokenData tokenData = (TokenData) o;
return TextUtils.equals(this.zzWX, tokenData.zzWX) && zzw.equal(this.zzWY, tokenData.zzWY) && this.zzWZ == tokenData.zzWZ && this.zzXa == tokenData.zzXa && zzw.equal(this.zzXb, tokenData.zzXb);
}
public String getToken() {
return this.zzWX;
}
public int hashCode() {
return zzw.hashCode(this.zzWX, this.zzWY, Boolean.valueOf(this.zzWZ), Boolean.valueOf(this.zzXa), this.zzXb);
}
public void writeToParcel(Parcel out, int flags) {
zzd.zza(this, out, flags);
}
@Nullable
public Long zzkh() {
return this.zzWY;
}
public boolean zzki() {
return this.zzWZ;
}
public boolean zzkj() {
return this.zzXa;
}
@Nullable
public List<String> zzkk() {
return this.zzXb;
}
}
| 3,145 | 0.631161 | 0.629253 | 104 | 29.240385 | 31.25223 | 201 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673077 | false | false | 4 |
153c093ca0edd7d5eeadc6bc9e1de54556378c50 | 11,381,663,404,193 | 69721b9e1ab727aab59c68baafd9527aff92d22b | /Main.java | 727d9da27a4b7cd470da6c74975028872c3a9a4b | []
| no_license | ThatMelo/MelosBuildTools | https://github.com/ThatMelo/MelosBuildTools | 199ec1bdb54913c99f4f0eaf5774655629016516 | 36a4373019d7339fe81459da41cf4ebe6eb904f5 | refs/heads/main | 2023-04-14T12:40:38.406000 | 2021-04-16T13:50:15 | 2021-04-16T13:50:15 | 358,613,689 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.Melo.MelosBuildTools;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Rotation;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
ShapedRecipe InvisibleInatorRecipe = getInvisibleInatorRecipe();
@Override
public void onEnable() {
Bukkit.addRecipe(InvisibleInatorRecipe);
Bukkit.broadcastMessage(ChatColor.DARK_PURPLE + "MelosBuildTools Ready");
this.getServer().getPluginManager().registerEvents(this, this);
}
@Override
public void onDisable() {
Bukkit.clearRecipes();
}
int repeatTimes;
int effRange;
public void getINATORArgs( String[] arguments) {
//get range
if (arguments.length > 0) {
try {
effRange = Integer.parseInt(arguments[0]);
}
catch (NumberFormatException e) {
effRange = 2;
}
}
else {
effRange = 2;
}
}
public ItemStack GetINATORItemStack() {
ItemStack item = new ItemStack(Material.GOLDEN_CARROT);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + "INVISIBLE-INATOR");
meta.setUnbreakable(true);
meta.addEnchant( Enchantment.DURABILITY , 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
ArrayList<String> lore = new ArrayList<String>();
lore.add("makes itemframes invisible");
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
//EventHandler
@EventHandler
public void onInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer(); //get player
//tests
if (player.isSneaking()) return;//check for sneaking
ItemStack mainHand = player.getInventory().getItemInMainHand();
if (mainHand == null) return;// check for item
if (!mainHand.hasItemMeta()) return; //check for meta
ItemMeta meta = mainHand.getItemMeta();//get meta
if (!meta.hasDisplayName()) return;//check for display name
if (!meta.getDisplayName().contains("INVISIBLE-INATOR") || !meta.hasLore()) return;//check for name/lore
if (!(event.getRightClicked() instanceof ItemFrame)) return; // stop the code if it's not an itemframe
ItemFrame itemFrame = (ItemFrame) event.getRightClicked(); // get the ItemFrame object
itemFrame.setVisible(!itemFrame.isVisible()); // if it's visible, make it invisible and vice versa
Rotation itemframeRotation = itemFrame.getRotation();
itemFrame.setRotation(itemframeRotation);
event.setCancelled(true);
}
//
@Override
public boolean onCommand(CommandSender sender, Command cmd,String label,String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Console cannot run this command");
return true;
}
Player player = (Player) sender;
if (label.equalsIgnoreCase("invisibleinator")) {
if (player.hasPermission("melosbuildtools.invisibleinator")) {
if (!(player.getInventory().contains(Material.AIR))) return false;
player.sendMessage(ChatColor.AQUA + "Item delivered!");
player.getInventory().addItem(GetINATORItemStack());
return true;
}
else {
player.sendMessage(ChatColor.RED + "No Permission");
return true;
}
}
return false;
}
// recipies
public ShapedRecipe getInvisibleInatorRecipe() {
ItemStack item = GetINATORItemStack();
NamespacedKey key = new NamespacedKey(this, "INVISIBLE-INATOR");
ShapedRecipe recipe = new ShapedRecipe(key, item);
recipe.shape(
" F ",
" G ",
" "
);
recipe.setIngredient('G',Material.GOLDEN_CARROT);
recipe.setIngredient('F',Material.FERMENTED_SPIDER_EYE);
return recipe;
}
}
| UTF-8 | Java | 4,159 | java | Main.java | Java | []
| null | []
| package me.Melo.MelosBuildTools;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.Rotation;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements Listener {
ShapedRecipe InvisibleInatorRecipe = getInvisibleInatorRecipe();
@Override
public void onEnable() {
Bukkit.addRecipe(InvisibleInatorRecipe);
Bukkit.broadcastMessage(ChatColor.DARK_PURPLE + "MelosBuildTools Ready");
this.getServer().getPluginManager().registerEvents(this, this);
}
@Override
public void onDisable() {
Bukkit.clearRecipes();
}
int repeatTimes;
int effRange;
public void getINATORArgs( String[] arguments) {
//get range
if (arguments.length > 0) {
try {
effRange = Integer.parseInt(arguments[0]);
}
catch (NumberFormatException e) {
effRange = 2;
}
}
else {
effRange = 2;
}
}
public ItemStack GetINATORItemStack() {
ItemStack item = new ItemStack(Material.GOLDEN_CARROT);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.GOLD + "INVISIBLE-INATOR");
meta.setUnbreakable(true);
meta.addEnchant( Enchantment.DURABILITY , 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
ArrayList<String> lore = new ArrayList<String>();
lore.add("makes itemframes invisible");
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
//EventHandler
@EventHandler
public void onInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer(); //get player
//tests
if (player.isSneaking()) return;//check for sneaking
ItemStack mainHand = player.getInventory().getItemInMainHand();
if (mainHand == null) return;// check for item
if (!mainHand.hasItemMeta()) return; //check for meta
ItemMeta meta = mainHand.getItemMeta();//get meta
if (!meta.hasDisplayName()) return;//check for display name
if (!meta.getDisplayName().contains("INVISIBLE-INATOR") || !meta.hasLore()) return;//check for name/lore
if (!(event.getRightClicked() instanceof ItemFrame)) return; // stop the code if it's not an itemframe
ItemFrame itemFrame = (ItemFrame) event.getRightClicked(); // get the ItemFrame object
itemFrame.setVisible(!itemFrame.isVisible()); // if it's visible, make it invisible and vice versa
Rotation itemframeRotation = itemFrame.getRotation();
itemFrame.setRotation(itemframeRotation);
event.setCancelled(true);
}
//
@Override
public boolean onCommand(CommandSender sender, Command cmd,String label,String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Console cannot run this command");
return true;
}
Player player = (Player) sender;
if (label.equalsIgnoreCase("invisibleinator")) {
if (player.hasPermission("melosbuildtools.invisibleinator")) {
if (!(player.getInventory().contains(Material.AIR))) return false;
player.sendMessage(ChatColor.AQUA + "Item delivered!");
player.getInventory().addItem(GetINATORItemStack());
return true;
}
else {
player.sendMessage(ChatColor.RED + "No Permission");
return true;
}
}
return false;
}
// recipies
public ShapedRecipe getInvisibleInatorRecipe() {
ItemStack item = GetINATORItemStack();
NamespacedKey key = new NamespacedKey(this, "INVISIBLE-INATOR");
ShapedRecipe recipe = new ShapedRecipe(key, item);
recipe.shape(
" F ",
" G ",
" "
);
recipe.setIngredient('G',Material.GOLDEN_CARROT);
recipe.setIngredient('F',Material.FERMENTED_SPIDER_EYE);
return recipe;
}
}
| 4,159 | 0.722529 | 0.721327 | 149 | 26.912752 | 25.383484 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.234899 | false | false | 4 |
616ecf71c2b9b11e0495ddbdfd2dffcaec14c69c | 4,922,032,538,868 | 22ea26a6084e1f8e71bbb822aab0d590ff8722ee | /Movie/src/Rank/totalMovieRank.java | 316fc8414f4350ca6d6d9a58669c031284c97c71 | []
| no_license | J-LiNDBERG/J_Dev | https://github.com/J-LiNDBERG/J_Dev | c3a720c838335a6ff35f7f9d1f23dc9c14e42f93 | 38d8c6970b1d1d3da2e37ba57b33f34dde10e8d4 | refs/heads/master | 2016-09-07T01:48:12.962000 | 2015-05-14T23:32:35 | 2015-05-14T23:32:35 | 35,647,442 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Rank;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAOs.MovieDAO;
import DAOs.cntDAO;
import DAOs.staffDetailDAO;
import DTOs.MovieDTO;
import DTOs.avgDTO;
import DTOs.cntDTO;
import DTOs.staffDetailDTO;
@WebServlet(name = "totalMovieRank", urlPatterns = { "/totalMovieRank.do" })
public class totalMovieRank extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<avgDTO> adto = null;
cntDAO cdao1 = new cntDAO();
adto = cdao1.avgRank();
ArrayList<MovieDTO> arr=new ArrayList<MovieDTO>();
MovieDTO mdto =null;
MovieDAO mdao=new MovieDAO();
for(int i=0;i<adto.size();i++){
mdto=mdao.avgMovieRank(adto.get(i).getMid());
arr.add(mdto);
}
cntDAO cdao=new cntDAO();
ArrayList<avgDTO> adto1=cdao.avgScore();
ArrayList<ArrayList<staffDetailDTO>> totalSdto = new ArrayList<ArrayList<staffDetailDTO>>();
ArrayList<staffDetailDTO> sdto = null;
staffDetailDAO sdao = new staffDetailDAO();
for (int i = 0; i < arr.size(); i++) {
sdto = sdao.InqStaffs(arr.get(i).getMid());
totalSdto.add(sdto);
}
String body_path = "";
body_path = "Rank/boxMain.jsp";
request.setAttribute("body_path", body_path);
request.setAttribute("totalSdto", totalSdto);
request.setAttribute("avgdto", adto1);
request.setAttribute("mdto", arr);
RequestDispatcher dis = request
.getRequestDispatcher("/mainTemplate.jsp");
dis.forward(request, response);
}
}
| UTF-8 | Java | 1,805 | java | totalMovieRank.java | Java | []
| null | []
| package Rank;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DAOs.MovieDAO;
import DAOs.cntDAO;
import DAOs.staffDetailDAO;
import DTOs.MovieDTO;
import DTOs.avgDTO;
import DTOs.cntDTO;
import DTOs.staffDetailDTO;
@WebServlet(name = "totalMovieRank", urlPatterns = { "/totalMovieRank.do" })
public class totalMovieRank extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<avgDTO> adto = null;
cntDAO cdao1 = new cntDAO();
adto = cdao1.avgRank();
ArrayList<MovieDTO> arr=new ArrayList<MovieDTO>();
MovieDTO mdto =null;
MovieDAO mdao=new MovieDAO();
for(int i=0;i<adto.size();i++){
mdto=mdao.avgMovieRank(adto.get(i).getMid());
arr.add(mdto);
}
cntDAO cdao=new cntDAO();
ArrayList<avgDTO> adto1=cdao.avgScore();
ArrayList<ArrayList<staffDetailDTO>> totalSdto = new ArrayList<ArrayList<staffDetailDTO>>();
ArrayList<staffDetailDTO> sdto = null;
staffDetailDAO sdao = new staffDetailDAO();
for (int i = 0; i < arr.size(); i++) {
sdto = sdao.InqStaffs(arr.get(i).getMid());
totalSdto.add(sdto);
}
String body_path = "";
body_path = "Rank/boxMain.jsp";
request.setAttribute("body_path", body_path);
request.setAttribute("totalSdto", totalSdto);
request.setAttribute("avgdto", adto1);
request.setAttribute("mdto", arr);
RequestDispatcher dis = request
.getRequestDispatcher("/mainTemplate.jsp");
dis.forward(request, response);
}
}
| 1,805 | 0.730194 | 0.72687 | 73 | 23.726027 | 23.269865 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.90411 | false | false | 4 |
f6b8f66be2ef9c03e8dc3264d232a6960a610fa1 | 20,847,771,292,038 | ce1295adbab192fa801ebaba23bafaa70ee4d8b2 | /code/mapspotter/process/topic/src/main/java/com/navinfo/mapspotter/process/topic/restriction/io/CrossInformationVistor.java | a175d80fe6bc3f88c2b57906439d586e68a474b3 | []
| no_license | ziyunhai/zhuhai_air_show | https://github.com/ziyunhai/zhuhai_air_show | 2b4c22185b28810772ec3a0c734b69ebac549280 | f1215345b78a65a8838e5fd71351d156ad392ffe | refs/heads/master | 2020-05-02T21:41:47.493000 | 2016-09-22T02:50:21 | 2016-09-22T02:50:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.navinfo.mapspotter.process.topic.restriction.io;
import com.navinfo.mapspotter.foundation.algorithm.DoubleMatrix;
import com.navinfo.mapspotter.foundation.algorithm.rtree.SimplePointRTree;
import com.navinfo.mapspotter.foundation.util.IntCoordinate;
import com.navinfo.mapspotter.foundation.util.JsonUtil;
import com.navinfo.mapspotter.foundation.util.SerializeUtil;
import com.navinfo.mapspotter.process.topic.restriction.CrossRaster;
import com.navinfo.mapspotter.process.topic.restriction.Link;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.geojson.Feature;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 基础路网路口信息访问接口
* Created by SongHuiXing on 2016/1/11.
*/
public class CrossInformationVistor {
public final static String s_IndexTableName = "cross_index";
public final static String s_InfoTableName = "cross_info";
private static byte[] s_analyPageEnvelopeCol = null;
private static byte[] s_analyRasterCol = null;
private static byte[] s_analyRasterColCount = null;
private static byte[] s_analyCrossEnvelopeCol = null;
private static byte[] s_analyTileInfoCol = null;
private static byte[] s_infoPidCol = null;
private static byte[] s_infoEnvelopeCol = null;
private static byte[] s_infoRestricCol = null;
private static byte[] s_infoLinkDirectionCol = null;
private static byte[] s_infoMeshIdCol = null;
private static byte[] s_infoLinkEnvelopeCol = null;
private static byte[] s_infoLinksCol = null;
private static byte[] s_infoNodesCol = null;
private static byte[] s_infoParentCrossCol = null;
private static byte[] s_infoForbiddenTurnCol = null;
private static byte[] s_infoChildrenCrossCol = null;
private static SerializeUtil<int[][]> intMxUtil = new SerializeUtil<>();
private static SerializeUtil<double[]> doubleArrayUtil = new SerializeUtil<>();
private static SerializeUtil<long[]> longArrayUtil = new SerializeUtil<>();
private static SerializeUtil<ArrayList<BaseCrossJsonModel.TurnFromChild>> childCrossSerializer =
new SerializeUtil<>();
private static SerializeUtil<ArrayList<Map.Entry<String, IntCoordinate>>> arraySerilizeUtil =
new SerializeUtil<>();
static{
s_infoPidCol = Bytes.toBytes("PID");
s_infoEnvelopeCol = Bytes.toBytes("Envelope");
s_infoRestricCol = Bytes.toBytes("Restrictions");
s_infoLinkDirectionCol = Bytes.toBytes("LinkDirection");
s_infoLinkEnvelopeCol = Bytes.toBytes("LinkEnvelope");
s_infoLinksCol = Bytes.toBytes("Links");
s_infoNodesCol = Bytes.toBytes("Nodes");
s_infoMeshIdCol = Bytes.toBytes("Mesh");
s_infoParentCrossCol = Bytes.toBytes("ParentCrossID");
s_infoForbiddenTurnCol = Bytes.toBytes("ForbiddenTurn");
s_infoChildrenCrossCol = Bytes.toBytes("ChildrenCrosses");
s_analyPageEnvelopeCol = Bytes.toBytes("PageEnvelope");
s_analyCrossEnvelopeCol = Bytes.toBytes("CrossEnvelope");
s_analyRasterCol = Bytes.toBytes("Raster");
s_analyRasterColCount = Bytes.toBytes("ColCount");
s_analyTileInfoCol = Bytes.toBytes("TileInfo");
}
public static Configuration getHBaseConfig(){
Configuration cfg = HBaseConfiguration.create();
cfg.set("hbase.zookeeper.quorum", "Master.Hadoop:2181");
cfg.set("hbase.master", "Slave3.Hadoop");
cfg.set("hbase.client.scanner.timeout.period", "60000");
return cfg;
}
public final byte[] indexPageFamily;
public final byte[] rasterColFamily;
public final byte[] baseinfoColFamily;
public CrossInformationVistor(String infoColFamilyName,
String rasterColFamilyName,
String indexColFamilyName){
if(null != infoColFamilyName){
baseinfoColFamily = Bytes.toBytes(infoColFamilyName);
} else {
baseinfoColFamily = Bytes.toBytes("Information");
}
if(null != rasterColFamilyName){
rasterColFamily = Bytes.toBytes(rasterColFamilyName);
} else {
rasterColFamily = Bytes.toBytes("Analysis");
}
if(null != indexColFamilyName){
indexPageFamily = Bytes.toBytes(indexColFamilyName);
} else {
indexPageFamily = Bytes.toBytes("Page1");
}
}
/**
* 构建路口索引的HBase put 信息
* @param raster
* @return
*/
public Put convertCrossIndexJson2Put(CrossRaster raster){
StringBuilder rowKey = new StringBuilder(getPidString(raster.getPid()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
pt.addColumn(indexPageFamily,
s_analyPageEnvelopeCol,
doubleArrayUtil.serialize(raster.getPageEnvelope()));
return pt;
}
/**
* 构建路口基本信息的Put
* @param crossJson
* @return
*/
public Put convertCrossJson2Put(BaseCrossJsonModel crossJson){
StringBuilder rowKey = new StringBuilder(getPidString(crossJson.getPID()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
pt.addColumn(baseinfoColFamily, s_infoPidCol, Bytes.toBytes(crossJson.getPID()));
pt.addColumn(baseinfoColFamily, s_infoMeshIdCol, Bytes.toBytes(crossJson.getMesh()));
pt.addColumn(baseinfoColFamily, s_infoRestricCol, Bytes.toBytes(crossJson.getRestriction()));
pt.addColumn(baseinfoColFamily, s_infoLinkDirectionCol, Bytes.toBytes(crossJson.getLinkDirection()));
pt.addColumn(baseinfoColFamily, s_infoEnvelopeCol, Bytes.toBytes(crossJson.getEnvelope()));
pt.addColumn(baseinfoColFamily, s_infoLinkEnvelopeCol, Bytes.toBytes(crossJson.getLinkenvelope()));
pt.addColumn(baseinfoColFamily, s_infoLinksCol, Bytes.toBytes(crossJson.getLinks()));
pt.addColumn(baseinfoColFamily, s_infoNodesCol, Bytes.toBytes(crossJson.getNodes()));
pt.addColumn(baseinfoColFamily, s_infoParentCrossCol, Bytes.toBytes(crossJson.getParentCrossPid()));
pt.addColumn(baseinfoColFamily, s_infoForbiddenTurnCol, longArrayUtil.serialize(crossJson.getForbiddenUTurn()));
pt.addColumn(baseinfoColFamily, s_infoChildrenCrossCol, childCrossSerializer.serialize(crossJson.getChildTurns()));
return pt;
}
/**
* 构建路口栅格的Put
* @param raster
* @return
*/
public Put convertCrossRaster2Put(CrossRaster raster){
StringBuilder rowKey = new StringBuilder(getPidString(raster.getPid()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
int[][] sparseInt = raster.getSparseRaster();
pt.addColumn(rasterColFamily, s_analyCrossEnvelopeCol, doubleArrayUtil.serialize(raster.getCrossEnvelope()));
pt.addColumn(rasterColFamily, s_analyPageEnvelopeCol, doubleArrayUtil.serialize(raster.getPageEnvelope()));
pt.addColumn(rasterColFamily, s_analyRasterCol, intMxUtil.serialize(sparseInt));
pt.addColumn(rasterColFamily, s_analyRasterColCount, Bytes.toBytes(raster.getRasterColCount()));
pt.addColumn(rasterColFamily, s_analyTileInfoCol, arraySerilizeUtil.serialize(raster.getCornerTilePos()));
return pt;
}
public static String getPidString(long pid){
return String.format("%08x", pid);
}
public static long getPid(String pidStr){
return Long.parseLong(pidStr, 16);
}
private Connection m_hbaseConn = null;
public boolean prepare(){
if(null == m_hbaseConn || m_hbaseConn.isClosed()){
try {
m_hbaseConn = ConnectionFactory.createConnection(getHBaseConfig());
} catch (IOException e) {
e.printStackTrace();
}
}
if(null == m_hbaseConn) {
return false;
} else {
return true;
}
}
public void shutdown(){
if(null != m_hbaseConn){
try {
if(!m_hbaseConn.isClosed())
m_hbaseConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取路口关联的Node和Link信息
* @param crosspid
* @return
*/
public BaseCrossJsonModel getNodeAndLinks(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
BaseCrossJsonModel crossbasicInfo = new BaseCrossJsonModel();
crossbasicInfo.setPID(crosspid);
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoLinksCol);
gt.addColumn(baseinfoColFamily, s_infoNodesCol);
gt.addColumn(baseinfoColFamily, s_infoLinkDirectionCol);
Result re = targetTable.get(gt);
crossbasicInfo.setLinks(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)));
crossbasicInfo.setNodes(Bytes.toString(re.getValue(baseinfoColFamily, s_infoNodesCol)));
crossbasicInfo.setLinkDirection(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkDirectionCol)));
} catch (IOException e) {
e.printStackTrace();
}
return crossbasicInfo;
}
public List<Link> getLinks(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
List<Link> links = null;
JsonUtil jsonUtil = JsonUtil.getInstance();
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoLinksCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
links = Link.convert(
jsonUtil.readCollection(
Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)),
Feature.class)
);
} catch (IOException e) {
e.printStackTrace();
}
return links;
}
/**
* 获取路口基础信息
* @param crosspid
* @return
*/
public BaseCrossJsonModel getCrossInfomation(String crosspid){
StringBuilder rowKey = new StringBuilder(crosspid);
BaseCrossJsonModel crossbasicInfo = new BaseCrossJsonModel();
crossbasicInfo.setPID(getPid(crosspid));
JsonUtil jsonUtil = JsonUtil.getInstance();
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addFamily(baseinfoColFamily);
Result re = targetTable.get(gt);
crossbasicInfo.setMesh(Bytes.toString(re.getValue(baseinfoColFamily, s_infoMeshIdCol)));
crossbasicInfo.setEnvelope(Bytes.toString(re.getValue(baseinfoColFamily, s_infoEnvelopeCol)));
crossbasicInfo.setLinkenvelope(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkEnvelopeCol)));
crossbasicInfo.setLinks(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)));
crossbasicInfo.setNodes(Bytes.toString(re.getValue(baseinfoColFamily, s_infoNodesCol)));
crossbasicInfo.setRestriction(Bytes.toString(re.getValue(baseinfoColFamily, s_infoRestricCol)));
crossbasicInfo.setLinkDirection(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkDirectionCol)));
crossbasicInfo.setParentCrossPid(Bytes.toLong(re.getValue(baseinfoColFamily, s_infoParentCrossCol)));
crossbasicInfo.setForbiddenUTurn(longArrayUtil.deserialize(re.getValue(baseinfoColFamily, s_infoForbiddenTurnCol)));
crossbasicInfo.setChildTurns(childCrossSerializer.deserialize(re.getValue(baseinfoColFamily, s_infoChildrenCrossCol)));
} catch (IOException e) {
e.printStackTrace();
}
return crossbasicInfo;
}
/**
* 获取路口母库的交限矩阵
* @param crosspid
* @return
*/
public int[][] getOriginalRestrictionMatrix(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
int[][] resMatrix = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoRestricCol);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
List<int[]> matrix =
JsonUtil.getInstance().readIntMatrix(re.getValue(baseinfoColFamily, s_infoRestricCol));
if (matrix.size() > 0) {
int rowCount = matrix.size();
int colCount = matrix.get(0).length;
resMatrix = new int[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
int[] row = matrix.get(i);
System.arraycopy(row, 0, resMatrix[i], 0, colCount);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return resMatrix;
}
/**
* 获取路口的子路口调头信息
* @param crosspid
* @return
*/
public ArrayList<BaseCrossJsonModel.TurnFromChild> getChildrenTurns(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoChildrenCrossCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
return childCrossSerializer.deserialize(re.getValue(baseinfoColFamily, s_infoChildrenCrossCol));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取该路口作为子路口时的理论禁调
* @param crosspid
* @return [进入linkid,退出linkid] 如果不是子路口则返回null
*/
public long[] getTheoryForbiddenTurn4Child(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoParentCrossCol);
gt.addColumn(baseinfoColFamily, s_infoForbiddenTurnCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
long parentCrossid = Bytes.toLong(re.getValue(baseinfoColFamily, s_infoParentCrossCol));
if(-1 == parentCrossid)
return null;
return longArrayUtil.deserialize(re.getValue(baseinfoColFamily, s_infoForbiddenTurnCol));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过HBase中的路口索引表格构建内存索引
* @return
*/
public SimplePointRTree buildMemIndex(){
double[] indexEnv = new double[]{70, 10, 140, 60};
short indexLevel = 9;
SimplePointRTree tree = new SimplePointRTree(indexEnv, indexLevel);
ResultScanner rsScanner = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_IndexTableName))){
Scan sc = new Scan();
sc.addFamily(indexPageFamily);
sc.setCacheBlocks(false);
sc.setCaching(1000);
rsScanner = targetTable.getScanner(sc);
StringBuilder rowkeyReverser = new StringBuilder(8);
for(Result re : rsScanner){
rowkeyReverser.replace(0, 8, Bytes.toString(re.getRow()));
long id = getPid(rowkeyReverser.reverse().toString());
double[] pageenv =
doubleArrayUtil.deserialize(re.getValue(indexPageFamily, s_analyPageEnvelopeCol));
CrossPosition crossInx = new CrossPosition(pageenv,id);
tree.insert(crossInx);
}
rsScanner.close();
rsScanner = null;
} catch (IOException e) {
e.printStackTrace();
} finally{
if(null != rsScanner){
rsScanner.close();
}
}
return tree;
}
/**
* 获取路口栅格
* @param crosspid
* @return
*/
public CrossRaster getCrossesRaster(long crosspid){
return getCrossesRaster(getPidString(crosspid));
}
/**
* 获取路口栅格
* @param crosspid
* @return
*/
public CrossRaster getCrossesRaster(String crosspid){
CrossRaster raster = null;
long pid = getPid(crosspid);
StringBuilder rowKey = new StringBuilder(crosspid);
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addFamily(rasterColFamily);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
raster = new CrossRaster();
raster.setPid(pid);
raster.setCrossEnvelope(doubleArrayUtil.deserialize(re.getValue(rasterColFamily, s_analyCrossEnvelopeCol)));
raster.setPageEnvelope(doubleArrayUtil.deserialize(re.getValue(rasterColFamily, s_analyPageEnvelopeCol)));
int[][] sparse = intMxUtil.deserialize(re.getValue(rasterColFamily, s_analyRasterCol));
raster.setSparseRaster(sparse);
int colCount = Bytes.toInt(re.getValue(rasterColFamily, s_analyRasterColCount));
raster.setRasterColCount(colCount);
raster.setCorner_tile_pos(arraySerilizeUtil.deserialize(re.getValue(rasterColFamily, s_analyTileInfoCol)));
}
} catch (IOException e) {
System.err.println(String.format("Can't find raster with %d", pid));
e.printStackTrace();
}
return raster;
}
/**
* 查询路口的meshid
* @param crosspid
* @return
*/
public int getCrossMeshID(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
int meshid = 0;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoMeshIdCol);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
String mesh = Bytes.toString(re.getValue(baseinfoColFamily, s_infoMeshIdCol));
meshid = Integer.parseInt(mesh);
}
} catch (IOException e) {
e.printStackTrace();
}
return meshid;
}
/**
* 将所有路口栅格以图片的形式输出到目标文件夹
* @param outFolder
* @return
*/
public int exportCrossRaster(String outFolder){
int crossCount = 0;
ResultScanner rsScanner = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Scan scan = new Scan();
scan.addColumn(rasterColFamily, s_analyRasterCol);
scan.addColumn(rasterColFamily, s_analyRasterColCount);
scan.setCacheBlocks(false);
scan.setBatch(2);
rsScanner = targetTable.getScanner(scan);
for(Result re : rsScanner){
StringBuilder rowkey = new StringBuilder(Bytes.toString(re.getRow()));
long crosspid = getPid(rowkey.reverse().toString());
int[][] sparse = intMxUtil.deserialize(re.getValue(rasterColFamily, s_analyRasterCol));
int colCount = Bytes.toInt(re.getValue(rasterColFamily, s_analyRasterColCount));
DoubleMatrix mx = DoubleMatrix.fromSparse(sparse[0], sparse[1], sparse[2], colCount);
BufferedImage bimage = new BufferedImage(mx.columns, mx.rows,
BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < mx.rows; i++) {
for (int j = 0; j < mx.columns; j++) {
int v = (int)mx.get(i, j);
Color color = null;
if(v == 255){
color = Color.BLACK;
}else if(v == 0) {
color = new Color(255, 255, 255, 255);
} else {
int g = 0, b = 0;
int r = v % 3;
v = v / 3;
if(v > 0) {
g = v % 3;
v = v / 3;
}
if(v > 0){
b = v % 3;
}
color = new Color(255*r/3, 255*g/3, 255*b/3);
}
bimage.setRGB(j, i, color.getRGB());
}
}
File f = new File(String.format("%s\\%d.jpg", outFolder, crosspid));
ImageIO.write(bimage, "jpg", f);
crossCount++;
}
rsScanner.close();
rsScanner = null;
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}finally {
if(null != rsScanner){
rsScanner.close();
}
}
return crossCount;
}
}
| UTF-8 | Java | 22,554 | java | CrossInformationVistor.java | Java | [
{
"context": " java.util.Map;\n\n/**\n * 基础路网路口信息访问接口\n * Created by SongHuiXing on 2016/1/11.\n */\npublic class CrossInformationVi",
"end": 1016,
"score": 0.9990653991699219,
"start": 1005,
"tag": "NAME",
"value": "SongHuiXing"
}
]
| null | []
| package com.navinfo.mapspotter.process.topic.restriction.io;
import com.navinfo.mapspotter.foundation.algorithm.DoubleMatrix;
import com.navinfo.mapspotter.foundation.algorithm.rtree.SimplePointRTree;
import com.navinfo.mapspotter.foundation.util.IntCoordinate;
import com.navinfo.mapspotter.foundation.util.JsonUtil;
import com.navinfo.mapspotter.foundation.util.SerializeUtil;
import com.navinfo.mapspotter.process.topic.restriction.CrossRaster;
import com.navinfo.mapspotter.process.topic.restriction.Link;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.geojson.Feature;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 基础路网路口信息访问接口
* Created by SongHuiXing on 2016/1/11.
*/
public class CrossInformationVistor {
public final static String s_IndexTableName = "cross_index";
public final static String s_InfoTableName = "cross_info";
private static byte[] s_analyPageEnvelopeCol = null;
private static byte[] s_analyRasterCol = null;
private static byte[] s_analyRasterColCount = null;
private static byte[] s_analyCrossEnvelopeCol = null;
private static byte[] s_analyTileInfoCol = null;
private static byte[] s_infoPidCol = null;
private static byte[] s_infoEnvelopeCol = null;
private static byte[] s_infoRestricCol = null;
private static byte[] s_infoLinkDirectionCol = null;
private static byte[] s_infoMeshIdCol = null;
private static byte[] s_infoLinkEnvelopeCol = null;
private static byte[] s_infoLinksCol = null;
private static byte[] s_infoNodesCol = null;
private static byte[] s_infoParentCrossCol = null;
private static byte[] s_infoForbiddenTurnCol = null;
private static byte[] s_infoChildrenCrossCol = null;
private static SerializeUtil<int[][]> intMxUtil = new SerializeUtil<>();
private static SerializeUtil<double[]> doubleArrayUtil = new SerializeUtil<>();
private static SerializeUtil<long[]> longArrayUtil = new SerializeUtil<>();
private static SerializeUtil<ArrayList<BaseCrossJsonModel.TurnFromChild>> childCrossSerializer =
new SerializeUtil<>();
private static SerializeUtil<ArrayList<Map.Entry<String, IntCoordinate>>> arraySerilizeUtil =
new SerializeUtil<>();
static{
s_infoPidCol = Bytes.toBytes("PID");
s_infoEnvelopeCol = Bytes.toBytes("Envelope");
s_infoRestricCol = Bytes.toBytes("Restrictions");
s_infoLinkDirectionCol = Bytes.toBytes("LinkDirection");
s_infoLinkEnvelopeCol = Bytes.toBytes("LinkEnvelope");
s_infoLinksCol = Bytes.toBytes("Links");
s_infoNodesCol = Bytes.toBytes("Nodes");
s_infoMeshIdCol = Bytes.toBytes("Mesh");
s_infoParentCrossCol = Bytes.toBytes("ParentCrossID");
s_infoForbiddenTurnCol = Bytes.toBytes("ForbiddenTurn");
s_infoChildrenCrossCol = Bytes.toBytes("ChildrenCrosses");
s_analyPageEnvelopeCol = Bytes.toBytes("PageEnvelope");
s_analyCrossEnvelopeCol = Bytes.toBytes("CrossEnvelope");
s_analyRasterCol = Bytes.toBytes("Raster");
s_analyRasterColCount = Bytes.toBytes("ColCount");
s_analyTileInfoCol = Bytes.toBytes("TileInfo");
}
public static Configuration getHBaseConfig(){
Configuration cfg = HBaseConfiguration.create();
cfg.set("hbase.zookeeper.quorum", "Master.Hadoop:2181");
cfg.set("hbase.master", "Slave3.Hadoop");
cfg.set("hbase.client.scanner.timeout.period", "60000");
return cfg;
}
public final byte[] indexPageFamily;
public final byte[] rasterColFamily;
public final byte[] baseinfoColFamily;
public CrossInformationVistor(String infoColFamilyName,
String rasterColFamilyName,
String indexColFamilyName){
if(null != infoColFamilyName){
baseinfoColFamily = Bytes.toBytes(infoColFamilyName);
} else {
baseinfoColFamily = Bytes.toBytes("Information");
}
if(null != rasterColFamilyName){
rasterColFamily = Bytes.toBytes(rasterColFamilyName);
} else {
rasterColFamily = Bytes.toBytes("Analysis");
}
if(null != indexColFamilyName){
indexPageFamily = Bytes.toBytes(indexColFamilyName);
} else {
indexPageFamily = Bytes.toBytes("Page1");
}
}
/**
* 构建路口索引的HBase put 信息
* @param raster
* @return
*/
public Put convertCrossIndexJson2Put(CrossRaster raster){
StringBuilder rowKey = new StringBuilder(getPidString(raster.getPid()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
pt.addColumn(indexPageFamily,
s_analyPageEnvelopeCol,
doubleArrayUtil.serialize(raster.getPageEnvelope()));
return pt;
}
/**
* 构建路口基本信息的Put
* @param crossJson
* @return
*/
public Put convertCrossJson2Put(BaseCrossJsonModel crossJson){
StringBuilder rowKey = new StringBuilder(getPidString(crossJson.getPID()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
pt.addColumn(baseinfoColFamily, s_infoPidCol, Bytes.toBytes(crossJson.getPID()));
pt.addColumn(baseinfoColFamily, s_infoMeshIdCol, Bytes.toBytes(crossJson.getMesh()));
pt.addColumn(baseinfoColFamily, s_infoRestricCol, Bytes.toBytes(crossJson.getRestriction()));
pt.addColumn(baseinfoColFamily, s_infoLinkDirectionCol, Bytes.toBytes(crossJson.getLinkDirection()));
pt.addColumn(baseinfoColFamily, s_infoEnvelopeCol, Bytes.toBytes(crossJson.getEnvelope()));
pt.addColumn(baseinfoColFamily, s_infoLinkEnvelopeCol, Bytes.toBytes(crossJson.getLinkenvelope()));
pt.addColumn(baseinfoColFamily, s_infoLinksCol, Bytes.toBytes(crossJson.getLinks()));
pt.addColumn(baseinfoColFamily, s_infoNodesCol, Bytes.toBytes(crossJson.getNodes()));
pt.addColumn(baseinfoColFamily, s_infoParentCrossCol, Bytes.toBytes(crossJson.getParentCrossPid()));
pt.addColumn(baseinfoColFamily, s_infoForbiddenTurnCol, longArrayUtil.serialize(crossJson.getForbiddenUTurn()));
pt.addColumn(baseinfoColFamily, s_infoChildrenCrossCol, childCrossSerializer.serialize(crossJson.getChildTurns()));
return pt;
}
/**
* 构建路口栅格的Put
* @param raster
* @return
*/
public Put convertCrossRaster2Put(CrossRaster raster){
StringBuilder rowKey = new StringBuilder(getPidString(raster.getPid()));
Put pt = new Put(Bytes.toBytes(rowKey.reverse().toString()));
int[][] sparseInt = raster.getSparseRaster();
pt.addColumn(rasterColFamily, s_analyCrossEnvelopeCol, doubleArrayUtil.serialize(raster.getCrossEnvelope()));
pt.addColumn(rasterColFamily, s_analyPageEnvelopeCol, doubleArrayUtil.serialize(raster.getPageEnvelope()));
pt.addColumn(rasterColFamily, s_analyRasterCol, intMxUtil.serialize(sparseInt));
pt.addColumn(rasterColFamily, s_analyRasterColCount, Bytes.toBytes(raster.getRasterColCount()));
pt.addColumn(rasterColFamily, s_analyTileInfoCol, arraySerilizeUtil.serialize(raster.getCornerTilePos()));
return pt;
}
public static String getPidString(long pid){
return String.format("%08x", pid);
}
public static long getPid(String pidStr){
return Long.parseLong(pidStr, 16);
}
private Connection m_hbaseConn = null;
public boolean prepare(){
if(null == m_hbaseConn || m_hbaseConn.isClosed()){
try {
m_hbaseConn = ConnectionFactory.createConnection(getHBaseConfig());
} catch (IOException e) {
e.printStackTrace();
}
}
if(null == m_hbaseConn) {
return false;
} else {
return true;
}
}
public void shutdown(){
if(null != m_hbaseConn){
try {
if(!m_hbaseConn.isClosed())
m_hbaseConn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取路口关联的Node和Link信息
* @param crosspid
* @return
*/
public BaseCrossJsonModel getNodeAndLinks(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
BaseCrossJsonModel crossbasicInfo = new BaseCrossJsonModel();
crossbasicInfo.setPID(crosspid);
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoLinksCol);
gt.addColumn(baseinfoColFamily, s_infoNodesCol);
gt.addColumn(baseinfoColFamily, s_infoLinkDirectionCol);
Result re = targetTable.get(gt);
crossbasicInfo.setLinks(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)));
crossbasicInfo.setNodes(Bytes.toString(re.getValue(baseinfoColFamily, s_infoNodesCol)));
crossbasicInfo.setLinkDirection(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkDirectionCol)));
} catch (IOException e) {
e.printStackTrace();
}
return crossbasicInfo;
}
public List<Link> getLinks(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
List<Link> links = null;
JsonUtil jsonUtil = JsonUtil.getInstance();
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoLinksCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
links = Link.convert(
jsonUtil.readCollection(
Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)),
Feature.class)
);
} catch (IOException e) {
e.printStackTrace();
}
return links;
}
/**
* 获取路口基础信息
* @param crosspid
* @return
*/
public BaseCrossJsonModel getCrossInfomation(String crosspid){
StringBuilder rowKey = new StringBuilder(crosspid);
BaseCrossJsonModel crossbasicInfo = new BaseCrossJsonModel();
crossbasicInfo.setPID(getPid(crosspid));
JsonUtil jsonUtil = JsonUtil.getInstance();
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addFamily(baseinfoColFamily);
Result re = targetTable.get(gt);
crossbasicInfo.setMesh(Bytes.toString(re.getValue(baseinfoColFamily, s_infoMeshIdCol)));
crossbasicInfo.setEnvelope(Bytes.toString(re.getValue(baseinfoColFamily, s_infoEnvelopeCol)));
crossbasicInfo.setLinkenvelope(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkEnvelopeCol)));
crossbasicInfo.setLinks(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinksCol)));
crossbasicInfo.setNodes(Bytes.toString(re.getValue(baseinfoColFamily, s_infoNodesCol)));
crossbasicInfo.setRestriction(Bytes.toString(re.getValue(baseinfoColFamily, s_infoRestricCol)));
crossbasicInfo.setLinkDirection(Bytes.toString(re.getValue(baseinfoColFamily, s_infoLinkDirectionCol)));
crossbasicInfo.setParentCrossPid(Bytes.toLong(re.getValue(baseinfoColFamily, s_infoParentCrossCol)));
crossbasicInfo.setForbiddenUTurn(longArrayUtil.deserialize(re.getValue(baseinfoColFamily, s_infoForbiddenTurnCol)));
crossbasicInfo.setChildTurns(childCrossSerializer.deserialize(re.getValue(baseinfoColFamily, s_infoChildrenCrossCol)));
} catch (IOException e) {
e.printStackTrace();
}
return crossbasicInfo;
}
/**
* 获取路口母库的交限矩阵
* @param crosspid
* @return
*/
public int[][] getOriginalRestrictionMatrix(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
int[][] resMatrix = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoRestricCol);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
List<int[]> matrix =
JsonUtil.getInstance().readIntMatrix(re.getValue(baseinfoColFamily, s_infoRestricCol));
if (matrix.size() > 0) {
int rowCount = matrix.size();
int colCount = matrix.get(0).length;
resMatrix = new int[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
int[] row = matrix.get(i);
System.arraycopy(row, 0, resMatrix[i], 0, colCount);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return resMatrix;
}
/**
* 获取路口的子路口调头信息
* @param crosspid
* @return
*/
public ArrayList<BaseCrossJsonModel.TurnFromChild> getChildrenTurns(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoChildrenCrossCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
return childCrossSerializer.deserialize(re.getValue(baseinfoColFamily, s_infoChildrenCrossCol));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取该路口作为子路口时的理论禁调
* @param crosspid
* @return [进入linkid,退出linkid] 如果不是子路口则返回null
*/
public long[] getTheoryForbiddenTurn4Child(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoParentCrossCol);
gt.addColumn(baseinfoColFamily, s_infoForbiddenTurnCol);
Result re = targetTable.get(gt);
if(re.isEmpty())
return null;
long parentCrossid = Bytes.toLong(re.getValue(baseinfoColFamily, s_infoParentCrossCol));
if(-1 == parentCrossid)
return null;
return longArrayUtil.deserialize(re.getValue(baseinfoColFamily, s_infoForbiddenTurnCol));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过HBase中的路口索引表格构建内存索引
* @return
*/
public SimplePointRTree buildMemIndex(){
double[] indexEnv = new double[]{70, 10, 140, 60};
short indexLevel = 9;
SimplePointRTree tree = new SimplePointRTree(indexEnv, indexLevel);
ResultScanner rsScanner = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_IndexTableName))){
Scan sc = new Scan();
sc.addFamily(indexPageFamily);
sc.setCacheBlocks(false);
sc.setCaching(1000);
rsScanner = targetTable.getScanner(sc);
StringBuilder rowkeyReverser = new StringBuilder(8);
for(Result re : rsScanner){
rowkeyReverser.replace(0, 8, Bytes.toString(re.getRow()));
long id = getPid(rowkeyReverser.reverse().toString());
double[] pageenv =
doubleArrayUtil.deserialize(re.getValue(indexPageFamily, s_analyPageEnvelopeCol));
CrossPosition crossInx = new CrossPosition(pageenv,id);
tree.insert(crossInx);
}
rsScanner.close();
rsScanner = null;
} catch (IOException e) {
e.printStackTrace();
} finally{
if(null != rsScanner){
rsScanner.close();
}
}
return tree;
}
/**
* 获取路口栅格
* @param crosspid
* @return
*/
public CrossRaster getCrossesRaster(long crosspid){
return getCrossesRaster(getPidString(crosspid));
}
/**
* 获取路口栅格
* @param crosspid
* @return
*/
public CrossRaster getCrossesRaster(String crosspid){
CrossRaster raster = null;
long pid = getPid(crosspid);
StringBuilder rowKey = new StringBuilder(crosspid);
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addFamily(rasterColFamily);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
raster = new CrossRaster();
raster.setPid(pid);
raster.setCrossEnvelope(doubleArrayUtil.deserialize(re.getValue(rasterColFamily, s_analyCrossEnvelopeCol)));
raster.setPageEnvelope(doubleArrayUtil.deserialize(re.getValue(rasterColFamily, s_analyPageEnvelopeCol)));
int[][] sparse = intMxUtil.deserialize(re.getValue(rasterColFamily, s_analyRasterCol));
raster.setSparseRaster(sparse);
int colCount = Bytes.toInt(re.getValue(rasterColFamily, s_analyRasterColCount));
raster.setRasterColCount(colCount);
raster.setCorner_tile_pos(arraySerilizeUtil.deserialize(re.getValue(rasterColFamily, s_analyTileInfoCol)));
}
} catch (IOException e) {
System.err.println(String.format("Can't find raster with %d", pid));
e.printStackTrace();
}
return raster;
}
/**
* 查询路口的meshid
* @param crosspid
* @return
*/
public int getCrossMeshID(long crosspid){
StringBuilder rowKey = new StringBuilder(getPidString(crosspid));
int meshid = 0;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Get gt = new Get(Bytes.toBytes(rowKey.reverse().toString()));
gt.addColumn(baseinfoColFamily, s_infoMeshIdCol);
Result re = targetTable.get(gt);
if(!re.isEmpty()) {
String mesh = Bytes.toString(re.getValue(baseinfoColFamily, s_infoMeshIdCol));
meshid = Integer.parseInt(mesh);
}
} catch (IOException e) {
e.printStackTrace();
}
return meshid;
}
/**
* 将所有路口栅格以图片的形式输出到目标文件夹
* @param outFolder
* @return
*/
public int exportCrossRaster(String outFolder){
int crossCount = 0;
ResultScanner rsScanner = null;
try(Table targetTable = m_hbaseConn.getTable(TableName.valueOf(s_InfoTableName))){
Scan scan = new Scan();
scan.addColumn(rasterColFamily, s_analyRasterCol);
scan.addColumn(rasterColFamily, s_analyRasterColCount);
scan.setCacheBlocks(false);
scan.setBatch(2);
rsScanner = targetTable.getScanner(scan);
for(Result re : rsScanner){
StringBuilder rowkey = new StringBuilder(Bytes.toString(re.getRow()));
long crosspid = getPid(rowkey.reverse().toString());
int[][] sparse = intMxUtil.deserialize(re.getValue(rasterColFamily, s_analyRasterCol));
int colCount = Bytes.toInt(re.getValue(rasterColFamily, s_analyRasterColCount));
DoubleMatrix mx = DoubleMatrix.fromSparse(sparse[0], sparse[1], sparse[2], colCount);
BufferedImage bimage = new BufferedImage(mx.columns, mx.rows,
BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < mx.rows; i++) {
for (int j = 0; j < mx.columns; j++) {
int v = (int)mx.get(i, j);
Color color = null;
if(v == 255){
color = Color.BLACK;
}else if(v == 0) {
color = new Color(255, 255, 255, 255);
} else {
int g = 0, b = 0;
int r = v % 3;
v = v / 3;
if(v > 0) {
g = v % 3;
v = v / 3;
}
if(v > 0){
b = v % 3;
}
color = new Color(255*r/3, 255*g/3, 255*b/3);
}
bimage.setRGB(j, i, color.getRGB());
}
}
File f = new File(String.format("%s\\%d.jpg", outFolder, crosspid));
ImageIO.write(bimage, "jpg", f);
crossCount++;
}
rsScanner.close();
rsScanner = null;
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}finally {
if(null != rsScanner){
rsScanner.close();
}
}
return crossCount;
}
}
| 22,554 | 0.611886 | 0.607657 | 621 | 34.79388 | 32.186794 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.623188 | false | false | 4 |
ac8c81826d19f47949729d2c19848cad19328bd7 | 10,325,101,411,526 | 178daf38a11fbddbe0bb71976c1075e597060da3 | /app/src/main/java/com/weiaibenpao/demo/chislim/ui/ShowMapActivity.java | 46807e6dab21223af9530fd8785974f6d7c4c772 | [
"Apache-2.0"
]
| permissive | Catfeeds/dongjiquan20170801 | https://github.com/Catfeeds/dongjiquan20170801 | b1c2eabb8d5e25624e63944ac0e7f78cd9d7228e | ec242ecef848247eb295f85f96b68889d9961e8b | refs/heads/master | 2020-04-11T02:47:37.440000 | 2017-08-23T05:43:20 | 2017-08-23T05:43:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.weiaibenpao.demo.chislim.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by zhangxing on 2016/12/19.
*/
public class ShowMapActivity extends AppCompatActivity {
ImageView backImg;
@BindView(R.id.back)
ImageView back;
@BindView(R.id.titleTv)
TextView titleTv;
@BindView(R.id.myTop)
RelativeLayout myTop;
@BindView(R.id.mySportTime)
TextView mySportTime;
@BindView(R.id.myDis)
TextView myDis;
@BindView(R.id.myTime)
TextView myTime;
@BindView(R.id.mySped)
TextView mySped;
@BindView(R.id.myCalior)
TextView myCalior;
@BindView(R.id.activity_medal)
RelativeLayout activityMedal;
@BindView(R.id.myStep)
TextView myStep;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap_layout);
StatusBarUtil.setColor(this , getResources().getColor(R.color.ku_bg ) , 0);
ButterKnife.bind(this);
backImg = (ImageView) findViewById(R.id.back);
backImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
int sportTime = getIntent().getIntExtra("sportTime", 0);//所用时间
int sportDistance = getIntent().getIntExtra("distance", 0);//距离
int calories = getIntent().getIntExtra("calories", 0);//大卡
String daytime = getIntent().getStringExtra("dayTime");//日期
int sportSped = getIntent().getIntExtra("sportSped", 0);//速度
String sportMapStr = getIntent().getStringExtra("sportImg");//url
int sportStep = getIntent().getIntExtra("sportStep", 0);//步数
mySportTime.setText(daytime);
myDis.setText(sportDistance + "");
myCalior.setText(calories + "");
myTime.setText(sportTime + "");
mySped.setText(sportSped + "");
myStep.setText(sportStep+"");
/* Picasso.with(this)
.load(sportMapStr)
.error(R.mipmap.zhanwei)
.placeholder(R.mipmap.zhanwei)
.into(sportImg);*/
}
}
| UTF-8 | Java | 2,562 | java | ShowMapActivity.java | Java | [
{
"context": "import butterknife.ButterKnife;\n\n/**\n * Created by zhangxing on 2016/12/19.\n */\n\npublic class ShowMapActivity ",
"end": 461,
"score": 0.9995267987251282,
"start": 452,
"tag": "USERNAME",
"value": "zhangxing"
}
]
| null | []
| package com.weiaibenpao.demo.chislim.ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.jaeger.library.StatusBarUtil;
import com.weiaibenpao.demo.chislim.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by zhangxing on 2016/12/19.
*/
public class ShowMapActivity extends AppCompatActivity {
ImageView backImg;
@BindView(R.id.back)
ImageView back;
@BindView(R.id.titleTv)
TextView titleTv;
@BindView(R.id.myTop)
RelativeLayout myTop;
@BindView(R.id.mySportTime)
TextView mySportTime;
@BindView(R.id.myDis)
TextView myDis;
@BindView(R.id.myTime)
TextView myTime;
@BindView(R.id.mySped)
TextView mySped;
@BindView(R.id.myCalior)
TextView myCalior;
@BindView(R.id.activity_medal)
RelativeLayout activityMedal;
@BindView(R.id.myStep)
TextView myStep;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap_layout);
StatusBarUtil.setColor(this , getResources().getColor(R.color.ku_bg ) , 0);
ButterKnife.bind(this);
backImg = (ImageView) findViewById(R.id.back);
backImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
int sportTime = getIntent().getIntExtra("sportTime", 0);//所用时间
int sportDistance = getIntent().getIntExtra("distance", 0);//距离
int calories = getIntent().getIntExtra("calories", 0);//大卡
String daytime = getIntent().getStringExtra("dayTime");//日期
int sportSped = getIntent().getIntExtra("sportSped", 0);//速度
String sportMapStr = getIntent().getStringExtra("sportImg");//url
int sportStep = getIntent().getIntExtra("sportStep", 0);//步数
mySportTime.setText(daytime);
myDis.setText(sportDistance + "");
myCalior.setText(calories + "");
myTime.setText(sportTime + "");
mySped.setText(sportSped + "");
myStep.setText(sportStep+"");
/* Picasso.with(this)
.load(sportMapStr)
.error(R.mipmap.zhanwei)
.placeholder(R.mipmap.zhanwei)
.into(sportImg);*/
}
}
| 2,562 | 0.657459 | 0.651539 | 81 | 30.283951 | 20.60998 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62963 | false | false | 4 |
7c18a721a2e1bb01feee29a87161e7f5ff40aa90 | 17,806,934,429,708 | faa238e42caac1080dce8eaa5dbfe687a638a830 | /person-management-api-reactive/src/main/java/com/api/common/exception/GlobalExceptionHandler.java | 903cb321556abf6dd8cb88822085337e84ad96f8 | []
| no_license | nirajsonawane/person-management-curd-system | https://github.com/nirajsonawane/person-management-curd-system | 879349c876958cfa4b4cc0d46d21521039205cfe | caa7e5c6786f07e45fefe8005d2e50644be6820b | refs/heads/master | 2023-01-08T22:17:22.656000 | 2020-01-26T20:38:35 | 2020-01-26T20:38:35 | 234,633,567 | 1 | 2 | null | false | 2023-01-01T15:40:34 | 2020-01-17T20:49:21 | 2020-01-31T22:42:16 | 2023-01-01T15:40:33 | 1,556 | 1 | 2 | 25 | Java | false | false | package com.api.common.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;
import java.util.List;
import java.util.stream.Collectors;
import static org.springframework.http.ResponseEntity.status;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(WebExchangeBindException.class)
protected ResponseEntity<ErrorDetails> handleWebExchangeBindException(WebExchangeBindException ex) {
log.error("Validation Error",ex);
List<String> errorList = ex
.getBindingResult()
.getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.toList());
ErrorDetails errorDetails = new ErrorDetails(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errorList);
return status(HttpStatus.BAD_REQUEST).body(errorDetails);
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
log.error("Exception caught in handleRuntimeException ", ex);
return status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
} | UTF-8 | Java | 1,503 | java | GlobalExceptionHandler.java | Java | []
| null | []
| package com.api.common.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.support.WebExchangeBindException;
import java.util.List;
import java.util.stream.Collectors;
import static org.springframework.http.ResponseEntity.status;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(WebExchangeBindException.class)
protected ResponseEntity<ErrorDetails> handleWebExchangeBindException(WebExchangeBindException ex) {
log.error("Validation Error",ex);
List<String> errorList = ex
.getBindingResult()
.getFieldErrors()
.stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.toList());
ErrorDetails errorDetails = new ErrorDetails(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errorList);
return status(HttpStatus.BAD_REQUEST).body(errorDetails);
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
log.error("Exception caught in handleRuntimeException ", ex);
return status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
}
} | 1,503 | 0.751164 | 0.749168 | 40 | 36.599998 | 29.875408 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 4 |
abbc56390ab76eedda7dd16b71fd92b949605488 | 36,532,991,845,177 | a6b8332d9c9f698eb2be59eaf7788ba165a77d65 | /src/main/java/com/crw/study/iterator/example1/PancakeHouseMenuIterator.java | 4f0fc150419cf82a32cd44c75e095d469528ba77 | []
| no_license | crrrrrw/java-desgin-patterns | https://github.com/crrrrrw/java-desgin-patterns | 4419b46758aec001bebc05731bb4da97d1cfed28 | 9e5c236964bf8a84a16d1b57c3ff6133c15edb99 | refs/heads/master | 2022-04-09T19:53:31.207000 | 2020-02-26T13:53:03 | 2020-02-26T13:53:03 | 115,080,988 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.crw.study.iterator.example1;
import java.util.List;
public class PancakeHouseMenuIterator implements Iterator {
List<MenuItem> menuItems;
int position = 0;
public PancakeHouseMenuIterator(List<MenuItem> menuItems) {
this.menuItems = menuItems;
}
@Override
public boolean hasNext() {
return menuItems.size() > 0 && position < menuItems.size();
}
@Override
public Object next() {
MenuItem menuItem = menuItems.get(position);
position++;
return menuItem;
}
}
| UTF-8 | Java | 553 | java | PancakeHouseMenuIterator.java | Java | []
| null | []
| package com.crw.study.iterator.example1;
import java.util.List;
public class PancakeHouseMenuIterator implements Iterator {
List<MenuItem> menuItems;
int position = 0;
public PancakeHouseMenuIterator(List<MenuItem> menuItems) {
this.menuItems = menuItems;
}
@Override
public boolean hasNext() {
return menuItems.size() > 0 && position < menuItems.size();
}
@Override
public Object next() {
MenuItem menuItem = menuItems.get(position);
position++;
return menuItem;
}
}
| 553 | 0.654611 | 0.649186 | 24 | 22.041666 | 20.917456 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 4 |
37c6ec381072d4e26e6d1682ce3445091257c791 | 33,981,781,284,958 | 781ffb75c79e1358eab8af22c9a82aee6fd37180 | /src/main/java/com/wtp/api/PublicApiDAO.java | 2e5082b3c1d036aed738d4aa681e5dc93f14d0e1 | []
| no_license | Ssuooo/webtemplate | https://github.com/Ssuooo/webtemplate | 1308cb035ed3a6b64e066b6ac8dced2293c8340c | 4d8900fdee3fc654c81379a82636e0dd2ab87376 | refs/heads/master | 2020-03-09T16:28:24.103000 | 2018-04-24T07:52:09 | 2018-04-24T07:52:09 | 128,777,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wtp.api;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.wtp.common.AbstractDAO;
@Repository("publicApiDAO")
public class PublicApiDAO extends AbstractDAO {
private final String NAMESPACE = "PublicAPI.";
public void insertApartRent(HashMap param) throws Exception {
master.insert(NAMESPACE +"insertApartRent", param);
}
public void insertApartTrade(HashMap param) throws Exception {
master.insert(NAMESPACE +"insertApartTrade", param);
}
public List<HashMap<String, Object>> selectApartRentList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectApartRentList", param);
}
public List<HashMap<String, Object>> selectApartTradeList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectApartTradeList", param);
}
public List<HashMap<String, Object>> selectRegionCodeList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectRegionCodeList", param);
}
}
| UTF-8 | Java | 1,039 | java | PublicApiDAO.java | Java | []
| null | []
| package com.wtp.api;
import java.util.HashMap;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.wtp.common.AbstractDAO;
@Repository("publicApiDAO")
public class PublicApiDAO extends AbstractDAO {
private final String NAMESPACE = "PublicAPI.";
public void insertApartRent(HashMap param) throws Exception {
master.insert(NAMESPACE +"insertApartRent", param);
}
public void insertApartTrade(HashMap param) throws Exception {
master.insert(NAMESPACE +"insertApartTrade", param);
}
public List<HashMap<String, Object>> selectApartRentList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectApartRentList", param);
}
public List<HashMap<String, Object>> selectApartTradeList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectApartTradeList", param);
}
public List<HashMap<String, Object>> selectRegionCodeList(HashMap param) throws Exception {
return slave.queryForList(NAMESPACE +"selectRegionCodeList", param);
}
}
| 1,039 | 0.781521 | 0.781521 | 33 | 30.484848 | 31.713797 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.393939 | false | false | 4 |
d564630156f2f9f9ecdd9f4ea4d5fdb260a62fe8 | 38,963,943,333,146 | 49e73b9353d7b2fac4cf715a05b9bab353ad708c | /src/java/com/huqiyun/dto/CBankuaiValueDTO.java | 6378b0d051ae77eea69f51c3724e87f1758eab35 | []
| no_license | h10086733/myspring | https://github.com/h10086733/myspring | cb2b227b88621ef7ea45da2902a75075fea5c695 | b904e8b487ae61160a266fa572a82d0b11aa3247 | refs/heads/master | 2021-01-12T00:57:04.927000 | 2017-08-15T08:50:22 | 2017-08-15T08:50:22 | 78,320,397 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.huqiyun.dto;
/**
* 板块每日收盘价格
* @author huqiyun
*
*/
public class CBankuaiValueDTO extends BaseDTO {
private String bankuaiJiancheng;//板块简称
private String bankuaiName;//板块名称
private String bankuaiDaima;//板块代码
private String bankuaiShoupanjia;//收盘价
private String cDate;//日期
public void setBankuaiJiancheng(String bankuaiJiancheng) {
this.bankuaiJiancheng = bankuaiJiancheng == null ? null : bankuaiJiancheng.trim();
}
public String getBankuaiJiancheng(){
return bankuaiJiancheng;
}
public void setBankuaiName(String bankuaiName) {
this.bankuaiName = bankuaiName == null ? null : bankuaiName.trim();
}
public String getBankuaiName(){
return bankuaiName;
}
public void setBankuaiDaima(String bankuaiDaima) {
this.bankuaiDaima = bankuaiDaima == null ? null : bankuaiDaima.trim();
}
public String getBankuaiDaima(){
return bankuaiDaima;
}
public void setBankuaiShoupanjia(String bankuaiShoupanjia) {
this.bankuaiShoupanjia = bankuaiShoupanjia == null ? null : bankuaiShoupanjia.trim();
}
public String getBankuaiShoupanjia(){
return bankuaiShoupanjia;
}
public void setCDate(String cDate) {
this.cDate = cDate == null ? null : cDate.trim();
}
public String getCDate(){
return cDate;
}
} | UTF-8 | Java | 1,462 | java | CBankuaiValueDTO.java | Java | [
{
"context": "age com.huqiyun.dto;\r\n/**\r\n * 板块每日收盘价格\r\n * @author huqiyun\r\n *\r\n */\r\npublic class CBankuaiValueDTO extends B",
"end": 62,
"score": 0.9992992877960205,
"start": 55,
"tag": "USERNAME",
"value": "huqiyun"
}
]
| null | []
| package com.huqiyun.dto;
/**
* 板块每日收盘价格
* @author huqiyun
*
*/
public class CBankuaiValueDTO extends BaseDTO {
private String bankuaiJiancheng;//板块简称
private String bankuaiName;//板块名称
private String bankuaiDaima;//板块代码
private String bankuaiShoupanjia;//收盘价
private String cDate;//日期
public void setBankuaiJiancheng(String bankuaiJiancheng) {
this.bankuaiJiancheng = bankuaiJiancheng == null ? null : bankuaiJiancheng.trim();
}
public String getBankuaiJiancheng(){
return bankuaiJiancheng;
}
public void setBankuaiName(String bankuaiName) {
this.bankuaiName = bankuaiName == null ? null : bankuaiName.trim();
}
public String getBankuaiName(){
return bankuaiName;
}
public void setBankuaiDaima(String bankuaiDaima) {
this.bankuaiDaima = bankuaiDaima == null ? null : bankuaiDaima.trim();
}
public String getBankuaiDaima(){
return bankuaiDaima;
}
public void setBankuaiShoupanjia(String bankuaiShoupanjia) {
this.bankuaiShoupanjia = bankuaiShoupanjia == null ? null : bankuaiShoupanjia.trim();
}
public String getBankuaiShoupanjia(){
return bankuaiShoupanjia;
}
public void setCDate(String cDate) {
this.cDate = cDate == null ? null : cDate.trim();
}
public String getCDate(){
return cDate;
}
} | 1,462 | 0.660057 | 0.660057 | 46 | 28.73913 | 24.785545 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.717391 | false | false | 4 |
9b9a98490f37ab2e4b07d276b31e3aab98f91330 | 34,385,508,214,050 | 233a54036c41a3b8dfde548fc0af78a1354132e0 | /Chapter07/application/src/test/java/dev/davivieira/topologyinventory/application/SwitchAdd.java | 286da08c58d139f37633e0fa66e7f457247b7bd4 | [
"MIT"
]
| permissive | PacktPublishing/Designing-Hexagonal-Architecture-with-Java-and-Quarkus | https://github.com/PacktPublishing/Designing-Hexagonal-Architecture-with-Java-and-Quarkus | 806ab87d2df1df7422bd8cb913c266e484ac495d | 8d702aea0db322fb2305fc5ae17043619abd868a | refs/heads/main | 2023-08-27T07:59:50.376000 | 2023-01-18T09:01:17 | 2023-01-18T09:01:17 | 353,330,520 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dev.davivieira.topologyinventory.application;
import dev.davivieira.topologyinventory.domain.entity.Switch;
import dev.davivieira.topologyinventory.domain.vo.*;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class SwitchAdd extends ApplicationTestData {
public SwitchAdd(){
loadData();
}
@Given("I provide a switch")
public void i_provide_a_switch(){
networkSwitch = Switch.builder().
id(Id.withId("f8c3de3d-1fea-4d7c-a8b0-29f63c4c3490")).
vendor(Vendor.CISCO).
model(Model.XYZ0004).
ip(IP.fromAddress("20.0.0.100")).
location(locationA).
switchType(SwitchType.LAYER3).
build();
assertNotNull(networkSwitch);
}
@Then("I add the switch to the edge router")
public void i_add_the_switch_to_the_edge_router(){
assertNotNull(edgeRouter);
edgeRouter = this.switchManagementUseCase.
addSwitchToEdgeRouter(networkSwitch, edgeRouter);
var actualId = networkSwitch.getId();
var expectedId = edgeRouter.
getSwitches().
get(Id.withId("f8c3de3d-1fea-4d7c-a8b0-29f63c4c3490")).
getId();
assertEquals(expectedId, actualId);
}
}
| UTF-8 | Java | 1,418 | java | SwitchAdd.java | Java | [
{
"context": "odel.XYZ0004).\n ip(IP.fromAddress(\"20.0.0.100\")).\n location(locationA).\n ",
"end": 740,
"score": 0.9995063543319702,
"start": 730,
"tag": "IP_ADDRESS",
"value": "20.0.0.100"
}
]
| null | []
| package dev.davivieira.topologyinventory.application;
import dev.davivieira.topologyinventory.domain.entity.Switch;
import dev.davivieira.topologyinventory.domain.vo.*;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class SwitchAdd extends ApplicationTestData {
public SwitchAdd(){
loadData();
}
@Given("I provide a switch")
public void i_provide_a_switch(){
networkSwitch = Switch.builder().
id(Id.withId("f8c3de3d-1fea-4d7c-a8b0-29f63c4c3490")).
vendor(Vendor.CISCO).
model(Model.XYZ0004).
ip(IP.fromAddress("172.16.31.10")).
location(locationA).
switchType(SwitchType.LAYER3).
build();
assertNotNull(networkSwitch);
}
@Then("I add the switch to the edge router")
public void i_add_the_switch_to_the_edge_router(){
assertNotNull(edgeRouter);
edgeRouter = this.switchManagementUseCase.
addSwitchToEdgeRouter(networkSwitch, edgeRouter);
var actualId = networkSwitch.getId();
var expectedId = edgeRouter.
getSwitches().
get(Id.withId("f8c3de3d-1fea-4d7c-a8b0-29f63c4c3490")).
getId();
assertEquals(expectedId, actualId);
}
}
| 1,420 | 0.636812 | 0.604372 | 42 | 32.761906 | 20.791264 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.404762 | false | false | 4 |
3257a6718cc3d63764823e7dd36110eadf6e28c7 | 38,852,274,191,151 | 7c56c60ac2c5f86ee9222ac373b2bd4276f6c48e | /data-structures/src/main/java/io/github/dmba/ch1/tasks/q17rotatematrix/package-info.java | 9195122a9cc62264538bc3ace9d496ae891d558f | [
"MIT"
]
| permissive | dmba/ctci-solutions | https://github.com/dmba/ctci-solutions | d978cf404dabe64c18fc18aa354007b9a40a6c37 | 2856d1dc18269968f8ac31b7f765f6072c66c2c3 | refs/heads/master | 2021-01-24T02:58:27.256000 | 2018-02-28T20:48:26 | 2018-02-28T20:48:26 | 122,870,144 | 0 | 0 | MIT | false | 2018-06-08T12:00:51 | 2018-02-25T19:47:39 | 2018-02-25T23:50:49 | 2018-03-05T23:25:59 | 47 | 1 | 0 | 1 | Java | false | null | /**
* 1.7 Rotate Matrix
* <p/>
* Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes,
* write a method to rotate the image by 90 degrees.
* Can you do this in place?
* <p/>
* Hints:
* <ul>
* <li>#51 : Try thinking about it layer by layer. Can you rotate a specific layer?</li>
* <li>#100: Rotating a specific layer would just mean swapping the values in four arrays.
* If you were asked to swap the values in two arrays, could you do this?
* Can you then extend it to four arrays?</li>
* </ul>
*/
package io.github.dmba.ch1.tasks.q17rotatematrix;
| UTF-8 | Java | 615 | java | package-info.java | Java | []
| null | []
| /**
* 1.7 Rotate Matrix
* <p/>
* Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes,
* write a method to rotate the image by 90 degrees.
* Can you do this in place?
* <p/>
* Hints:
* <ul>
* <li>#51 : Try thinking about it layer by layer. Can you rotate a specific layer?</li>
* <li>#100: Rotating a specific layer would just mean swapping the values in four arrays.
* If you were asked to swap the values in two arrays, could you do this?
* Can you then extend it to four arrays?</li>
* </ul>
*/
package io.github.dmba.ch1.tasks.q17rotatematrix;
| 615 | 0.666667 | 0.645528 | 16 | 37.4375 | 33.507404 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 4 |
ed28fc1241ca876091f14a9a29204d7e8eeb2a10 | 22,643,067,649,797 | e8f9c05e995401fb4b02f712962b2904f07f1c9a | /app/src/main/java/com/example/guju/adapter/MyBaseAdapter.java | e745a099d662eb0073099730b598248a359b2ee2 | []
| no_license | SummerVine/Guju | https://github.com/SummerVine/Guju | adddd80d8ac9c2197cff35e7b48f637f5ef9050d | 7221c5dcfc52270f2153216405e3f81f5fe6b890 | refs/heads/master | 2021-01-19T04:28:29.326000 | 2016-07-12T13:25:49 | 2016-07-12T13:25:49 | 62,556,790 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.guju.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
public abstract class MyBaseAdapter<T> extends BaseAdapter{
private List<T> data;
private LayoutInflater inflater;
public MyBaseAdapter(List<T> data, Context context) {
this.data = data;
inflater = LayoutInflater.from(context);
}
public LayoutInflater getInflater() {
return inflater;
}
public void addAll(List<T> list){
data.addAll(list);
notifyDataSetChanged();
}
public void removeAll(){
data.clear();
notifyDataSetChanged();
}
public void deleteItem(int position){
data.remove(position);
notifyDataSetChanged();
}
@Override
public int getCount() {
return data.size();
}
@Override
public T getItem(int i) {
return data.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return getViewItem(i,view,viewGroup);
}
public abstract View getViewItem(int i, View view, ViewGroup viewGroup);
}
| UTF-8 | Java | 1,303 | java | MyBaseAdapter.java | Java | []
| null | []
| package com.example.guju.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import java.util.List;
public abstract class MyBaseAdapter<T> extends BaseAdapter{
private List<T> data;
private LayoutInflater inflater;
public MyBaseAdapter(List<T> data, Context context) {
this.data = data;
inflater = LayoutInflater.from(context);
}
public LayoutInflater getInflater() {
return inflater;
}
public void addAll(List<T> list){
data.addAll(list);
notifyDataSetChanged();
}
public void removeAll(){
data.clear();
notifyDataSetChanged();
}
public void deleteItem(int position){
data.remove(position);
notifyDataSetChanged();
}
@Override
public int getCount() {
return data.size();
}
@Override
public T getItem(int i) {
return data.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return getViewItem(i,view,viewGroup);
}
public abstract View getViewItem(int i, View view, ViewGroup viewGroup);
}
| 1,303 | 0.650038 | 0.650038 | 57 | 21.85965 | 18.303905 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 4 |
f45059197d9cba4cee61b4c17deea2575d3771e2 | 38,096,359,928,497 | d1142059039876c710cb87b9dc7ac1e928791303 | /src/main/java/com/example/dto/input/LoginFormDTO.java | 843da4f3c60d4e1754dd66fea4944b099fd6def1 | [
"MIT"
]
| permissive | kajkal/spring-boot-security-with-jwt-demo | https://github.com/kajkal/spring-boot-security-with-jwt-demo | a93fa002a44bf0e2708ede7e8a421a6ab62e812d | b2114a65f62a6cd71257c682ac1b118396bad82c | refs/heads/master | 2020-04-09T03:00:09.721000 | 2018-12-01T16:42:13 | 2018-12-01T16:42:13 | 159,964,498 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.dto.input;
public class LoginFormDTO {
private String username;
private String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "LoginFormDTO{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
} | UTF-8 | Java | 461 | java | LoginFormDTO.java | Java | [
{
"context": "\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n ",
"end": 179,
"score": 0.9951909780502319,
"start": 171,
"tag": "USERNAME",
"value": "username"
},
{
"context": "n \"LoginFormDTO{\" +\n \"username='\" + username + '\\'' +\n \", password='\" + passwor",
"end": 371,
"score": 0.9930055737495422,
"start": 363,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n\n}",
"end": 422,
"score": 0.9940288066864014,
"start": 414,
"tag": "PASSWORD",
"value": "password"
}
]
| null | []
| package com.example.dto.input;
public class LoginFormDTO {
private String username;
private String password;
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "LoginFormDTO{" +
"username='" + username + '\'' +
", password='" + <PASSWORD> + '\'' +
'}';
}
} | 463 | 0.524946 | 0.524946 | 26 | 16.76923 | 15.918803 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.269231 | false | false | 4 |
ede9a074bb4c2a8581879f44ad44abe943d87625 | 37,907,381,368,086 | 374fb86b0e2c422c6782b528414fb2ee332f7821 | /rest/src/test/java/org/usergrid/rest/test/util/RestRunner.java | 0f80ed0e4e668d1a5b1c2b6ca93447515b6d5e97 | [
"Apache-2.0"
]
| permissive | cazcade/cgrid | https://github.com/cazcade/cgrid | 91e1ba2970f8dff322cdd8723b3700910383e704 | 572100b176eaf19ca6ac8570825f15ceb1863638 | refs/heads/master | 2017-04-30T02:47:14.188000 | 2013-10-16T00:42:02 | 2013-10-16T00:42:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright 2012 Apigee Corporation
*
* 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.usergrid.rest.test.util;
import com.sun.jersey.test.framework.JerseyTest;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.usergrid.cassandra.CassandraRunner;
import org.usergrid.rest.test.resource.TestContext;
import org.usergrid.rest.test.security.TestAdminUser;
import java.lang.reflect.Field;
/**
* Helper that creates a test application and test context as well as running
* cassandra runners
*
* @author tnine
*
*/
public class RestRunner extends CassandraRunner {
private Field cachedField;
/**
* @param klass
* @throws InitializationError
*/
public RestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
private void setupTest(Class<?> testClass, String methodName, JerseyTest test) {
Field target = findField(testClass);
if (target == null) {
throw new RuntimeException(String.format("You did not specify a %s field with the %s annotation",
TestContext.class.getName(), Context.class));
}
String name = testClass.getName() + "." + methodName;
TestAdminUser testAdmin = new TestAdminUser(name, name + "@usergrid.com", name + "@usergrid.com");
// create the text context
TestContext context = TestContext.create(test).withOrg(name).withApp(methodName).withUser(testAdmin).initAll();
try {
boolean accessible = target.isAccessible();
target.setAccessible(true);
target.set(test, context);
target.setAccessible(accessible);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Find the field
*
* @param testClass
* @return
*/
private Field findField(final Class<?> testClass) {
if (cachedField != null) {
return cachedField;
}
Class<?> current = testClass;
do {
for (Field field : current.getDeclaredFields()) {
if (field.getAnnotation(Context.class) != null) {
cachedField = field;
return cachedField;
}
}
current = current.getSuperclass();
} while (current != null);
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.junit.runners.BlockJUnit4ClassRunner#methodInvoker(org.junit.runners
* .model.FrameworkMethod, java.lang.Object)
*/
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
System.out.println("There is an errant System.exit() going on and I've given up trying to get the tests working for now - neilellis");
if(true) return null;
if (!(test instanceof JerseyTest)) {
throw new RuntimeException(String.format("This runner can only be used with subclasses of %s", JerseyTest.class));
}
setupTest(test.getClass(), method.getName(), (JerseyTest) test);
return super.methodInvoker(method, test);
}
}
| UTF-8 | Java | 3,667 | java | RestRunner.java | Java | [
{
"context": "ell as running\n * cassandra runners\n * \n * @author tnine\n * \n */\npublic class RestRunner extends Cassandra",
"end": 1297,
"score": 0.9989984631538391,
"start": 1292,
"tag": "USERNAME",
"value": "tnine"
}
]
| null | []
| /*******************************************************************************
* Copyright 2012 Apigee Corporation
*
* 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.usergrid.rest.test.util;
import com.sun.jersey.test.framework.JerseyTest;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
import org.usergrid.cassandra.CassandraRunner;
import org.usergrid.rest.test.resource.TestContext;
import org.usergrid.rest.test.security.TestAdminUser;
import java.lang.reflect.Field;
/**
* Helper that creates a test application and test context as well as running
* cassandra runners
*
* @author tnine
*
*/
public class RestRunner extends CassandraRunner {
private Field cachedField;
/**
* @param klass
* @throws InitializationError
*/
public RestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
private void setupTest(Class<?> testClass, String methodName, JerseyTest test) {
Field target = findField(testClass);
if (target == null) {
throw new RuntimeException(String.format("You did not specify a %s field with the %s annotation",
TestContext.class.getName(), Context.class));
}
String name = testClass.getName() + "." + methodName;
TestAdminUser testAdmin = new TestAdminUser(name, name + "@usergrid.com", name + "@usergrid.com");
// create the text context
TestContext context = TestContext.create(test).withOrg(name).withApp(methodName).withUser(testAdmin).initAll();
try {
boolean accessible = target.isAccessible();
target.setAccessible(true);
target.set(test, context);
target.setAccessible(accessible);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Find the field
*
* @param testClass
* @return
*/
private Field findField(final Class<?> testClass) {
if (cachedField != null) {
return cachedField;
}
Class<?> current = testClass;
do {
for (Field field : current.getDeclaredFields()) {
if (field.getAnnotation(Context.class) != null) {
cachedField = field;
return cachedField;
}
}
current = current.getSuperclass();
} while (current != null);
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.junit.runners.BlockJUnit4ClassRunner#methodInvoker(org.junit.runners
* .model.FrameworkMethod, java.lang.Object)
*/
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
System.out.println("There is an errant System.exit() going on and I've given up trying to get the tests working for now - neilellis");
if(true) return null;
if (!(test instanceof JerseyTest)) {
throw new RuntimeException(String.format("This runner can only be used with subclasses of %s", JerseyTest.class));
}
setupTest(test.getClass(), method.getName(), (JerseyTest) test);
return super.methodInvoker(method, test);
}
}
| 3,667 | 0.659667 | 0.657213 | 127 | 27.874016 | 30.333576 | 140 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.401575 | false | false | 4 |
2848dcc92b5a7bffb883a682a41d26609495d48b | 60,129,591,500 | 376417d0ee190516549e75e5740416d492186bd3 | /src/java/com/tcc/bean/StatusMb.java | bc41b24694ceb09b6f4e33c2eb50d08c40e3b280 | []
| no_license | PauloCastro91/tcc | https://github.com/PauloCastro91/tcc | d5f38135b5c8762882c416eb6d6f9ff6017ea544 | 3fbfd28487ef00dcf81f2fbc47a9af084179ffc6 | refs/heads/master | 2020-04-01T08:31:43.076000 | 2013-12-03T11:38:26 | 2013-12-03T11:38:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tcc.bean;
/**
*
* @author paulo.castro
*/
import com.tcc.bo.StatusBo;
import com.tcc.model.SttStatus;
import com.tcc.util.JPAUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* @author paulo.castro
*/
@ManagedBean
@ViewScoped
public class StatusMb extends BaseMb implements Serializable {
private SttStatus stt = new SttStatus();
private ModoTela modo = new ModoTela();
private StatusBo statusBo = new StatusBo();
private List<SttStatus> sttList = new ArrayList<SttStatus>();
private String descricao;
public StatusMb() {
}
public void cancelar() {
limpar();
}
public void limpar() {
stt = new SttStatus();
descricao = "";
recarregarLista();
modo.setModoTela(ModoTela.VISUALIZACAO);
}
public void novo() {
stt = new SttStatus();
descricao = "";
modo.setModoTela(ModoTela.INSERCAO);
}
public void alterar() {
modo.setModoTela(ModoTela.ALTERACAO);
}
public void validarDuplicidade() throws Exception {
List<SttStatus> mesmaDescricao = statusBo.carrgar(descricao);
if (mesmaDescricao != null && !mesmaDescricao.isEmpty()) {
if (stt != null && stt.getSttId() != null) {
boolean jaUsuada = false;
for (SttStatus c : mesmaDescricao) {
if ((!c.getSttId().equals(stt.getSttId())) && (stt.getSttDescricao().trim().equalsIgnoreCase(stt.getSttDescricao().trim()))) {
jaUsuada = true;
break;
}
}
if (jaUsuada) {
throw new Exception("Descrição já usada para outro status");
}
} else {
throw new Exception("Descrição já usada para outro status");
}
}
}
public void salvar() {
try {
if ((descricao != null) && (!descricao.trim().isEmpty()) && (descricao.trim().length() >= 3)) {
stt.setSttDescricao(descricao);
validarDuplicidade();
if (stt.getSttId() != null) {
statusBo.alterar(stt);
} else {
statusBo.inserir(stt);
}
limpar();
} else {
throw new Exception("Insira Pelo menos 3 letras na descrição do Status!");
}
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
@PostConstruct
public void recarregarLista() {
try {
sttList = new ArrayList<SttStatus>();
sttList = statusBo.listarTodos();
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
public void pesquisarStatus() {
try {
sttList = new ArrayList<SttStatus>();
if ((descricao != null) && (!descricao.trim().isEmpty()) && (descricao.trim().length() >= 2)) {
sttList = new ArrayList<SttStatus>();
sttList = statusBo.carrgar(descricao);
} else {
throw new Exception("Insira Pelo menos 2 letras para busca!");
}
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
public void inativar() {
statusBo.inativar(stt);
stt = new SttStatus();
modo = new ModoTela();
}
public void ativar() {
statusBo.ativar(stt);
stt = new SttStatus();
modo = new ModoTela();
}
/**
* Getters and Setters
*/
public SttStatus getStt() {
return stt;
}
public void setStt(SttStatus stt) {
this.stt = stt;
}
public ModoTela getModo() {
return modo;
}
public void setModo(ModoTela modo) {
this.modo = modo;
}
public StatusBo getStatusBo() {
return statusBo;
}
public void setStatusBo(StatusBo statusBo) {
this.statusBo = statusBo;
}
public List<SttStatus> getSttList() {
return sttList;
}
public void setSttList(List<SttStatus> sttList) {
this.sttList = sttList;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
| UTF-8 | Java | 4,821 | java | StatusMb.java | Java | [
{
"context": "\n */\r\npackage com.tcc.bean;\r\n\r\n/**\r\n *\r\n * @author paulo.castro\r\n */\r\nimport com.tcc.bo.StatusBo;\r\nimp",
"end": 150,
"score": 0.793809711933136,
"start": 149,
"tag": "NAME",
"value": "p"
},
{
"context": "*/\r\npackage com.tcc.bean;\r\n\r\n/**\r\n *\r\n * @author paulo.castro\r\n */\r\nimport com.tcc.bo.StatusBo;\r\nimport com.tcc",
"end": 161,
"score": 0.7814421653747559,
"start": 150,
"tag": "USERNAME",
"value": "aulo.castro"
},
{
"context": "avax.faces.bean.ViewScoped;\r\n\r\n/**\r\n *\r\n * @author paulo.castro\r\n */\r\n@ManagedBean\r\n@ViewScoped\r\npubli",
"end": 481,
"score": 0.8035995364189148,
"start": 480,
"tag": "NAME",
"value": "p"
},
{
"context": "ax.faces.bean.ViewScoped;\r\n\r\n/**\r\n *\r\n * @author paulo.castro\r\n */\r\n@ManagedBean\r\n@ViewScoped\r\npublic class S",
"end": 490,
"score": 0.8230504989624023,
"start": 481,
"tag": "USERNAME",
"value": "aulo.cast"
},
{
"context": "bean.ViewScoped;\r\n\r\n/**\r\n *\r\n * @author paulo.castro\r\n */\r\n@ManagedBean\r\n@ViewScoped\r\npublic class Sta",
"end": 492,
"score": 0.5296755433082581,
"start": 490,
"tag": "NAME",
"value": "ro"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.tcc.bean;
/**
*
* @author paulo.castro
*/
import com.tcc.bo.StatusBo;
import com.tcc.model.SttStatus;
import com.tcc.util.JPAUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
/**
*
* @author paulo.castro
*/
@ManagedBean
@ViewScoped
public class StatusMb extends BaseMb implements Serializable {
private SttStatus stt = new SttStatus();
private ModoTela modo = new ModoTela();
private StatusBo statusBo = new StatusBo();
private List<SttStatus> sttList = new ArrayList<SttStatus>();
private String descricao;
public StatusMb() {
}
public void cancelar() {
limpar();
}
public void limpar() {
stt = new SttStatus();
descricao = "";
recarregarLista();
modo.setModoTela(ModoTela.VISUALIZACAO);
}
public void novo() {
stt = new SttStatus();
descricao = "";
modo.setModoTela(ModoTela.INSERCAO);
}
public void alterar() {
modo.setModoTela(ModoTela.ALTERACAO);
}
public void validarDuplicidade() throws Exception {
List<SttStatus> mesmaDescricao = statusBo.carrgar(descricao);
if (mesmaDescricao != null && !mesmaDescricao.isEmpty()) {
if (stt != null && stt.getSttId() != null) {
boolean jaUsuada = false;
for (SttStatus c : mesmaDescricao) {
if ((!c.getSttId().equals(stt.getSttId())) && (stt.getSttDescricao().trim().equalsIgnoreCase(stt.getSttDescricao().trim()))) {
jaUsuada = true;
break;
}
}
if (jaUsuada) {
throw new Exception("Descrição já usada para outro status");
}
} else {
throw new Exception("Descrição já usada para outro status");
}
}
}
public void salvar() {
try {
if ((descricao != null) && (!descricao.trim().isEmpty()) && (descricao.trim().length() >= 3)) {
stt.setSttDescricao(descricao);
validarDuplicidade();
if (stt.getSttId() != null) {
statusBo.alterar(stt);
} else {
statusBo.inserir(stt);
}
limpar();
} else {
throw new Exception("Insira Pelo menos 3 letras na descrição do Status!");
}
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
@PostConstruct
public void recarregarLista() {
try {
sttList = new ArrayList<SttStatus>();
sttList = statusBo.listarTodos();
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
public void pesquisarStatus() {
try {
sttList = new ArrayList<SttStatus>();
if ((descricao != null) && (!descricao.trim().isEmpty()) && (descricao.trim().length() >= 2)) {
sttList = new ArrayList<SttStatus>();
sttList = statusBo.carrgar(descricao);
} else {
throw new Exception("Insira Pelo menos 2 letras para busca!");
}
} catch (Exception e) {
JPAUtil.addMensagemErro(e.getMessage());
}
}
public void inativar() {
statusBo.inativar(stt);
stt = new SttStatus();
modo = new ModoTela();
}
public void ativar() {
statusBo.ativar(stt);
stt = new SttStatus();
modo = new ModoTela();
}
/**
* Getters and Setters
*/
public SttStatus getStt() {
return stt;
}
public void setStt(SttStatus stt) {
this.stt = stt;
}
public ModoTela getModo() {
return modo;
}
public void setModo(ModoTela modo) {
this.modo = modo;
}
public StatusBo getStatusBo() {
return statusBo;
}
public void setStatusBo(StatusBo statusBo) {
this.statusBo = statusBo;
}
public List<SttStatus> getSttList() {
return sttList;
}
public void setSttList(List<SttStatus> sttList) {
this.sttList = sttList;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
| 4,821 | 0.528568 | 0.527737 | 176 | 25.34659 | 23.376106 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.357955 | false | false | 4 |
ffb8c99a32ccddd324f4311705924650a62a4098 | 38,981,123,210,247 | 29c5f232dfc8977f599e182dff53a6641b870d56 | /trabModuloVendas/src/Conexao/PedidosDao.java | 13261d2fbc99b15c1689cb5ce9a8555c30f0ff44 | []
| no_license | trabRamonEduardo/ModuloVendas | https://github.com/trabRamonEduardo/ModuloVendas | 935065d4554048248f2af5b9031bfcb18e65d5ee | 7172364968c24181dacd6db328558497f22a0772 | refs/heads/master | 2015-08-11T07:19:50.770000 | 2014-06-12T22:48:59 | 2014-06-12T22:48:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Conexao;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import pedido.Pedido;
/**
*
* @author Ramon
*/
public class PedidosDao extends Dao {
public PedidosDao() {
super();
System.out.println("Conexão Aberta! (Classe PedidosDao)");
}
public int adiciona(Pedido pedido) throws SQLException {
String sql = "insert into erp.pedidos (dataCriacao, observacao, "
+ "transportadora_idtransportadora, formaPagamento_idformaPagamento, "
+ "pessoa_idpessoa) values (?,?,?,?,?)";
try (PreparedStatement stmt = super.connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
stmt.setDate(1, new Date(pedido.getDataCriacao().getTime()));
stmt.setString(2, pedido.getObservacao());
stmt.setInt(3, pedido.getIdTransportadora());
stmt.setInt(4, pedido.getIdFormaPagamento());
stmt.setInt(5, pedido.getIdPessoa());
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
int id = 0;
if (rs.first())
id = rs.getInt(1);
rs.close();
return id;
} catch (SQLException e) {
throw new RuntimeException("Problema na criação do Statement (Classe PedidosDao, Método adiciona)", e);
}
}
}
| UTF-8 | Java | 1,466 | java | PedidosDao.java | Java | [
{
"context": "ion;\r\nimport pedido.Pedido;\r\n\r\n/**\r\n *\r\n * @author Ramon\r\n */\r\npublic class PedidosDao extends Dao {\r\n\r\n ",
"end": 188,
"score": 0.8373966217041016,
"start": 183,
"tag": "NAME",
"value": "Ramon"
}
]
| null | []
| package Conexao;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import pedido.Pedido;
/**
*
* @author Ramon
*/
public class PedidosDao extends Dao {
public PedidosDao() {
super();
System.out.println("Conexão Aberta! (Classe PedidosDao)");
}
public int adiciona(Pedido pedido) throws SQLException {
String sql = "insert into erp.pedidos (dataCriacao, observacao, "
+ "transportadora_idtransportadora, formaPagamento_idformaPagamento, "
+ "pessoa_idpessoa) values (?,?,?,?,?)";
try (PreparedStatement stmt = super.connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
stmt.setDate(1, new Date(pedido.getDataCriacao().getTime()));
stmt.setString(2, pedido.getObservacao());
stmt.setInt(3, pedido.getIdTransportadora());
stmt.setInt(4, pedido.getIdFormaPagamento());
stmt.setInt(5, pedido.getIdPessoa());
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
int id = 0;
if (rs.first())
id = rs.getInt(1);
rs.close();
return id;
} catch (SQLException e) {
throw new RuntimeException("Problema na criação do Statement (Classe PedidosDao, Método adiciona)", e);
}
}
}
| 1,466 | 0.593707 | 0.588919 | 43 | 32 | 30.092106 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.860465 | false | false | 4 |
6cf119ed2434330b22992d6b4088476a4e6c06b5 | 37,984,690,784,015 | 5f239182924e4d2654d22ac3cb96d880ffb01a4c | /src/main/java/com/borislam/view/ProductDetailBean.java | 8561e51dfc7266da816e39d775b4d7cb7feb4c56 | []
| no_license | jlombardo/spring-data-mongodb-jsf | https://github.com/jlombardo/spring-data-mongodb-jsf | 2b23a50dc7f70568b00cee99d7b8842466cb1bc6 | 7fe6f3133e80a7ad737ed09d9800f73737a91331 | refs/heads/master | 2021-01-15T22:38:51.075000 | 2013-02-11T03:06:02 | 2013-02-11T03:06:02 | 8,181,120 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.borislam.view;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.dao.DataAccessException;
import com.borislam.domain.Detail;
import com.borislam.domain.Pricing;
import com.borislam.domain.Product;
import com.borislam.service.ProductService;
@Component
@Scope("session")
public class ProductDetailBean {
@Autowired
private ProductService productService;
private boolean newProduct;
private Product product;
private String newTrack;
private String newChapter;
public boolean isNewProduct() {
return newProduct;
}
public void setNewProduct(boolean newProduct) {
this.newProduct = newProduct;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getNewTrack() {
return newTrack;
}
public void setNewTrack(String newTrack) {
this.newTrack = newTrack;
}
public String getNewChapter() {
return newChapter;
}
public void setNewChapter(String newChapter) {
this.newChapter = newChapter;
}
public void initProduct(){
Object selectedProduct = (FacesContext.getCurrentInstance().getExternalContext().getFlash()).get("selected");
if (selectedProduct==null && !FacesContext.getCurrentInstance().isPostback()) {
product = new Product();
product.setDetails(new Detail());
product.setPricing(new Pricing(0,0));
setNewProduct(true);
}
if (selectedProduct!=null) {
product = (Product)selectedProduct;
setNewProduct(false);
}
}
public void doSave(ActionEvent event) {
try {
productService.saveProduct(product);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Save Successfully!"));
}
catch (DataAccessException e)
{
e.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error when saving product!",null));
}
}
public void doAddTracks(ActionEvent event) {
List<String> tracks = product.getDetails().getTracks();
if (CollectionUtils.isEmpty(tracks)) {
product.getDetails().setTracks(new ArrayList<String>());
}
product.getDetails().getTracks().add(this.newTrack);
}
public void doAddChapters(ActionEvent event) {
List<String> tracks = product.getDetails().getChapters();
if (CollectionUtils.isEmpty(tracks)) {
product.getDetails().setChapters(new ArrayList<String>() );
}
product.getDetails().getChapters().add(this.newChapter);
}
public void clearDetails(ValueChangeEvent event) {
if ("Audio Album".equalsIgnoreCase(event.getNewValue().toString()) ) {
product.getDetails().setChapters(null);
}
if ("Book".equalsIgnoreCase( event.getNewValue().toString())) {
product.getDetails().setTracks(null);
}
}
}
| UTF-8 | Java | 3,250 | java | ProductDetailBean.java | Java | []
| null | []
| package com.borislam.view;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.dao.DataAccessException;
import com.borislam.domain.Detail;
import com.borislam.domain.Pricing;
import com.borislam.domain.Product;
import com.borislam.service.ProductService;
@Component
@Scope("session")
public class ProductDetailBean {
@Autowired
private ProductService productService;
private boolean newProduct;
private Product product;
private String newTrack;
private String newChapter;
public boolean isNewProduct() {
return newProduct;
}
public void setNewProduct(boolean newProduct) {
this.newProduct = newProduct;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getNewTrack() {
return newTrack;
}
public void setNewTrack(String newTrack) {
this.newTrack = newTrack;
}
public String getNewChapter() {
return newChapter;
}
public void setNewChapter(String newChapter) {
this.newChapter = newChapter;
}
public void initProduct(){
Object selectedProduct = (FacesContext.getCurrentInstance().getExternalContext().getFlash()).get("selected");
if (selectedProduct==null && !FacesContext.getCurrentInstance().isPostback()) {
product = new Product();
product.setDetails(new Detail());
product.setPricing(new Pricing(0,0));
setNewProduct(true);
}
if (selectedProduct!=null) {
product = (Product)selectedProduct;
setNewProduct(false);
}
}
public void doSave(ActionEvent event) {
try {
productService.saveProduct(product);
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Save Successfully!"));
}
catch (DataAccessException e)
{
e.printStackTrace();
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error when saving product!",null));
}
}
public void doAddTracks(ActionEvent event) {
List<String> tracks = product.getDetails().getTracks();
if (CollectionUtils.isEmpty(tracks)) {
product.getDetails().setTracks(new ArrayList<String>());
}
product.getDetails().getTracks().add(this.newTrack);
}
public void doAddChapters(ActionEvent event) {
List<String> tracks = product.getDetails().getChapters();
if (CollectionUtils.isEmpty(tracks)) {
product.getDetails().setChapters(new ArrayList<String>() );
}
product.getDetails().getChapters().add(this.newChapter);
}
public void clearDetails(ValueChangeEvent event) {
if ("Audio Album".equalsIgnoreCase(event.getNewValue().toString()) ) {
product.getDetails().setChapters(null);
}
if ("Book".equalsIgnoreCase( event.getNewValue().toString())) {
product.getDetails().setTracks(null);
}
}
}
| 3,250 | 0.741538 | 0.740923 | 130 | 24 | 24.334528 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.661538 | false | false | 4 |
b8b7ee31cb8989e5ddde557a3cd281462d7cebc3 | 34,050,500,775,062 | d1ecf9cd0fc524d5ac4691bb1b9cbe99ebc4ec53 | /src/main/java/com/sellerNet/backManagement/service/BreaksOrderService.java | 05ee1c7a452f336b58945b6e5b8a653e98127993 | []
| no_license | oskampung/im- | https://github.com/oskampung/im- | 1f30410f78e7259169fe722cb1b677fe89d48ef2 | a751760b79231acbc591cd0da76389633e6883c0 | refs/heads/master | 2021-09-16T10:11:07.161000 | 2018-06-19T11:04:35 | 2018-06-19T11:04:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sellerNet.backManagement.service;
import com.sellerNet.backManagement.entity.BreaksOrder;
public abstract interface BreaksOrderService extends baseService<BreaksOrder, Integer>{
} | UTF-8 | Java | 200 | java | BreaksOrderService.java | Java | []
| null | []
| package com.sellerNet.backManagement.service;
import com.sellerNet.backManagement.entity.BreaksOrder;
public abstract interface BreaksOrderService extends baseService<BreaksOrder, Integer>{
} | 200 | 0.83 | 0.83 | 7 | 26.857143 | 32.886944 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 4 |
9bfa6ceab267531a71d4804dc23760d2d77cbf69 | 34,059,090,708,071 | f97eb3915b95dd8120c3f165d411de4a493deafa | /src/main/java/com/timboudreau/niothing/SplitFile.java | ad872e844fea8af3b1fceea771cb788064d94d07 | [
"MIT"
]
| permissive | timboudreau/niothing | https://github.com/timboudreau/niothing | 05f3555812da4c0cdd5d839e6a2fedca2d2c1d21 | 5041c89d25de26f22a64d2306680743d98c02209 | refs/heads/master | 2021-04-12T05:06:46.412000 | 2015-05-09T07:31:14 | 2015-05-09T07:31:14 | 35,319,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* The MIT License
*
* Copyright 2015 Tim Boudreau.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.timboudreau.niothing;
import com.mastfrog.util.Exceptions;
import com.mastfrog.util.Streams;
import com.mastfrog.util.collections.CollectionUtils;
import com.mastfrog.util.collections.Converter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Thread-safe Iterable which produces an iterator of InputStreams of regions of
* a single file, which can be accessed concurrently. Memory-maps the total
* region requested, and returns InputStreams over sub-ByteBuffers representing
* each region.
*
* @author Tim Boudreau
*/
public final class SplitFile implements Iterable<RegionInputStream>, AutoCloseable {
private final List<Region> regions;
private final File file;
private FileChannel channel;
private MappedByteBuffer allRegions;
public SplitFile(File file, Collection<Region> regions) {
this.file = file;
this.regions = new ArrayList<>(regions);
Collections.sort(this.regions);
// Trigger ISE early if total region to map is > Integer.MAX_VALUE
// This can be avoided if we want to map individual regions instead of
// the entire file - but the OS's memory manager will generally take
// care of not actually slurping the whole file into memory instantly
range();
}
private Region first() {
return regions.get(0);
}
private Region last() {
return regions.get(regions.size() - 1);
}
private Region range() {
// This will throw an exception if the total range to map is > Integer.MAX_VALUE
// This could be avoided by mapping individual regions if needed, but likely
// not to perform as well
return new Region(first().start, last().end);
}
synchronized MappedByteBuffer masterBuffer() throws IOException {
if (channel == null) {
channel = new FileInputStream(file).getChannel();
Region range = range();
allRegions = channel.map(FileChannel.MapMode.READ_ONLY, range.start, range.length());
}
return allRegions;
}
@Override
public Iterator<RegionInputStream> iterator() {
if (regions.isEmpty()) {
return Collections.emptyIterator();
}
synchronized (this) {
if (channel != null) {
// Two iterators could result in the channel being closed while still in
// use by another iterator
throw new IllegalStateException("Cannot reuse this object until all streams "
+ "from the previously returned iterator are closed.");
}
}
return new SynchronizedIterator<>(CollectionUtils.convertedIterator(new RegionToInputStream(), regions.iterator()));
}
@Override
public void close() throws Exception {
FileChannel openFileChannel;
synchronized (this) {
openFileChannel = channel;
channel = null;
allRegions = null;
}
if (openFileChannel != null) {
openFileChannel.close();
}
}
private ByteBuffer bufferFor(Region region) throws IOException {
ByteBuffer master = masterBuffer();
master.position((int) region.start);
ByteBuffer result = master.slice();
result.limit(region.length());
return result;
}
@Override
public String toString() {
return "SplitFile{" + file + ", " + regions + "}";
}
private final class RegionToInputStream implements Converter<RegionInputStream, Region> {
private final AtomicInteger counter = new AtomicInteger(regions.size());
@Override
public RegionInputStream convert(Region region) {
try {
ByteBuffer buf = bufferFor(region);
return new CloseCountingInputStream(region, Streams.asInputStream(buf), counter);
} catch (IOException ex) {
return Exceptions.chuck(ex);
}
}
@Override
public Region unconvert(RegionInputStream t) {
throw new UnsupportedOperationException("Not needed.");
}
}
private void onLastStreamClosed() {
try {
close();
} catch (Exception ex) {
Exceptions.chuck(ex);
}
}
private final class CloseCountingInputStream extends RegionInputStream {
final AtomicInteger closeCounter;
private boolean closed;
public CloseCountingInputStream(Region region, InputStream streamToWrap, AtomicInteger closeCounter) {
super(region, streamToWrap);
this.closeCounter = closeCounter;
}
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
try {
super.close();
} finally {
if (0 == closeCounter.decrementAndGet()) {
onLastStreamClosed();
}
}
}
}
}
/**
* Multiple threads will be banging on this iterator at once, so it needs to
* be synchronized, though the underlying collection doesn't.
*
* @param <T> The type
*/
static class SynchronizedIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
public SynchronizedIterator(Iterator<T> iterator) {
this.iterator = iterator;
}
@Override
public synchronized boolean hasNext() {
return iterator.hasNext();
}
@Override
public synchronized T next() {
return iterator.next();
}
}
}
| UTF-8 | Java | 7,197 | java | SplitFile.java | Java | [
{
"context": "/*\n * The MIT License\n *\n * Copyright 2015 Tim Boudreau.\n *\n * Permission is hereby granted, free of char",
"end": 55,
"score": 0.9998776316642761,
"start": 43,
"tag": "NAME",
"value": "Tim Boudreau"
},
{
"context": "Buffers representing\n * each region.\n *\n * @author Tim Boudreau\n */\npublic final class SplitFile implements Itera",
"end": 2024,
"score": 0.9998859167098999,
"start": 2012,
"tag": "NAME",
"value": "Tim Boudreau"
}
]
| null | []
| /*
* The MIT License
*
* Copyright 2015 <NAME>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.timboudreau.niothing;
import com.mastfrog.util.Exceptions;
import com.mastfrog.util.Streams;
import com.mastfrog.util.collections.CollectionUtils;
import com.mastfrog.util.collections.Converter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Thread-safe Iterable which produces an iterator of InputStreams of regions of
* a single file, which can be accessed concurrently. Memory-maps the total
* region requested, and returns InputStreams over sub-ByteBuffers representing
* each region.
*
* @author <NAME>
*/
public final class SplitFile implements Iterable<RegionInputStream>, AutoCloseable {
private final List<Region> regions;
private final File file;
private FileChannel channel;
private MappedByteBuffer allRegions;
public SplitFile(File file, Collection<Region> regions) {
this.file = file;
this.regions = new ArrayList<>(regions);
Collections.sort(this.regions);
// Trigger ISE early if total region to map is > Integer.MAX_VALUE
// This can be avoided if we want to map individual regions instead of
// the entire file - but the OS's memory manager will generally take
// care of not actually slurping the whole file into memory instantly
range();
}
private Region first() {
return regions.get(0);
}
private Region last() {
return regions.get(regions.size() - 1);
}
private Region range() {
// This will throw an exception if the total range to map is > Integer.MAX_VALUE
// This could be avoided by mapping individual regions if needed, but likely
// not to perform as well
return new Region(first().start, last().end);
}
synchronized MappedByteBuffer masterBuffer() throws IOException {
if (channel == null) {
channel = new FileInputStream(file).getChannel();
Region range = range();
allRegions = channel.map(FileChannel.MapMode.READ_ONLY, range.start, range.length());
}
return allRegions;
}
@Override
public Iterator<RegionInputStream> iterator() {
if (regions.isEmpty()) {
return Collections.emptyIterator();
}
synchronized (this) {
if (channel != null) {
// Two iterators could result in the channel being closed while still in
// use by another iterator
throw new IllegalStateException("Cannot reuse this object until all streams "
+ "from the previously returned iterator are closed.");
}
}
return new SynchronizedIterator<>(CollectionUtils.convertedIterator(new RegionToInputStream(), regions.iterator()));
}
@Override
public void close() throws Exception {
FileChannel openFileChannel;
synchronized (this) {
openFileChannel = channel;
channel = null;
allRegions = null;
}
if (openFileChannel != null) {
openFileChannel.close();
}
}
private ByteBuffer bufferFor(Region region) throws IOException {
ByteBuffer master = masterBuffer();
master.position((int) region.start);
ByteBuffer result = master.slice();
result.limit(region.length());
return result;
}
@Override
public String toString() {
return "SplitFile{" + file + ", " + regions + "}";
}
private final class RegionToInputStream implements Converter<RegionInputStream, Region> {
private final AtomicInteger counter = new AtomicInteger(regions.size());
@Override
public RegionInputStream convert(Region region) {
try {
ByteBuffer buf = bufferFor(region);
return new CloseCountingInputStream(region, Streams.asInputStream(buf), counter);
} catch (IOException ex) {
return Exceptions.chuck(ex);
}
}
@Override
public Region unconvert(RegionInputStream t) {
throw new UnsupportedOperationException("Not needed.");
}
}
private void onLastStreamClosed() {
try {
close();
} catch (Exception ex) {
Exceptions.chuck(ex);
}
}
private final class CloseCountingInputStream extends RegionInputStream {
final AtomicInteger closeCounter;
private boolean closed;
public CloseCountingInputStream(Region region, InputStream streamToWrap, AtomicInteger closeCounter) {
super(region, streamToWrap);
this.closeCounter = closeCounter;
}
@Override
public void close() throws IOException {
if (!closed) {
closed = true;
try {
super.close();
} finally {
if (0 == closeCounter.decrementAndGet()) {
onLastStreamClosed();
}
}
}
}
}
/**
* Multiple threads will be banging on this iterator at once, so it needs to
* be synchronized, though the underlying collection doesn't.
*
* @param <T> The type
*/
static class SynchronizedIterator<T> implements Iterator<T> {
private final Iterator<T> iterator;
public SynchronizedIterator(Iterator<T> iterator) {
this.iterator = iterator;
}
@Override
public synchronized boolean hasNext() {
return iterator.hasNext();
}
@Override
public synchronized T next() {
return iterator.next();
}
}
}
| 7,185 | 0.642351 | 0.641378 | 213 | 32.788731 | 27.971272 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.492958 | false | false | 4 |
76cde2b31d3220e87ea371fe66318ca3fe1e73bc | 7,095,286,031,020 | 1a2fb33ddd3056bec3c7c4391afd4bab077665a4 | /src/com/navior/ids/android/view/popup/LoadingDialog.java | ddb6fc478ebdd550c2ef906cfe6913ba95db75a2 | []
| no_license | dawnwords/navior_ids | https://github.com/dawnwords/navior_ids | 5c9e167ea542e3338295dc28bb01ecb4b3894b6a | 0e87f402895f68231c0bd92027176e446fd6d32a | refs/heads/master | 2021-01-22T02:28:23.543000 | 2013-12-18T05:28:44 | 2013-12-18T05:28:44 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* ==============================BEGIN_COPYRIGHT===============================
* ===================NAVIOR CO.,LTD. PROPRIETARY INFORMATION==================
* This software is supplied under the terms of a license agreement or
* nondisclosure agreement with NAVIOR CO.,LTD. and may not be copied or
* disclosed except in accordance with the terms of that agreement.
* ==========Copyright (c) 2010 NAVIOR CO.,LTD. All Rights Reserved.===========
* ===============================END_COPYRIGHT================================
*
* @author cs1
* @date 13-11-26
*/
package com.navior.ids.android.view.popup;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import com.navior.ids.android.R;
public class LoadingDialog {
public static ProgressDialog show(Context context, String msg, DialogInterface.OnCancelListener listener) {
return ProgressDialog.show(context, context.getString(R.string.loading), msg, false, true, listener);
}
}
| UTF-8 | Java | 1,013 | java | LoadingDialog.java | Java | [
{
"context": "IGHT================================\n *\n * @author cs1\n * @date 13-11-26\n */\npackage com.navior.ids.andr",
"end": 553,
"score": 0.9996682405471802,
"start": 550,
"tag": "USERNAME",
"value": "cs1"
}
]
| null | []
| /**
* ==============================BEGIN_COPYRIGHT===============================
* ===================NAVIOR CO.,LTD. PROPRIETARY INFORMATION==================
* This software is supplied under the terms of a license agreement or
* nondisclosure agreement with NAVIOR CO.,LTD. and may not be copied or
* disclosed except in accordance with the terms of that agreement.
* ==========Copyright (c) 2010 NAVIOR CO.,LTD. All Rights Reserved.===========
* ===============================END_COPYRIGHT================================
*
* @author cs1
* @date 13-11-26
*/
package com.navior.ids.android.view.popup;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import com.navior.ids.android.R;
public class LoadingDialog {
public static ProgressDialog show(Context context, String msg, DialogInterface.OnCancelListener listener) {
return ProgressDialog.show(context, context.getString(R.string.loading), msg, false, true, listener);
}
}
| 1,013 | 0.627838 | 0.616979 | 25 | 39.52 | 35.284126 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64 | false | false | 4 |
47471c5e2b6a9f64747c9d574b8f13fda8ddc58e | 4,355,096,890,957 | bd4301e2cfecd7a4dd3e815f663e73bcecf1a5d6 | /HimanUserModule/src/main/java/com/cg/main/service/IAdminServiceImpl.java | 8ba47411d74a6a268c648ae2d0bf9d3d372f0d0d | []
| no_license | LaxmiMaranabasari/HimanUserModule | https://github.com/LaxmiMaranabasari/HimanUserModule | 35a7a09a3ad3e38cb286476f8e33094ba16b1b2c | 7cefc1630cb014182f6cdf0935b8318dde0df13e | refs/heads/main | 2023-08-05T04:18:38.234000 | 2021-09-16T12:07:55 | 2021-09-16T12:07:55 | 407,149,233 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cg.main.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.main.beans.Admin;
import com.cg.main.beans.Customer;
import com.cg.main.beans.SigninStatus;
import com.cg.main.beans.User;
import com.cg.main.exception.AdminNotFoundException;
import com.cg.main.exception.InvalidCredentials;
import com.cg.main.exception.NotLoggedInException;
import com.cg.main.repository.AdminRepository;
@Service
public class IAdminServiceImpl implements IAdminService{
@Autowired
private AdminRepository repository;
private Admin a = new Admin();
@Override
public Admin signIn(String contactNo, String password) {
boolean flag = false;
try {
if(a.getContactNo().equals(contactNo) && a.getPassword().equals(password)) {
a.setStatus(SigninStatus.ADMININ);
repository.save(a);
flag = true;
}
else{
flag = false;
a.setStatus(SigninStatus.ADMINOUT);
throw new InvalidCredentials("Invalid Credentials");
}
}
catch(InvalidCredentials i) {
System.out.println(i);
}
if(flag)
return a;
return null;
}
@Override
public Admin signout(String contactNo) {
List<Admin> list = repository.findAll();
boolean flag = false;
try {
for(Admin u : list) {
if(u.getContactNo().equals(contactNo)) {
u.setStatus(SigninStatus.ADMINOUT);
repository.save(u);
a = repository.findById(u.getContactNo()).get();
flag = true;
} else {
flag = false;
throw new InvalidCredentials("Invalid Credentials");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if(flag)
return a;
return null;
}
/*@Override
public String signOut() {
if(a.getStatus().equals(SigninStatus.ADMININ)) {
a.setStatus(SigninStatus.ADMINOUT);
repository.save(a);
} else {
return "You need to login";
}
return "Logged out";
}*/
@Override
public Admin updateAdmin(String contactNo, Admin admin){
Admin temp=null;
try {
temp = repository.findById(contactNo).orElseThrow(()-> new AdminNotFoundException("No admin found with this contactNo: "+a.getContactNo()));
if(temp.getStatus().compareTo(SigninStatus.ADMININ) == 0)
{
temp.setContactNo(a.getContactNo());
temp.setPassword(a.getPassword());
return repository.saveAndFlush(temp);
}
else
{
throw new NotLoggedInException("Please login to update values!!");
}
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*@Override
public Admin removeAdmin(String contactNo) {
Admin deletedAdmin=null;
try {
deletedAdmin=repository.findById(contactNo).orElseThrow(()-> new AdminNotFoundException("Admin not found"));
repository.delete(deletedAdmin);
} catch (AdminNotFoundException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
return deletedAdmin;
}*/
}
| UTF-8 | Java | 3,032 | java | IAdminServiceImpl.java | Java | [
{
"context": "ntactNo(a.getContactNo());\r\n\t\t\t\t temp.setPassword(a.getPassword());\r\n\t\t\t\t return repository.saveAndFlush(temp);\r\n",
"end": 2397,
"score": 0.9992148876190186,
"start": 2384,
"tag": "PASSWORD",
"value": "a.getPassword"
}
]
| null | []
| package com.cg.main.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.main.beans.Admin;
import com.cg.main.beans.Customer;
import com.cg.main.beans.SigninStatus;
import com.cg.main.beans.User;
import com.cg.main.exception.AdminNotFoundException;
import com.cg.main.exception.InvalidCredentials;
import com.cg.main.exception.NotLoggedInException;
import com.cg.main.repository.AdminRepository;
@Service
public class IAdminServiceImpl implements IAdminService{
@Autowired
private AdminRepository repository;
private Admin a = new Admin();
@Override
public Admin signIn(String contactNo, String password) {
boolean flag = false;
try {
if(a.getContactNo().equals(contactNo) && a.getPassword().equals(password)) {
a.setStatus(SigninStatus.ADMININ);
repository.save(a);
flag = true;
}
else{
flag = false;
a.setStatus(SigninStatus.ADMINOUT);
throw new InvalidCredentials("Invalid Credentials");
}
}
catch(InvalidCredentials i) {
System.out.println(i);
}
if(flag)
return a;
return null;
}
@Override
public Admin signout(String contactNo) {
List<Admin> list = repository.findAll();
boolean flag = false;
try {
for(Admin u : list) {
if(u.getContactNo().equals(contactNo)) {
u.setStatus(SigninStatus.ADMINOUT);
repository.save(u);
a = repository.findById(u.getContactNo()).get();
flag = true;
} else {
flag = false;
throw new InvalidCredentials("Invalid Credentials");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
if(flag)
return a;
return null;
}
/*@Override
public String signOut() {
if(a.getStatus().equals(SigninStatus.ADMININ)) {
a.setStatus(SigninStatus.ADMINOUT);
repository.save(a);
} else {
return "You need to login";
}
return "Logged out";
}*/
@Override
public Admin updateAdmin(String contactNo, Admin admin){
Admin temp=null;
try {
temp = repository.findById(contactNo).orElseThrow(()-> new AdminNotFoundException("No admin found with this contactNo: "+a.getContactNo()));
if(temp.getStatus().compareTo(SigninStatus.ADMININ) == 0)
{
temp.setContactNo(a.getContactNo());
temp.setPassword(<PASSWORD>());
return repository.saveAndFlush(temp);
}
else
{
throw new NotLoggedInException("Please login to update values!!");
}
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
/*@Override
public Admin removeAdmin(String contactNo) {
Admin deletedAdmin=null;
try {
deletedAdmin=repository.findById(contactNo).orElseThrow(()-> new AdminNotFoundException("Admin not found"));
repository.delete(deletedAdmin);
} catch (AdminNotFoundException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
return deletedAdmin;
}*/
}
| 3,029 | 0.670185 | 0.669855 | 120 | 23.266666 | 23.191856 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.491667 | false | false | 4 |
bbf6a3f964056846586fbb9b1c840adbfb73ef60 | 39,470,749,476,723 | 5615e0085923c7324fccd6332e190dbedab98a6e | /src/main/java/com/example/demo/service/UserSystemRoleService.java | dd6aa34f66e8ac8af5ac0c6f7a6215f0acb5170c | []
| no_license | ChongDeng/SSO | https://github.com/ChongDeng/SSO | 6467878a7dddb9668327864547be789eaf42865c | 33f83cc63148d3e7eaefbc6b5a4121d35da26272 | refs/heads/master | 2022-04-09T10:14:15.770000 | 2020-02-14T00:46:04 | 2020-02-14T00:46:04 | 238,472,264 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.service;
import com.example.demo.entity.UserSystemRole;
import com.example.demo.mapper.UserSystemRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserSystemRoleService {
@Autowired
UserSystemRoleMapper userSystemRoleMapper;
//1 insert: 能插入的前提是参数record中已赋值的成员覆盖了对应数据表中的所有“not null”字段
public boolean insert(UserSystemRole record)
{
userSystemRoleMapper.insertSelective(record);
return true;
}
//2 remove
public boolean remove(UserSystemRole param)
{
userSystemRoleMapper.remove(param);
return true;
}
//3 update
public boolean update(Long user_id, Long role_id, long new_role_id)
{
userSystemRoleMapper.update(user_id, role_id, new_role_id);
return true;
}
//4 get system role name by user id
public List<UserSystemRole> getItems(Long user_id)
{
UserSystemRole param = new UserSystemRole();
param.setUser_id(user_id);
return userSystemRoleMapper.getItems(param);
}
}
| UTF-8 | Java | 1,226 | java | UserSystemRoleService.java | Java | []
| null | []
| package com.example.demo.service;
import com.example.demo.entity.UserSystemRole;
import com.example.demo.mapper.UserSystemRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserSystemRoleService {
@Autowired
UserSystemRoleMapper userSystemRoleMapper;
//1 insert: 能插入的前提是参数record中已赋值的成员覆盖了对应数据表中的所有“not null”字段
public boolean insert(UserSystemRole record)
{
userSystemRoleMapper.insertSelective(record);
return true;
}
//2 remove
public boolean remove(UserSystemRole param)
{
userSystemRoleMapper.remove(param);
return true;
}
//3 update
public boolean update(Long user_id, Long role_id, long new_role_id)
{
userSystemRoleMapper.update(user_id, role_id, new_role_id);
return true;
}
//4 get system role name by user id
public List<UserSystemRole> getItems(Long user_id)
{
UserSystemRole param = new UserSystemRole();
param.setUser_id(user_id);
return userSystemRoleMapper.getItems(param);
}
}
| 1,226 | 0.70654 | 0.703098 | 46 | 24.26087 | 22.978662 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.434783 | false | false | 4 |
266985c899806b9ca5b7a41d8a82068106d4bfac | 23,175,643,596,476 | 8da195a56aee5a276ac8286ca065cc629843dcec | /src/main/java/com/coy/introduction/systematic/thinking/stream/MaterialStream.java | 1b4ca27a38e5881c8b4166a67aa2d8035f73ff0a | []
| no_license | coy0725/system | https://github.com/coy0725/system | 045a2b55d2911fe3c7a576300e638b0450629c91 | 74d0a6a59c4ee61f190a97675327375c4daa0a50 | refs/heads/master | 2023-04-16T21:40:34.316000 | 2021-04-25T15:57:35 | 2021-04-25T15:57:35 | 358,654,043 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coy.introduction.systematic.thinking.stream;
/**
* 物质流
* 例如树干中的水分,或者学生在大学中的改变
* @author coy
* @since 2021/4/20
**/
public interface MaterialStream extends Stream {
}
| UTF-8 | Java | 230 | java | MaterialStream.java | Java | [
{
"context": "am;\n\n/**\n * 物质流\n * 例如树干中的水分,或者学生在大学中的改变\n * @author coy\n * @since 2021/4/20\n **/\npublic interface Materia",
"end": 107,
"score": 0.9995993971824646,
"start": 104,
"tag": "USERNAME",
"value": "coy"
}
]
| null | []
| package com.coy.introduction.systematic.thinking.stream;
/**
* 物质流
* 例如树干中的水分,或者学生在大学中的改变
* @author coy
* @since 2021/4/20
**/
public interface MaterialStream extends Stream {
}
| 230 | 0.728261 | 0.690217 | 10 | 17.4 | 18.869022 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 4 |
ac4b104d72054d983e28ae5c6579682ae12a7850 | 28,226,525,115,286 | 28fa242fd4c9e426cd9b89770b7867d97a2456b8 | /src/terrapeer/vui/j3dui/control/inputs/EnableInputDragFilter.java | b0069bb03b59ede37f8f2b9c1d04da7109d82602 | []
| no_license | pengpengli/terrapeer | https://github.com/pengpengli/terrapeer | 064bacc0bafe4b65fa7710f5858c08c1843f349d | 1a3bf6c433c89798362c2f7c24872daadc12aae3 | refs/heads/master | 2021-06-02T11:34:50.933000 | 2004-07-19T15:34:04 | 2004-07-19T15:34:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package terrapeer.vui.j3dui.control.inputs;
import javax.media.j3d.*;
import javax.vecmath.*;
import terrapeer.vui.j3dui.utils.Debug;
import terrapeer.vui.j3dui.control.*;
/**
A special input drag filter that enables and disables the
passage of drag events, defaulting to enabled. This filter
should only be used with sensors monitoring the same display
canvas otherwise its operation is undefined. Input events
are used as follows:
<UL>
<LI> InputDragTarget: Input drag.
<LI> InputCancelTarget: Cancels any active drag. Causes the
output drag position to return to its starting position and
blocks further dragging until drag stop.
<LI> EnableTarget: Enables and disables dragging, with drag
starts and stops issued as needed.
</UL>
<P>
Because drag events are state sensitive (see below), unlike
with other events, this filter is the sole means for enabling
and disabling input drag events other than disabling the
sensor itself.
<P>
To accommodate drags being enabled and disabled in mid-stride,
if a drag is active when disable occurs the output drag will
be terminated. If a drag is active when an enable occurs or
if no drag is active but a "do drag" event occurs then the
output drag will be initiate.
@author Jon Barrilleaux,
copyright (c) 1999 Jon Barrilleaux,
All Rights Reserved.
*/
public class EnableInputDragFilter implements InputDragTarget,
InputCancelTarget, EnableTarget {
// public interface =========================================
/**
Constructs an EnableInputDragFilter with event target
<target>.
@param target Event target. Never null.
*/
public EnableInputDragFilter(InputDragTarget target) {
if(target==null) throw new
IllegalArgumentException("<target> is null.");
_eventTarget = target;
}
/**
Constructs an EnableInputDragFilter with event target
<target> and enable set to <enable>.
@param target Event target. Never null.
@param enable True to enable events, false to disable them.
*/
public EnableInputDragFilter(InputDragTarget target,
boolean enable) {
this(target);
setEnable(enable);
}
/**
Gets the event target.
@return Reference to the event target.
*/
public InputDragTarget getEventTarget() {
return _eventTarget;
}
/**
Gets the enable state.
@return True if enabled.
*/
public boolean getEnable() {
return _enable;
}
// EnableTarget implementation
public void setEnable(boolean enable) {
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter.enable",
"ENABLE:EnableInputDragFilter:setEnable:" +
" enable=" + enable +
" oldEnable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(_enable && !enable && _targetDrag) {
_targetDrag = false;
_eventTarget.stopInputDrag(_source, _pos);
}
if(!_enable && enable && _sourceDrag) {
_targetDrag = true;
_eventTarget.startInputDrag(_source, _pos);
}
_enable = enable;
}
// InputCancelTarget implementation
public void setInputCancel() {
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter.cancel",
"EnableInputDragFilter:setInputCancel:" +
" enable=" + _enable +
" targetDrag=" + _targetDrag +
" startPos=" + _startPos +
" startSource=" + _startSource);}
// if drag active, restore start position but no stop
if(_enable && _targetDrag) {
_cancel = true;
_eventTarget.doInputDrag(_startSource, _startPos);
}
}
// InputDragTarget implementation
public void startInputDrag(Canvas3D source, Vector2d pos) {
_cancel = false;
_startSource = source;
_startPos.set(pos);
_source = source;
_pos.set(pos);
_sourceDrag = true;
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:startInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
_targetDrag = true;
_eventTarget.startInputDrag(source, pos);
}
public void doInputDrag(Canvas3D source, Vector2d pos) {
_source = source;
_pos.set(pos);
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:doInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
if(_cancel) return;
if(!_targetDrag) {
_sourceDrag = true;
_targetDrag = true;
_eventTarget.startInputDrag(source, pos);
}
getEventTarget().doInputDrag(source, pos);
}
public void stopInputDrag(Canvas3D source, Vector2d pos) {
_source = source;
_pos.set(pos);
_sourceDrag = false;
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:stopInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
if(!_targetDrag) return;
_targetDrag = false;
_eventTarget.stopInputDrag(source, pos);
}
// personal body ============================================
/** Event target. */
private InputDragTarget _eventTarget;
/** True if events enabled. */
private boolean _enable = true;
/** True if a source drag is active. */
private boolean _sourceDrag = false;
/** True if an target drag is active. */
private boolean _targetDrag = false;
/** Last source. */
private Canvas3D _source;
/** Last pos. */
private Vector2d _pos = new Vector2d();
/** True if drag canceled. */
private boolean _cancel = false;
/** Starting source for cancel. */
private Canvas3D _startSource;
/** Starting pos for cancel. */
private Vector2d _startPos = new Vector2d();
} | UTF-8 | Java | 5,667 | java | EnableInputDragFilter.java | Java | [
{
"context": " then the\noutput drag will be initiate. \n\n@author Jon Barrilleaux,\ncopyright (c) 1999 Jon Barrilleaux,\nAll Rights R",
"end": 1244,
"score": 0.9998475909233093,
"start": 1229,
"tag": "NAME",
"value": "Jon Barrilleaux"
},
{
"context": "te. \n\n@author Jon Barrilleaux,\ncopyright (c) 1999 Jon Barrilleaux,\nAll Rights Reserved.\n*/\n\npublic class EnableInpu",
"end": 1280,
"score": 0.9998570680618286,
"start": 1265,
"tag": "NAME",
"value": "Jon Barrilleaux"
}
]
| null | []
| package terrapeer.vui.j3dui.control.inputs;
import javax.media.j3d.*;
import javax.vecmath.*;
import terrapeer.vui.j3dui.utils.Debug;
import terrapeer.vui.j3dui.control.*;
/**
A special input drag filter that enables and disables the
passage of drag events, defaulting to enabled. This filter
should only be used with sensors monitoring the same display
canvas otherwise its operation is undefined. Input events
are used as follows:
<UL>
<LI> InputDragTarget: Input drag.
<LI> InputCancelTarget: Cancels any active drag. Causes the
output drag position to return to its starting position and
blocks further dragging until drag stop.
<LI> EnableTarget: Enables and disables dragging, with drag
starts and stops issued as needed.
</UL>
<P>
Because drag events are state sensitive (see below), unlike
with other events, this filter is the sole means for enabling
and disabling input drag events other than disabling the
sensor itself.
<P>
To accommodate drags being enabled and disabled in mid-stride,
if a drag is active when disable occurs the output drag will
be terminated. If a drag is active when an enable occurs or
if no drag is active but a "do drag" event occurs then the
output drag will be initiate.
@author <NAME>,
copyright (c) 1999 <NAME>,
All Rights Reserved.
*/
public class EnableInputDragFilter implements InputDragTarget,
InputCancelTarget, EnableTarget {
// public interface =========================================
/**
Constructs an EnableInputDragFilter with event target
<target>.
@param target Event target. Never null.
*/
public EnableInputDragFilter(InputDragTarget target) {
if(target==null) throw new
IllegalArgumentException("<target> is null.");
_eventTarget = target;
}
/**
Constructs an EnableInputDragFilter with event target
<target> and enable set to <enable>.
@param target Event target. Never null.
@param enable True to enable events, false to disable them.
*/
public EnableInputDragFilter(InputDragTarget target,
boolean enable) {
this(target);
setEnable(enable);
}
/**
Gets the event target.
@return Reference to the event target.
*/
public InputDragTarget getEventTarget() {
return _eventTarget;
}
/**
Gets the enable state.
@return True if enabled.
*/
public boolean getEnable() {
return _enable;
}
// EnableTarget implementation
public void setEnable(boolean enable) {
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter.enable",
"ENABLE:EnableInputDragFilter:setEnable:" +
" enable=" + enable +
" oldEnable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(_enable && !enable && _targetDrag) {
_targetDrag = false;
_eventTarget.stopInputDrag(_source, _pos);
}
if(!_enable && enable && _sourceDrag) {
_targetDrag = true;
_eventTarget.startInputDrag(_source, _pos);
}
_enable = enable;
}
// InputCancelTarget implementation
public void setInputCancel() {
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter.cancel",
"EnableInputDragFilter:setInputCancel:" +
" enable=" + _enable +
" targetDrag=" + _targetDrag +
" startPos=" + _startPos +
" startSource=" + _startSource);}
// if drag active, restore start position but no stop
if(_enable && _targetDrag) {
_cancel = true;
_eventTarget.doInputDrag(_startSource, _startPos);
}
}
// InputDragTarget implementation
public void startInputDrag(Canvas3D source, Vector2d pos) {
_cancel = false;
_startSource = source;
_startPos.set(pos);
_source = source;
_pos.set(pos);
_sourceDrag = true;
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:startInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
_targetDrag = true;
_eventTarget.startInputDrag(source, pos);
}
public void doInputDrag(Canvas3D source, Vector2d pos) {
_source = source;
_pos.set(pos);
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:doInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
if(_cancel) return;
if(!_targetDrag) {
_sourceDrag = true;
_targetDrag = true;
_eventTarget.startInputDrag(source, pos);
}
getEventTarget().doInputDrag(source, pos);
}
public void stopInputDrag(Canvas3D source, Vector2d pos) {
_source = source;
_pos.set(pos);
_sourceDrag = false;
if(Debug.getEnabled()){
Debug.println(this, "EnableInputDragFilter",
"DRAG:EnableInputDragFilter:stopInputDrag:" +
" pos=" + pos +
" source=" + source +
" enable=" + _enable +
" srcDrag=" + _sourceDrag +
" trgDrag=" + _targetDrag);}
if(!_enable) return;
if(!_targetDrag) return;
_targetDrag = false;
_eventTarget.stopInputDrag(source, pos);
}
// personal body ============================================
/** Event target. */
private InputDragTarget _eventTarget;
/** True if events enabled. */
private boolean _enable = true;
/** True if a source drag is active. */
private boolean _sourceDrag = false;
/** True if an target drag is active. */
private boolean _targetDrag = false;
/** Last source. */
private Canvas3D _source;
/** Last pos. */
private Vector2d _pos = new Vector2d();
/** True if drag canceled. */
private boolean _cancel = false;
/** Starting source for cancel. */
private Canvas3D _startSource;
/** Starting pos for cancel. */
private Vector2d _startPos = new Vector2d();
} | 5,649 | 0.691371 | 0.687842 | 234 | 23.222221 | 19.291782 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.294872 | false | false | 4 |
3c2d3a54ceef12a7a8eb9ae4eb10372f796f1123 | 10,213,432,283,284 | 78369970ce0b2b6d49523a79a3c82e65a6bf1068 | /codereview/src/main/java/com/chrome/codereview/phone/UnifiedDiffAdapter.java | 2378f01986faf0d92e01ca996ff77e217f8e270b | [
"MIT",
"CC-BY-3.0"
]
| permissive | svasilinets/codereview.chromium | https://github.com/svasilinets/codereview.chromium | 1214abd1eb9c7d8cc14d91149d51877662c2d1ba | 889188da440050275441e20f8a13b07d58b85ef3 | refs/heads/master | 2016-09-10T01:22:43.189000 | 2015-06-15T18:08:06 | 2015-06-15T18:08:06 | 18,726,131 | 1 | 1 | null | false | 2015-01-28T08:22:26 | 2014-04-13T09:54:17 | 2014-12-28T01:32:33 | 2015-01-28T08:22:26 | 1,260 | 1 | 2 | 10 | Java | null | null | package com.chrome.codereview.phone;
import android.content.Context;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.chrome.codereview.DiffAdapter;
import com.chrome.codereview.R;
import com.chrome.codereview.model.Comment;
import com.chrome.codereview.model.FileDiff;
import com.chrome.codereview.utils.ViewUtils;
import java.util.HashMap;
import java.util.List;
public class UnifiedDiffAdapter extends DiffAdapter implements AdapterView.OnItemClickListener{
public static final int LINE_TYPE = 0;
public static final int COMMENT_TYPE = 1;
public UnifiedDiffAdapter(Context context, FileDiff fileDiff, List<Comment> comments) {
super(context, fileDiff, comments);
resetComments(comments);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return linesWithComments.get(position) instanceof FileDiff.DiffLine ? LINE_TYPE : COMMENT_TYPE;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == LINE_TYPE) {
return getDiffLineView((FileDiff.DiffLine) getItem(position), convertView, parent);
}
return getCommentView((Comment) getItem(position), convertView, parent);
}
public View getCommentView(Comment comment, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.comment_item, parent, false);
}
fillCommentView(comment, convertView);
return convertView;
}
public View getDiffLineView(FileDiff.DiffLine line, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.diff_line, parent, false);
}
int resource;
switch (line.type()) {
case LEFT:
resource = R.drawable.diff_removed_line_bg;
break;
case RIGHT:
resource = R.drawable.diff_added_line_bg;
break;
case MARKER:
resource = R.drawable.diff_marker_line_bg;
break;
default:
resource = R.drawable.diff_default_line_bg;
}
convertView.setBackgroundDrawable(context.getResources().getDrawable(resource));
ViewUtils.setText(convertView, android.R.id.text1, line.text());
return convertView;
}
@Override
protected void rebuildWithComments(HashMap<Pair<Integer, Boolean>, List<Comment>> lineToComments) {
for (FileDiff.DiffLine diffLine : diffLines) {
linesWithComments.add(diffLine);
switch (diffLine.type()) {
case MARKER:
break;
case BOTH_SIDE:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.leftLineNumber(), true)));
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.rightLineNumber(), false)));
break;
case RIGHT:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.rightLineNumber(), false)));
break;
case LEFT:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.leftLineNumber(), true)));
break;
}
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (this.getItemViewType(position) != LINE_TYPE || commentActionListener == null) {
return;
}
FileDiff.DiffLine diffLine = (FileDiff.DiffLine) getItem(position);
if (diffLine.type() == FileDiff.LineType.MARKER) {
return;
}
int line = diffLine.type() == FileDiff.LineType.LEFT ? diffLine.leftLineNumber() : diffLine.rightLineNumber();
commentActionListener.writeComment(line, diffLine.type() == FileDiff.LineType.LEFT);
}
private static void addAll(List<Object> main, List<Comment> add) {
if (add != null) {
main.addAll(add);
}
}
}
| UTF-8 | Java | 4,353 | java | UnifiedDiffAdapter.java | Java | []
| null | []
| package com.chrome.codereview.phone;
import android.content.Context;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.chrome.codereview.DiffAdapter;
import com.chrome.codereview.R;
import com.chrome.codereview.model.Comment;
import com.chrome.codereview.model.FileDiff;
import com.chrome.codereview.utils.ViewUtils;
import java.util.HashMap;
import java.util.List;
public class UnifiedDiffAdapter extends DiffAdapter implements AdapterView.OnItemClickListener{
public static final int LINE_TYPE = 0;
public static final int COMMENT_TYPE = 1;
public UnifiedDiffAdapter(Context context, FileDiff fileDiff, List<Comment> comments) {
super(context, fileDiff, comments);
resetComments(comments);
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return linesWithComments.get(position) instanceof FileDiff.DiffLine ? LINE_TYPE : COMMENT_TYPE;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == LINE_TYPE) {
return getDiffLineView((FileDiff.DiffLine) getItem(position), convertView, parent);
}
return getCommentView((Comment) getItem(position), convertView, parent);
}
public View getCommentView(Comment comment, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.comment_item, parent, false);
}
fillCommentView(comment, convertView);
return convertView;
}
public View getDiffLineView(FileDiff.DiffLine line, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.diff_line, parent, false);
}
int resource;
switch (line.type()) {
case LEFT:
resource = R.drawable.diff_removed_line_bg;
break;
case RIGHT:
resource = R.drawable.diff_added_line_bg;
break;
case MARKER:
resource = R.drawable.diff_marker_line_bg;
break;
default:
resource = R.drawable.diff_default_line_bg;
}
convertView.setBackgroundDrawable(context.getResources().getDrawable(resource));
ViewUtils.setText(convertView, android.R.id.text1, line.text());
return convertView;
}
@Override
protected void rebuildWithComments(HashMap<Pair<Integer, Boolean>, List<Comment>> lineToComments) {
for (FileDiff.DiffLine diffLine : diffLines) {
linesWithComments.add(diffLine);
switch (diffLine.type()) {
case MARKER:
break;
case BOTH_SIDE:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.leftLineNumber(), true)));
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.rightLineNumber(), false)));
break;
case RIGHT:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.rightLineNumber(), false)));
break;
case LEFT:
addAll(linesWithComments, lineToComments.get(new Pair<Integer, Boolean>(diffLine.leftLineNumber(), true)));
break;
}
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (this.getItemViewType(position) != LINE_TYPE || commentActionListener == null) {
return;
}
FileDiff.DiffLine diffLine = (FileDiff.DiffLine) getItem(position);
if (diffLine.type() == FileDiff.LineType.MARKER) {
return;
}
int line = diffLine.type() == FileDiff.LineType.LEFT ? diffLine.leftLineNumber() : diffLine.rightLineNumber();
commentActionListener.writeComment(line, diffLine.type() == FileDiff.LineType.LEFT);
}
private static void addAll(List<Object> main, List<Comment> add) {
if (add != null) {
main.addAll(add);
}
}
}
| 4,353 | 0.632437 | 0.631518 | 119 | 35.57983 | 33.882519 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.781513 | false | false | 4 |
cdeb55d88e97bee9e09fbab534c73e093476ef27 | 10,213,432,285,918 | 2e6efa93e5d965b2de736f58502807b5cf647ebc | /src/test/java/pages/URL.java | 89e9ca8783e73a4f5a2f21fe7f43fc28881cc426 | []
| no_license | demola09/swaglabs-automated-webdriver-testsuite | https://github.com/demola09/swaglabs-automated-webdriver-testsuite | 01961b6c2339b1beb01624b74848dffb2773189e | c235c561b3c722b8b1dc0b1db9192f3e5ddd7a6f | refs/heads/main | 2023-04-18T03:04:49.354000 | 2021-04-29T20:23:49 | 2021-04-29T20:23:49 | 362,930,309 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pages;
import org.openqa.selenium.WebDriver;
public class URL {
private WebDriver driver = null;
public String BASE_URL = "https://www.saucedemo.com/";
//Used only when swags is UAT
public String SwagsUrl() {
// TODO Auto-generated method stub
return BASE_URL;
}
public void launchURL(){
//URL baseUrl = new URL();
driver.get(SwagsUrl());
driver.manage().window().maximize();
}
}
| UTF-8 | Java | 415 | java | URL.java | Java | []
| null | []
| package pages;
import org.openqa.selenium.WebDriver;
public class URL {
private WebDriver driver = null;
public String BASE_URL = "https://www.saucedemo.com/";
//Used only when swags is UAT
public String SwagsUrl() {
// TODO Auto-generated method stub
return BASE_URL;
}
public void launchURL(){
//URL baseUrl = new URL();
driver.get(SwagsUrl());
driver.manage().window().maximize();
}
}
| 415 | 0.681928 | 0.681928 | 26 | 14.961538 | 16.312998 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.961538 | false | false | 4 |
e4ee6ca6cb658fbeafcb09d7d9191a5799f2d483 | 21,775,484,256,778 | 57cff58d7a4b774a647d5a43ec9e2276ea4a44b7 | /BoardView.java | 67a04908d67971ba047aa3083ed4516242ccdd4f | []
| no_license | rdgehan/SuodokuApp | https://github.com/rdgehan/SuodokuApp | 1759005300c531ca3854f590ca86bfa247769323 | d8285d0e313c9a37340a7a011c652f5d2a456748 | refs/heads/master | 2020-04-05T22:28:47.759000 | 2018-11-12T18:30:02 | 2018-11-12T18:30:02 | 157,257,530 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.utep.cs.cs4330.sudoku;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import java.util.ArrayList;
import java.util.List;
import edu.utep.cs.cs4330.sudoku.model.Board;
import edu.utep.cs.cs4330.sudoku.model.Square;
/**
* A special view class to display a Sudoku board modeled by the
* {@link edu.utep.cs.cs4330.sudoku.model.Board} class. You need to write code for
* the <code>onDraw()</code> method.
*
* @see edu.utep.cs.cs4330.sudoku.model.Board
* @author cheon
*/
public class BoardView extends View {
/** To notify a square selection. */
public interface SelectionListener {
/** Called when a square of the board is selected by tapping.
* @param x 0-based column index of the selected square.
* @param y 0-based row index of the selected square. */
void onSelection(int x, int y);
}
/** Listeners to be notified when a square is selected. */
private final List<SelectionListener> listeners = new ArrayList<>();
/** Number of squares in rows and columns.*/
private int boardSize = 9;
/** Board to be displayed by this view. */
private Board board;
/** Width and height of each square. This is automatically calculated
* this view's dimension is changed. */
private float squareSize;
/** Translation of screen coordinates to display the grid at the center. */
private float transX;
/** Translation of screen coordinates to display the grid at the center. */
private float transY;
/** Paint to draw the background of the grid. */
private final Paint boardPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
int boardColor = Color.rgb(201, 186, 145);
boardPaint.setColor(boardColor);
boardPaint.setAlpha(80); // semi transparent
}
/** Create a new board view to be run in the given context. */
public BoardView(Context context) { //@cons
this(context, null);
}
/** Create a new board view by inflating it from XML. */
public BoardView(Context context, AttributeSet attrs) { //@cons
this(context, attrs, 0);
}
/** Create a new instance by inflating it from XML and apply a class-specific base
* style from a theme attribute. */
public BoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setSaveEnabled(true);
getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
}
/** Set the board to be displayed by this view. */
public void setBoard(Board board) {
this.board = board;
boardSize = board.size;
}
/** Draw a 2-D graphics representation of the associated board. */
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(transX, transY);
if (board != null) {
drawGrid(canvas);
drawSquares(canvas);
}
canvas.translate(-transX, -transY);
}
/** Draw horizontal and vertical grid lines. */
private void drawGrid(Canvas canvas) {
final float maxCoord = maxCoord();
canvas.drawRect(0, 0, maxCoord, maxCoord, boardPaint);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
if(boardSize == 9) {
for (int i = -1; i <= 1; i++) {
canvas.drawLine(maxCoord / 3 + i, 0, maxCoord / 3 + i, maxCoord, paint);
canvas.drawLine(maxCoord * 2 / 3 + i, 0, maxCoord * 2 / 3 + i, maxCoord, paint);
canvas.drawLine(0, maxCoord / 3 + i, maxCoord, maxCoord / 3 + i, paint);
canvas.drawLine(0, maxCoord * 2 / 3 + i, maxCoord, maxCoord * 2 / 3 + i, paint);
}
}
else{
for (int i = -1; i <= 1; i++) {
canvas.drawLine(maxCoord / 2 + i, 0, maxCoord / 2 + i, maxCoord, paint);
canvas.drawLine(0, maxCoord / 2 + i, maxCoord, maxCoord / 2 + i, paint);
}
}
for(int i = 1; i < boardSize; i++){
canvas.drawLine(maxCoord/boardSize*i, 0, maxCoord/boardSize*i, maxCoord, paint);
canvas.drawLine(0, maxCoord/boardSize*i, maxCoord, maxCoord/boardSize*i, paint);
}
}
public boolean hintsEnabled;
/** Draw all the squares (numbers) of the associated board. */
private void drawSquares(Canvas canvas) {
float max = maxCoord();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(max/boardSize - max/(boardSize*10));
Paint peerPaint = new Paint();
peerPaint.setColor(Color.GREEN);
peerPaint.setTextSize(max/boardSize - max/(boardSize*10));
Paint lockedSquare = new Paint();
lockedSquare.setColor(Color.BLACK);
lockedSquare.setTextSize(max/boardSize - max/(boardSize*10));
Paint lockSqBg = new Paint();
int lockedSquareColor = Color.rgb(200, 185, 144);
lockSqBg.setColor(lockedSquareColor);
Paint smallSquare = new Paint();
smallSquare.setColor(Color.BLACK);
smallSquare.setTextSize(max/(3*boardSize));
Paint sqrSelpaint = new Paint();
int sqrSelColor = Color.rgb(200, 215, 154);
sqrSelpaint.setColor(sqrSelColor);
Square[][] b = board.board;
for(int i = 0; i < boardSize; i++) {
for(int j = 0; j < boardSize; j++) {
if(board.board[i][j].isSelected)
canvas.drawRect(i*max/boardSize + 5, j*max/boardSize + 5, (i+1)*max/boardSize - 5, (j+1)*max/boardSize - 5, sqrSelpaint);
if(board.board[i][j].value != 0) {
String s = "" + board.board[i][j].value + "";
if(board.board[i][j].locked) {
canvas.drawRect(i*max/boardSize + 5, j*max/boardSize + 5, (i+1)*max/boardSize - 5, (j+1)*max/boardSize - 5, lockSqBg);
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), lockedSquare);
}
else {
if(board.board[i][j].placedByPeer)
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), peerPaint);
else
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), paint);
}
}
else if(hintsEnabled){
String myString = "";
String myString2 = "";
for(int x = 1; x <= boardSize; x++){
if(board.board[i][j].isOption(x)){
if(x <= boardSize/2)
myString += "" + x;
else
myString2 += "" + x;
}
canvas.drawText(myString2, max / boardSize * (i) + (max / boardSize / 8), max / boardSize * (j + 1) - (max / boardSize / 6), smallSquare);
canvas.drawText(myString, max / boardSize * (i) + (max / boardSize / 8), max / boardSize * (j + 1) - (max / boardSize / 2), smallSquare);
}
}
}
}
}
/** Overridden here to detect tapping on the board and
* to notify the selected square if exists. */
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
int xy = locateSquare(event.getX(), event.getY());
if (xy >= 0) {
// xy encoded as: x * 100 + y
notifySelection(xy / 100, xy % 100);
}
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
/**
* Given screen coordinates, locate the corresponding square of the board, or
* -1 if there is no corresponding square in the board.
* The result is encoded as <code>x*100 + y</code>, where x and y are 0-based
* column/row indexes of the corresponding square.
*/
private int locateSquare(float x, float y) {
x -= transX;
y -= transY;
if (x <= maxCoord() && y <= maxCoord()) {
final float squareSize = lineGap();
int ix = (int) (x / squareSize);
int iy = (int) (y / squareSize);
return ix * 100 + iy;
}
return -1;
}
/** To obtain the dimension of this view. */
private final ViewTreeObserver.OnGlobalLayoutListener layoutListener
= new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
squareSize = lineGap();
float width = Math.min(getMeasuredWidth(), getMeasuredHeight());
transX = (getMeasuredWidth() - width) / 2f;
transY = (getMeasuredHeight() - width) / 2f;
}
};
/** Return the distance between two consecutive horizontal/vertical lines. */
protected float lineGap() {
return Math.min(getMeasuredWidth(), getMeasuredHeight()) / (float) boardSize;
}
/** Return the number of horizontal/vertical lines. */
private int numOfLines() { //@helper
return boardSize + 1;
}
/** Return the maximum screen coordinate. */
protected float maxCoord() { //@helper
return lineGap() * (numOfLines() - 1);
}
/** Register the given listener. */
public void addSelectionListener(SelectionListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
/** Unregister the given listener. */
public void removeSelectionListener(SelectionListener listener) {
listeners.remove(listener);
}
/** Notify a square selection to all registered listeners.
*
* @param x 0-based column index of the selected square
* @param y 0-based row index of the selected square
*/
private void notifySelection(int x, int y) {
for (SelectionListener listener: listeners) {
listener.onSelection(x, y);
}
}
}
| UTF-8 | Java | 10,943 | java | BoardView.java | Java | [
{
"context": " edu.utep.cs.cs4330.sudoku.model.Board\r\n * @author cheon\r\n */\r\npublic class BoardView extends View {\r\n\r\n ",
"end": 717,
"score": 0.9788757562637329,
"start": 712,
"tag": "USERNAME",
"value": "cheon"
}
]
| null | []
| package edu.utep.cs.cs4330.sudoku;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import java.util.ArrayList;
import java.util.List;
import edu.utep.cs.cs4330.sudoku.model.Board;
import edu.utep.cs.cs4330.sudoku.model.Square;
/**
* A special view class to display a Sudoku board modeled by the
* {@link edu.utep.cs.cs4330.sudoku.model.Board} class. You need to write code for
* the <code>onDraw()</code> method.
*
* @see edu.utep.cs.cs4330.sudoku.model.Board
* @author cheon
*/
public class BoardView extends View {
/** To notify a square selection. */
public interface SelectionListener {
/** Called when a square of the board is selected by tapping.
* @param x 0-based column index of the selected square.
* @param y 0-based row index of the selected square. */
void onSelection(int x, int y);
}
/** Listeners to be notified when a square is selected. */
private final List<SelectionListener> listeners = new ArrayList<>();
/** Number of squares in rows and columns.*/
private int boardSize = 9;
/** Board to be displayed by this view. */
private Board board;
/** Width and height of each square. This is automatically calculated
* this view's dimension is changed. */
private float squareSize;
/** Translation of screen coordinates to display the grid at the center. */
private float transX;
/** Translation of screen coordinates to display the grid at the center. */
private float transY;
/** Paint to draw the background of the grid. */
private final Paint boardPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
{
int boardColor = Color.rgb(201, 186, 145);
boardPaint.setColor(boardColor);
boardPaint.setAlpha(80); // semi transparent
}
/** Create a new board view to be run in the given context. */
public BoardView(Context context) { //@cons
this(context, null);
}
/** Create a new board view by inflating it from XML. */
public BoardView(Context context, AttributeSet attrs) { //@cons
this(context, attrs, 0);
}
/** Create a new instance by inflating it from XML and apply a class-specific base
* style from a theme attribute. */
public BoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setSaveEnabled(true);
getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
}
/** Set the board to be displayed by this view. */
public void setBoard(Board board) {
this.board = board;
boardSize = board.size;
}
/** Draw a 2-D graphics representation of the associated board. */
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(transX, transY);
if (board != null) {
drawGrid(canvas);
drawSquares(canvas);
}
canvas.translate(-transX, -transY);
}
/** Draw horizontal and vertical grid lines. */
private void drawGrid(Canvas canvas) {
final float maxCoord = maxCoord();
canvas.drawRect(0, 0, maxCoord, maxCoord, boardPaint);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
if(boardSize == 9) {
for (int i = -1; i <= 1; i++) {
canvas.drawLine(maxCoord / 3 + i, 0, maxCoord / 3 + i, maxCoord, paint);
canvas.drawLine(maxCoord * 2 / 3 + i, 0, maxCoord * 2 / 3 + i, maxCoord, paint);
canvas.drawLine(0, maxCoord / 3 + i, maxCoord, maxCoord / 3 + i, paint);
canvas.drawLine(0, maxCoord * 2 / 3 + i, maxCoord, maxCoord * 2 / 3 + i, paint);
}
}
else{
for (int i = -1; i <= 1; i++) {
canvas.drawLine(maxCoord / 2 + i, 0, maxCoord / 2 + i, maxCoord, paint);
canvas.drawLine(0, maxCoord / 2 + i, maxCoord, maxCoord / 2 + i, paint);
}
}
for(int i = 1; i < boardSize; i++){
canvas.drawLine(maxCoord/boardSize*i, 0, maxCoord/boardSize*i, maxCoord, paint);
canvas.drawLine(0, maxCoord/boardSize*i, maxCoord, maxCoord/boardSize*i, paint);
}
}
public boolean hintsEnabled;
/** Draw all the squares (numbers) of the associated board. */
private void drawSquares(Canvas canvas) {
float max = maxCoord();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(max/boardSize - max/(boardSize*10));
Paint peerPaint = new Paint();
peerPaint.setColor(Color.GREEN);
peerPaint.setTextSize(max/boardSize - max/(boardSize*10));
Paint lockedSquare = new Paint();
lockedSquare.setColor(Color.BLACK);
lockedSquare.setTextSize(max/boardSize - max/(boardSize*10));
Paint lockSqBg = new Paint();
int lockedSquareColor = Color.rgb(200, 185, 144);
lockSqBg.setColor(lockedSquareColor);
Paint smallSquare = new Paint();
smallSquare.setColor(Color.BLACK);
smallSquare.setTextSize(max/(3*boardSize));
Paint sqrSelpaint = new Paint();
int sqrSelColor = Color.rgb(200, 215, 154);
sqrSelpaint.setColor(sqrSelColor);
Square[][] b = board.board;
for(int i = 0; i < boardSize; i++) {
for(int j = 0; j < boardSize; j++) {
if(board.board[i][j].isSelected)
canvas.drawRect(i*max/boardSize + 5, j*max/boardSize + 5, (i+1)*max/boardSize - 5, (j+1)*max/boardSize - 5, sqrSelpaint);
if(board.board[i][j].value != 0) {
String s = "" + board.board[i][j].value + "";
if(board.board[i][j].locked) {
canvas.drawRect(i*max/boardSize + 5, j*max/boardSize + 5, (i+1)*max/boardSize - 5, (j+1)*max/boardSize - 5, lockSqBg);
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), lockedSquare);
}
else {
if(board.board[i][j].placedByPeer)
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), peerPaint);
else
canvas.drawText(s, max / boardSize * (i) + (max / boardSize / 4), max / boardSize * (j + 1) - (max / boardSize / 6), paint);
}
}
else if(hintsEnabled){
String myString = "";
String myString2 = "";
for(int x = 1; x <= boardSize; x++){
if(board.board[i][j].isOption(x)){
if(x <= boardSize/2)
myString += "" + x;
else
myString2 += "" + x;
}
canvas.drawText(myString2, max / boardSize * (i) + (max / boardSize / 8), max / boardSize * (j + 1) - (max / boardSize / 6), smallSquare);
canvas.drawText(myString, max / boardSize * (i) + (max / boardSize / 8), max / boardSize * (j + 1) - (max / boardSize / 2), smallSquare);
}
}
}
}
}
/** Overridden here to detect tapping on the board and
* to notify the selected square if exists. */
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
int xy = locateSquare(event.getX(), event.getY());
if (xy >= 0) {
// xy encoded as: x * 100 + y
notifySelection(xy / 100, xy % 100);
}
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
/**
* Given screen coordinates, locate the corresponding square of the board, or
* -1 if there is no corresponding square in the board.
* The result is encoded as <code>x*100 + y</code>, where x and y are 0-based
* column/row indexes of the corresponding square.
*/
private int locateSquare(float x, float y) {
x -= transX;
y -= transY;
if (x <= maxCoord() && y <= maxCoord()) {
final float squareSize = lineGap();
int ix = (int) (x / squareSize);
int iy = (int) (y / squareSize);
return ix * 100 + iy;
}
return -1;
}
/** To obtain the dimension of this view. */
private final ViewTreeObserver.OnGlobalLayoutListener layoutListener
= new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
squareSize = lineGap();
float width = Math.min(getMeasuredWidth(), getMeasuredHeight());
transX = (getMeasuredWidth() - width) / 2f;
transY = (getMeasuredHeight() - width) / 2f;
}
};
/** Return the distance between two consecutive horizontal/vertical lines. */
protected float lineGap() {
return Math.min(getMeasuredWidth(), getMeasuredHeight()) / (float) boardSize;
}
/** Return the number of horizontal/vertical lines. */
private int numOfLines() { //@helper
return boardSize + 1;
}
/** Return the maximum screen coordinate. */
protected float maxCoord() { //@helper
return lineGap() * (numOfLines() - 1);
}
/** Register the given listener. */
public void addSelectionListener(SelectionListener listener) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
/** Unregister the given listener. */
public void removeSelectionListener(SelectionListener listener) {
listeners.remove(listener);
}
/** Notify a square selection to all registered listeners.
*
* @param x 0-based column index of the selected square
* @param y 0-based row index of the selected square
*/
private void notifySelection(int x, int y) {
for (SelectionListener listener: listeners) {
listener.onSelection(x, y);
}
}
}
| 10,943 | 0.555789 | 0.541808 | 278 | 37.363308 | 30.929853 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.730216 | false | false | 4 |
a887246945dbf39b3ee51b6f58b9933433b9de6f | 22,393,959,537,408 | dd4e5a15965ec40bfcf6d0fbb773bed4d9e87d2a | /src/main/java/com/fastdata/algorithm/easy/hashtable/IsomorphicStrings.java | dd1e6c7b8266dd224d2dd6c52e4e0088333e64ab | []
| no_license | lucky0604/leetcode-practice | https://github.com/lucky0604/leetcode-practice | 6d27719f5e771df75f4aba9c74141913858045f1 | fc4a22ea22dbe82877f45770af8461f1b2e618af | refs/heads/main | 2023-08-15T07:26:36.082000 | 2021-09-20T04:45:37 | 2021-09-20T04:45:37 | 334,917,997 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fastdata.algorithm.easy.hashtable;
import java.util.HashMap;
import java.util.Map;
public class IsomorphicStrings {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
// set hashmap to assign keys and values to the string
Map<Character, Character> map = new HashMap<Character, Character>();
char[] sArr = new char[s.length()];
char[] tArr = new char[t.length()];
for (int i = 0; i < s.length(); i ++) {
sArr[i] = s.charAt(i);
tArr[i] = t.charAt(i);
}
for (int i = 0; i < sArr.length; i ++) {
char s1 = sArr[i];
char t1 = tArr[i];
if (!map.containsKey(s1) && !map.containsValue(t1)) {
map.put(s1, t1);
}
if ((!map.containsKey(s1) && map.containsValue(t1) || !map.get(s1).equals(t1))) {
return false;
}
}
return true;
}
}
| UTF-8 | Java | 885 | java | IsomorphicStrings.java | Java | []
| null | []
| package com.fastdata.algorithm.easy.hashtable;
import java.util.HashMap;
import java.util.Map;
public class IsomorphicStrings {
public boolean isIsomorphic(String s, String t) {
if (s.length() != t.length()) {
return false;
}
// set hashmap to assign keys and values to the string
Map<Character, Character> map = new HashMap<Character, Character>();
char[] sArr = new char[s.length()];
char[] tArr = new char[t.length()];
for (int i = 0; i < s.length(); i ++) {
sArr[i] = s.charAt(i);
tArr[i] = t.charAt(i);
}
for (int i = 0; i < sArr.length; i ++) {
char s1 = sArr[i];
char t1 = tArr[i];
if (!map.containsKey(s1) && !map.containsValue(t1)) {
map.put(s1, t1);
}
if ((!map.containsKey(s1) && map.containsValue(t1) || !map.get(s1).equals(t1))) {
return false;
}
}
return true;
}
}
| 885 | 0.580791 | 0.567232 | 35 | 23.285715 | 21.763103 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.542857 | false | false | 4 |
d6b93389864924c2bb3e164156bc2abbbfaf936d | 8,426,725,892,401 | ffbf4d160366b25501db42387b040c36a6e3f2db | /shiatzy-web-mobile/src/main/java/com/dookay/shiatzy/web/mobile/controller/HomeController.java | 2ca3c9507f8ece5436d5b219a71c0bc6fd47542b | []
| no_license | github2sean/coral-shop-shiatzy | https://github.com/github2sean/coral-shop-shiatzy | 367cdee058a6adc856f8a7264a9e12dfee83a583 | 559aee541c93af6bd9f02a9abceb29f2ccb5ba2b | refs/heads/master | 2021-01-01T04:36:17.708000 | 2017-07-14T08:56:21 | 2017-07-14T08:56:21 | 97,202,815 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dookay.shiatzy.web.mobile.controller;
import com.dookay.coral.adapter.sendmsg.sendmail.SimpleAliDMSendMail;
import com.dookay.coral.common.json.JsonUtils;
import com.dookay.coral.common.web.CookieUtil;
import com.dookay.coral.common.web.HttpContext;
import com.dookay.coral.common.web.JsonResult;
import com.dookay.coral.host.user.context.UserContext;
import com.dookay.coral.host.user.domain.AccountDomain;
import com.dookay.coral.host.user.service.IAccountService;
import com.dookay.coral.shop.content.domain.ContentCategoryDomain;
import com.dookay.coral.shop.content.domain.PushContentDomain;
import com.dookay.coral.shop.content.query.ContentCategoryQuery;
import com.dookay.coral.shop.content.query.PushContentQuery;
import com.dookay.coral.shop.content.service.IContentCategoryService;
import com.dookay.coral.shop.content.service.IPushContentService;
import com.dookay.coral.shop.customer.domain.CustomerAddressDomain;
import com.dookay.coral.shop.customer.domain.CustomerDomain;
import com.dookay.coral.shop.customer.service.ICustomerAddressService;
import com.dookay.coral.shop.customer.service.ICustomerService;
import com.dookay.coral.shop.goods.domain.GoodsCategoryDomain;
import com.dookay.coral.shop.goods.query.GoodsCategoryQuery;
import com.dookay.coral.shop.goods.service.IGoodsCategoryService;
import com.dookay.coral.shop.index.domain.IndexBlockDomain;
import com.dookay.coral.shop.index.domain.IndexBlockGroupDomain;
import com.dookay.coral.shop.index.query.IndexBlockGroupQuery;
import com.dookay.coral.shop.index.query.IndexBlockQuery;
import com.dookay.coral.shop.index.service.IIndexBlockGroupService;
import com.dookay.coral.shop.index.service.IIndexBlockService;
import com.dookay.coral.shop.order.domain.OrderDomain;
import com.dookay.coral.shop.promotion.domain.CouponDomain;
import com.dookay.coral.shop.promotion.query.CouponQuery;
import com.dookay.coral.shop.promotion.service.ICouponService;
import com.dookay.coral.shop.shipping.domain.ShippingCountryDomain;
import com.dookay.coral.shop.shipping.query.ShippingCountryQuery;
import com.dookay.coral.shop.shipping.service.IShippingCountryService;
import com.dookay.shiatzy.web.mobile.base.MobileBaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/4/25
*/
@Controller
@RequestMapping("home/")
public class HomeController extends MobileBaseController {
@Autowired
private IGoodsCategoryService goodsCategoryService;
@Autowired
private ICouponService couponService;
@Autowired
private IShippingCountryService shippingCountryService;
@Autowired
private IContentCategoryService contentCategoryService;
@Autowired
private IPushContentService pushContentService;
@Autowired
private IIndexBlockGroupService indexBlockGroupService;
@Autowired
private IIndexBlockService indexBlockService;
@Autowired
private CookieLocaleResolver resolver;
@Autowired
private SimpleAliDMSendMail simpleAliDMSendMail;
private static final String PUSH_HISTORY = "push_history";
private final static String SHIPPING_COUNTRY_ID="shippingCountryId";
private final static String LANGUAGE_HISTORY = "Language";
private final static int MAX_COOKIE_AGE = 24*60*60*7;
private static String ORDER = "order";
@RequestMapping(value = "index", method = RequestMethod.GET)
public ModelAndView index() throws MessagingException {
ModelAndView mv = new ModelAndView("home/index");
CouponQuery query = new CouponQuery();
query.setIndexShow(1);
CouponDomain couponDomain = couponService.getFirst(query);
mv.addObject("coupon",couponDomain);
//查询页尾内容
ContentCategoryQuery querys=new ContentCategoryQuery();
querys.setLevel(1);
List<ContentCategoryDomain> domainList=contentCategoryService.getList(querys);
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
session.setAttribute("domainList",domainList);
//查询推送内容
//先查询cookie中是否以查看过内容查看过无需再显示
String pushId = CookieUtil.getCookieValue(request,PUSH_HISTORY);
System.out.println("pushId:"+JsonUtils.toJSONString(pushId));
if(StringUtils.isBlank(pushId)){
PushContentQuery pushContentQuery = new PushContentQuery();
pushContentQuery.setIsValid(1);
pushContentQuery.setDesc(false);
pushContentQuery.setOrderBy("time");
List<PushContentDomain> pushContentList = pushContentService.getList(pushContentQuery);
PushContentDomain result = null;
Date nowTime = new Date();
for(PushContentDomain line: pushContentList){
Date time = line.getTime();
if(time.after(nowTime)){
result = line;
break;
}
}
if(result!=null){
System.out.println("pushContent:"+JsonUtils.toJSONString(result));
CookieUtil.setCookieValue(HttpContext.current().getResponse(),PUSH_HISTORY,result.getId()+"",MAX_COOKIE_AGE);
mv.addObject("pushContent",result);
}
}
//查询首页布局样式
IndexBlockGroupQuery groupQuery = new IndexBlockGroupQuery();
groupQuery.setIsValid(1);
groupQuery.setDesc(false);
groupQuery.setOrderBy("rank");
List<IndexBlockGroupDomain> groupList = indexBlockGroupService.getList(groupQuery);
IndexBlockQuery blockQuery = new IndexBlockQuery();
System.out.println("groupList:"+groupList+"\n size:"+groupList.size());
for(IndexBlockGroupDomain line:groupList){
blockQuery.setGroupId(line.getId());
blockQuery.setDesc(false);
blockQuery.setOrderBy("rank");
blockQuery.setIsValid(1);
List<IndexBlockDomain> indexBlockDomainList = indexBlockService.getList(blockQuery);
for(IndexBlockDomain row:indexBlockDomainList){
String image = row.getImage();
if(StringUtils.isNotBlank(image) && !image.contains("[{") && !image.contains("}]")){
image = "[{\"alt\":\"首页图\",\"file\":\""+image+"\"}]";
}
row.setImage(image);
}
System.out.println("indexBlockDomainList:"+indexBlockDomainList+"\n size:"+indexBlockDomainList.size());
line.setIndexBlockDomainList(indexBlockDomainList);
}
mv.addObject("groupList",groupList);
return mv;
}
@RequestMapping(value = "chooseShippingCountry", method = RequestMethod.POST)
@ResponseBody
public JsonResult chooseShippingCountry(HttpServletResponse response, Long shippingCountryId){
if(shippingCountryId==null){
return errorResult("选择为空");
}
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
session.setAttribute(SHIPPING_COUNTRY_ID,shippingCountryId);
CookieUtil.setCookieValueByKey(response,"shippingCountry",shippingCountryId+"",60*60*24*365);
String currentCode = "CNY";
Double fee = 0D;
if(shippingCountryId!=null){
ShippingCountryDomain shippingCountryDomain = shippingCountryService.get(shippingCountryId);
Double rate = shippingCountryDomain.getRate()!=null?shippingCountryDomain.getRate():1D;
//根据国家选择结算币种
int currentCodeType = shippingCountryDomain.getRateType();
if(currentCodeType==1){
currentCode = "USD";
}else if(currentCodeType==2){
currentCode = "EUR";
}
fee = shippingCountryDomain.getShippingCost()/rate;
}
OrderDomain orderDomain = (OrderDomain)session.getAttribute(ORDER);
if(orderDomain!=null){
orderDomain.setCurrentCode(currentCode);
orderDomain.setShipFee(new BigDecimal(fee).setScale(0,BigDecimal.ROUND_HALF_DOWN).doubleValue());
}
return successResult("选择成功");
}
@RequestMapping(value = "listShippingCountry", method = RequestMethod.GET)
public ModelAndView listShippingCountry(){
ModelAndView mv = new ModelAndView("home/listShippingCountry");
//查询出配送国家
ShippingCountryQuery query = new ShippingCountryQuery();
query.setDesc(false);
query.setOrderBy("rank");
List<ShippingCountryDomain> shippingCountryDomainList = shippingCountryService.getList(query);
mv.addObject("countryList",shippingCountryDomainList);
return mv;
}
@RequestMapping(value = "selectLanguage", method = RequestMethod.POST)
@ResponseBody
public JsonResult selectLanguage(String nowLanguage){
//判断当前语言环境
String cookieName = resolver.getCookieName();
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
if("zh_CN".equals(nowLanguage)){
CookieUtil.setCookieValueByKey(HttpContext.current().getResponse(),cookieName,"zh_CN",MAX_COOKIE_AGE);
}else if("en_US".equals(nowLanguage)){
CookieUtil.setCookieValueByKey(HttpContext.current().getResponse(),cookieName,"en_US",MAX_COOKIE_AGE);
}else{
return errorResult("参数有错");
}
return successResult("选择成功");
}
@RequestMapping(value = "queryCurrentRate", method = RequestMethod.POST)
@ResponseBody
public JsonResult queryCurrentRate(){
//判断当前语言环境
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
String countryId = CookieUtil.getCookieValueByKey(request,"shippingCountry");
Long id = StringUtils.isBlank(countryId)?1L:Long.parseLong(countryId);
if(id==null){
return errorResult("未选择国家");
}
//查询出配送国家
ShippingCountryDomain country = shippingCountryService.get(id);
if(country==null){
return errorResult("无此国家");
}
return successResult("查询成功",country);
}
}
| UTF-8 | Java | 11,172 | java | HomeController.java | Java | [
{
"context": "il.HashMap;\nimport java.util.List;\n\n/**\n * @author Luxor\n * @version v0.0.1\n * @since 2017/4/25\n */\n@Contr",
"end": 2991,
"score": 0.999701201915741,
"start": 2986,
"tag": "USERNAME",
"value": "Luxor"
}
]
| null | []
| package com.dookay.shiatzy.web.mobile.controller;
import com.dookay.coral.adapter.sendmsg.sendmail.SimpleAliDMSendMail;
import com.dookay.coral.common.json.JsonUtils;
import com.dookay.coral.common.web.CookieUtil;
import com.dookay.coral.common.web.HttpContext;
import com.dookay.coral.common.web.JsonResult;
import com.dookay.coral.host.user.context.UserContext;
import com.dookay.coral.host.user.domain.AccountDomain;
import com.dookay.coral.host.user.service.IAccountService;
import com.dookay.coral.shop.content.domain.ContentCategoryDomain;
import com.dookay.coral.shop.content.domain.PushContentDomain;
import com.dookay.coral.shop.content.query.ContentCategoryQuery;
import com.dookay.coral.shop.content.query.PushContentQuery;
import com.dookay.coral.shop.content.service.IContentCategoryService;
import com.dookay.coral.shop.content.service.IPushContentService;
import com.dookay.coral.shop.customer.domain.CustomerAddressDomain;
import com.dookay.coral.shop.customer.domain.CustomerDomain;
import com.dookay.coral.shop.customer.service.ICustomerAddressService;
import com.dookay.coral.shop.customer.service.ICustomerService;
import com.dookay.coral.shop.goods.domain.GoodsCategoryDomain;
import com.dookay.coral.shop.goods.query.GoodsCategoryQuery;
import com.dookay.coral.shop.goods.service.IGoodsCategoryService;
import com.dookay.coral.shop.index.domain.IndexBlockDomain;
import com.dookay.coral.shop.index.domain.IndexBlockGroupDomain;
import com.dookay.coral.shop.index.query.IndexBlockGroupQuery;
import com.dookay.coral.shop.index.query.IndexBlockQuery;
import com.dookay.coral.shop.index.service.IIndexBlockGroupService;
import com.dookay.coral.shop.index.service.IIndexBlockService;
import com.dookay.coral.shop.order.domain.OrderDomain;
import com.dookay.coral.shop.promotion.domain.CouponDomain;
import com.dookay.coral.shop.promotion.query.CouponQuery;
import com.dookay.coral.shop.promotion.service.ICouponService;
import com.dookay.coral.shop.shipping.domain.ShippingCountryDomain;
import com.dookay.coral.shop.shipping.query.ShippingCountryQuery;
import com.dookay.coral.shop.shipping.service.IShippingCountryService;
import com.dookay.shiatzy.web.mobile.base.MobileBaseController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/**
* @author Luxor
* @version v0.0.1
* @since 2017/4/25
*/
@Controller
@RequestMapping("home/")
public class HomeController extends MobileBaseController {
@Autowired
private IGoodsCategoryService goodsCategoryService;
@Autowired
private ICouponService couponService;
@Autowired
private IShippingCountryService shippingCountryService;
@Autowired
private IContentCategoryService contentCategoryService;
@Autowired
private IPushContentService pushContentService;
@Autowired
private IIndexBlockGroupService indexBlockGroupService;
@Autowired
private IIndexBlockService indexBlockService;
@Autowired
private CookieLocaleResolver resolver;
@Autowired
private SimpleAliDMSendMail simpleAliDMSendMail;
private static final String PUSH_HISTORY = "push_history";
private final static String SHIPPING_COUNTRY_ID="shippingCountryId";
private final static String LANGUAGE_HISTORY = "Language";
private final static int MAX_COOKIE_AGE = 24*60*60*7;
private static String ORDER = "order";
@RequestMapping(value = "index", method = RequestMethod.GET)
public ModelAndView index() throws MessagingException {
ModelAndView mv = new ModelAndView("home/index");
CouponQuery query = new CouponQuery();
query.setIndexShow(1);
CouponDomain couponDomain = couponService.getFirst(query);
mv.addObject("coupon",couponDomain);
//查询页尾内容
ContentCategoryQuery querys=new ContentCategoryQuery();
querys.setLevel(1);
List<ContentCategoryDomain> domainList=contentCategoryService.getList(querys);
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
session.setAttribute("domainList",domainList);
//查询推送内容
//先查询cookie中是否以查看过内容查看过无需再显示
String pushId = CookieUtil.getCookieValue(request,PUSH_HISTORY);
System.out.println("pushId:"+JsonUtils.toJSONString(pushId));
if(StringUtils.isBlank(pushId)){
PushContentQuery pushContentQuery = new PushContentQuery();
pushContentQuery.setIsValid(1);
pushContentQuery.setDesc(false);
pushContentQuery.setOrderBy("time");
List<PushContentDomain> pushContentList = pushContentService.getList(pushContentQuery);
PushContentDomain result = null;
Date nowTime = new Date();
for(PushContentDomain line: pushContentList){
Date time = line.getTime();
if(time.after(nowTime)){
result = line;
break;
}
}
if(result!=null){
System.out.println("pushContent:"+JsonUtils.toJSONString(result));
CookieUtil.setCookieValue(HttpContext.current().getResponse(),PUSH_HISTORY,result.getId()+"",MAX_COOKIE_AGE);
mv.addObject("pushContent",result);
}
}
//查询首页布局样式
IndexBlockGroupQuery groupQuery = new IndexBlockGroupQuery();
groupQuery.setIsValid(1);
groupQuery.setDesc(false);
groupQuery.setOrderBy("rank");
List<IndexBlockGroupDomain> groupList = indexBlockGroupService.getList(groupQuery);
IndexBlockQuery blockQuery = new IndexBlockQuery();
System.out.println("groupList:"+groupList+"\n size:"+groupList.size());
for(IndexBlockGroupDomain line:groupList){
blockQuery.setGroupId(line.getId());
blockQuery.setDesc(false);
blockQuery.setOrderBy("rank");
blockQuery.setIsValid(1);
List<IndexBlockDomain> indexBlockDomainList = indexBlockService.getList(blockQuery);
for(IndexBlockDomain row:indexBlockDomainList){
String image = row.getImage();
if(StringUtils.isNotBlank(image) && !image.contains("[{") && !image.contains("}]")){
image = "[{\"alt\":\"首页图\",\"file\":\""+image+"\"}]";
}
row.setImage(image);
}
System.out.println("indexBlockDomainList:"+indexBlockDomainList+"\n size:"+indexBlockDomainList.size());
line.setIndexBlockDomainList(indexBlockDomainList);
}
mv.addObject("groupList",groupList);
return mv;
}
@RequestMapping(value = "chooseShippingCountry", method = RequestMethod.POST)
@ResponseBody
public JsonResult chooseShippingCountry(HttpServletResponse response, Long shippingCountryId){
if(shippingCountryId==null){
return errorResult("选择为空");
}
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
session.setAttribute(SHIPPING_COUNTRY_ID,shippingCountryId);
CookieUtil.setCookieValueByKey(response,"shippingCountry",shippingCountryId+"",60*60*24*365);
String currentCode = "CNY";
Double fee = 0D;
if(shippingCountryId!=null){
ShippingCountryDomain shippingCountryDomain = shippingCountryService.get(shippingCountryId);
Double rate = shippingCountryDomain.getRate()!=null?shippingCountryDomain.getRate():1D;
//根据国家选择结算币种
int currentCodeType = shippingCountryDomain.getRateType();
if(currentCodeType==1){
currentCode = "USD";
}else if(currentCodeType==2){
currentCode = "EUR";
}
fee = shippingCountryDomain.getShippingCost()/rate;
}
OrderDomain orderDomain = (OrderDomain)session.getAttribute(ORDER);
if(orderDomain!=null){
orderDomain.setCurrentCode(currentCode);
orderDomain.setShipFee(new BigDecimal(fee).setScale(0,BigDecimal.ROUND_HALF_DOWN).doubleValue());
}
return successResult("选择成功");
}
@RequestMapping(value = "listShippingCountry", method = RequestMethod.GET)
public ModelAndView listShippingCountry(){
ModelAndView mv = new ModelAndView("home/listShippingCountry");
//查询出配送国家
ShippingCountryQuery query = new ShippingCountryQuery();
query.setDesc(false);
query.setOrderBy("rank");
List<ShippingCountryDomain> shippingCountryDomainList = shippingCountryService.getList(query);
mv.addObject("countryList",shippingCountryDomainList);
return mv;
}
@RequestMapping(value = "selectLanguage", method = RequestMethod.POST)
@ResponseBody
public JsonResult selectLanguage(String nowLanguage){
//判断当前语言环境
String cookieName = resolver.getCookieName();
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
if("zh_CN".equals(nowLanguage)){
CookieUtil.setCookieValueByKey(HttpContext.current().getResponse(),cookieName,"zh_CN",MAX_COOKIE_AGE);
}else if("en_US".equals(nowLanguage)){
CookieUtil.setCookieValueByKey(HttpContext.current().getResponse(),cookieName,"en_US",MAX_COOKIE_AGE);
}else{
return errorResult("参数有错");
}
return successResult("选择成功");
}
@RequestMapping(value = "queryCurrentRate", method = RequestMethod.POST)
@ResponseBody
public JsonResult queryCurrentRate(){
//判断当前语言环境
HttpServletRequest request = HttpContext.current().getRequest();
HttpSession session = request.getSession();
String countryId = CookieUtil.getCookieValueByKey(request,"shippingCountry");
Long id = StringUtils.isBlank(countryId)?1L:Long.parseLong(countryId);
if(id==null){
return errorResult("未选择国家");
}
//查询出配送国家
ShippingCountryDomain country = shippingCountryService.get(id);
if(country==null){
return errorResult("无此国家");
}
return successResult("查询成功",country);
}
}
| 11,172 | 0.711454 | 0.707892 | 246 | 43.504066 | 27.628157 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.731707 | false | false | 4 |
0b6172ff89a83ccb6f1e7ea95e0943aca317a70c | 6,528,350,296,783 | d089349e391aa47825c96e8284290f273162672c | /src/data/basis/Transaction.java | 527fe0ed6632a803fedcee3fa3879a015488de20 | []
| no_license | MWeigert/Vectron | https://github.com/MWeigert/Vectron | a3921cec7156bc4038727275ca009d3ad9a57780 | 02d71477b3ea9a1b57b344e16affa1e357e75b50 | refs/heads/master | 2020-04-24T14:54:31.310000 | 2014-10-24T15:31:32 | 2014-10-24T15:31:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Vectron Parser
* Parser to analyze Badge export files from the Vectroncommander
*/
package data.basis;
import java.util.HashMap;
import java.util.Map;
/**
* @author Mathias Weigert
* @version 0.75
*
* Class which stores all data from one Transaction
*/
public class Transaction {
private Map<Integer, String> transLog;
private Long badgeNumber;
private TransactionArticle[] transactionArticles;
public Transaction() {
transLog = new HashMap<Integer, String>();
badgeNumber = (long) 0;
}
/*
* Getter and Setter of the used data
*/
public Map<Integer, String> getTransLog() {
return transLog;
}
public void setTransLog(Map<Integer, String> transLog) {
this.transLog = transLog;
}
public String getTransLogLine(int number) {
return transLog.get(number);
}
public void putTransLogLine(int number, String line) {
transLog.put(number, line);
}
public Long getBadgeNumber() {
return badgeNumber;
}
public void setBadgeNumber(Long value) {
badgeNumber = value;
}
// public TransactionArticle[] getTransactionArticle(int pos) {
// return transactionArticles[pos];
// }
//
// public void setTransactionArticle(int pos, TransactionArticle[] transactionArticles) {
// this.transactionArticles[pos] = transactionArticles;
// }
public TransactionArticle[] getTransactionArticles() {
return transactionArticles;
}
public void setTransactionArticles(TransactionArticle[] transactionArticles) {
this.transactionArticles = transactionArticles;
}
}
| UTF-8 | Java | 1,518 | java | Transaction.java | Java | [
{
"context": "til.HashMap;\nimport java.util.Map;\n\n/**\n * @author Mathias Weigert\n * @version 0.75\n * \n * Class which stor",
"end": 193,
"score": 0.9997563362121582,
"start": 178,
"tag": "NAME",
"value": "Mathias Weigert"
}
]
| null | []
| /**
* Vectron Parser
* Parser to analyze Badge export files from the Vectroncommander
*/
package data.basis;
import java.util.HashMap;
import java.util.Map;
/**
* @author <NAME>
* @version 0.75
*
* Class which stores all data from one Transaction
*/
public class Transaction {
private Map<Integer, String> transLog;
private Long badgeNumber;
private TransactionArticle[] transactionArticles;
public Transaction() {
transLog = new HashMap<Integer, String>();
badgeNumber = (long) 0;
}
/*
* Getter and Setter of the used data
*/
public Map<Integer, String> getTransLog() {
return transLog;
}
public void setTransLog(Map<Integer, String> transLog) {
this.transLog = transLog;
}
public String getTransLogLine(int number) {
return transLog.get(number);
}
public void putTransLogLine(int number, String line) {
transLog.put(number, line);
}
public Long getBadgeNumber() {
return badgeNumber;
}
public void setBadgeNumber(Long value) {
badgeNumber = value;
}
// public TransactionArticle[] getTransactionArticle(int pos) {
// return transactionArticles[pos];
// }
//
// public void setTransactionArticle(int pos, TransactionArticle[] transactionArticles) {
// this.transactionArticles[pos] = transactionArticles;
// }
public TransactionArticle[] getTransactionArticles() {
return transactionArticles;
}
public void setTransactionArticles(TransactionArticle[] transactionArticles) {
this.transactionArticles = transactionArticles;
}
}
| 1,509 | 0.730567 | 0.727931 | 71 | 20.380281 | 22.634491 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.098592 | false | false | 4 |
75bbd1d35fa0342fc6f6ae2d1627aaeb576eb332 | 33,165,737,471,553 | dd0d9f6632d18c2219fdbbbcaee23c8e7238df00 | /src/cn/edu/sjzc/servlet/client/RegisterServlet.java | 37fafa21dd955b1aef3685eabb11904d3f6c0d0c | []
| no_license | ct446620064/bookstore | https://github.com/ct446620064/bookstore | de47232641fe94876aaca912f9e0b8e8ba68d3b9 | ea49cff1358f031efb0648489b19822ae153c515 | refs/heads/master | 2020-08-21T09:41:00.799000 | 2020-05-30T13:22:44 | 2020-05-30T13:22:44 | 216,133,155 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.edu.sjzc.servlet.client;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import cn.edu.sjzc.domin.User;
import cn.edu.sjzc.domin.UserFormBean;
import cn.edu.sjzc.service.UserService;
import cn.edu.sjzc.utils.ActiveCodeUtils;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserFormBean ufb = new UserFormBean();
Map<String, String[]> properties = request.getParameterMap();
try {
BeanUtils.populate(ufb, properties);
// 表单不合法
if (!ufb.isCorrect()){
Map<String, String> errors = ufb.getErrorsMap();
request.setAttribute("errors", errors);
request.setAttribute("formBean", ufb);
RequestDispatcher rd = request.getRequestDispatcher("/client/register.jsp");
rd.forward(request, response);
return;
}
// 表单合法
User user = new User();
BeanUtils.populate(user, properties);
// 设置激活码
user.setActiveCode(ActiveCodeUtils.createActiveCode());
// 使用service将user对象存入到数据库中
UserService us = new UserService();
us.register(user);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 转到注册成功页面
RequestDispatcher rd = request.getRequestDispatcher("/client/login.jsp");
rd.forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| UTF-8 | Java | 2,039 | java | RegisterServlet.java | Java | []
| null | []
| package cn.edu.sjzc.servlet.client;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import cn.edu.sjzc.domin.User;
import cn.edu.sjzc.domin.UserFormBean;
import cn.edu.sjzc.service.UserService;
import cn.edu.sjzc.utils.ActiveCodeUtils;
public class RegisterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserFormBean ufb = new UserFormBean();
Map<String, String[]> properties = request.getParameterMap();
try {
BeanUtils.populate(ufb, properties);
// 表单不合法
if (!ufb.isCorrect()){
Map<String, String> errors = ufb.getErrorsMap();
request.setAttribute("errors", errors);
request.setAttribute("formBean", ufb);
RequestDispatcher rd = request.getRequestDispatcher("/client/register.jsp");
rd.forward(request, response);
return;
}
// 表单合法
User user = new User();
BeanUtils.populate(user, properties);
// 设置激活码
user.setActiveCode(ActiveCodeUtils.createActiveCode());
// 使用service将user对象存入到数据库中
UserService us = new UserService();
us.register(user);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 转到注册成功页面
RequestDispatcher rd = request.getRequestDispatcher("/client/login.jsp");
rd.forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| 2,039 | 0.737697 | 0.737697 | 76 | 24.93421 | 22.030085 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.381579 | false | false | 4 |
2142a3abb3dad83ea2b3f0e58d3a22f408bb6682 | 14,783,277,447,542 | 84deed8d63883a60a6d31f5d0cf7be4d1791f0c1 | /android/app/src/main/java/com/example/jb/icarnfc/SelectStatus.java | 32f123f3380dc5b0aab1efe4a5eb22879a907562 | []
| no_license | Jbp83/ICarNFC2.0 | https://github.com/Jbp83/ICarNFC2.0 | 0993090a7396ccaa78b5f70a091d9ca90d3c82b2 | 7dc1e5b080d54871a6c7f2492cbcb704d88e374e | refs/heads/master | 2021-01-23T07:50:39.186000 | 2017-05-17T11:25:10 | 2017-05-17T11:25:10 | 86,456,247 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jb.icarnfc;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class SelectStatus extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_status);
Button particulier= (Button) findViewById(R.id.particulier);
particulier.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(getBaseContext(), SignUp.class);
startActivity(myIntent);
}
});
Button pro= (Button) findViewById(R.id.pro);
pro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(getBaseContext(), SignUpPro.class);
startActivity(myIntent);
}
});
}
}
| UTF-8 | Java | 1,139 | java | SelectStatus.java | Java | []
| null | []
| package com.example.jb.icarnfc;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
public class SelectStatus extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_status);
Button particulier= (Button) findViewById(R.id.particulier);
particulier.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(getBaseContext(), SignUp.class);
startActivity(myIntent);
}
});
Button pro= (Button) findViewById(R.id.pro);
pro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(getBaseContext(), SignUpPro.class);
startActivity(myIntent);
}
});
}
}
| 1,139 | 0.643547 | 0.642669 | 42 | 26.119047 | 24.45034 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452381 | false | false | 4 |
92749bfb0da0fb961510aa6f510eed1510f10dc2 | 16,054,587,769,372 | 5107d917c5b4395f9f1d1934b5001938b1eea3b8 | /src/java/com/ufpr/tads/web2/facade/CadastroFacade.java | e2b492790861a8d1c75f96b50e360e5b7aa83af0 | []
| no_license | wgiacomin/java-ee | https://github.com/wgiacomin/java-ee | 523d5e3c0d18df15a4e2f5441dddf3d8dbc037a4 | 99fe0eafe5847978b47c68446490bddd3b9b0909 | refs/heads/main | 2023-07-01T10:50:18.767000 | 2021-08-04T00:00:09 | 2021-08-04T00:00:09 | 367,941,971 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ufpr.tads.web2.facade;
import com.ufpr.tads.web2.beans.CadastroBean;
import com.ufpr.tads.web2.beans.LoginBean;
import com.ufpr.tads.web2.beans.PerfilBean;
import com.ufpr.tads.web2.dao.AtendimentoDAO;
import com.ufpr.tads.web2.dao.CadastroDAO;
import com.ufpr.tads.web2.dao.CidadeDAO;
import com.ufpr.tads.web2.dao.EstadoDAO;
import com.ufpr.tads.web2.dao.LoginDAO;
import com.ufpr.tads.web2.dao.PerfilDAO;
import com.ufpr.tads.web2.dao.utils.ConnectionFactory;
import com.ufpr.tads.web2.exceptions.BeanInvalidoException;
import com.ufpr.tads.web2.exceptions.CPFException;
import com.ufpr.tads.web2.exceptions.RegistroDuplicadoException;
import com.ufpr.tads.web2.exceptions.RegistroInexistenteException;
import com.ufpr.tads.web2.exceptions.DAOException;
import com.ufpr.tads.web2.exceptions.FacadeException;
import com.ufpr.tads.web2.exceptions.RegistroComUsoException;
import java.util.List;
public class CadastroFacade {
public static CadastroBean buscarBasico(CadastroBean cadastro) throws FacadeException, BeanInvalidoException, RegistroInexistenteException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bCad = new CadastroDAO(factory.getConnection());
cadastro = bCad.buscarBasico(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
return cadastro;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar cadastro " + cadastro.getId(), e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static CadastroBean buscar(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bCad = new CadastroDAO(factory.getConnection());
CidadeDAO cCad = new CidadeDAO(factory.getConnection());
EstadoDAO dCad = new EstadoDAO(factory.getConnection());
PerfilDAO eCad = new PerfilDAO(factory.getConnection());
cadastro = bCad.buscar(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
cadastro.setPerfil(eCad.buscar(cadastro.getPerfil()));
cadastro.setCidade(cCad.buscar(cadastro.getCidade()));
cadastro.getCidade().setEstado(dCad.buscar(cadastro.getCidade().getEstado()));
return cadastro;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar cadastro " + cadastro.getId(), e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static List<CadastroBean> buscarTodos() throws FacadeException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
List<CadastroBean> cadastros = bd.buscarTodos();
return cadastros;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar todos os cadastros: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static List<CadastroBean> buscarTodosPorPerfil(PerfilBean perfil) throws FacadeException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
List<CadastroBean> cadastros = bd.buscarTodosPorPerfil(perfil);
return cadastros;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar todos os cadastros por perfil: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void inserir(CadastroBean cadastro) throws FacadeException, BeanInvalidoException, RegistroDuplicadoException, CPFException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
LoginDAO lbd = new LoginDAO(factory.getConnection());
LoginBean login = (LoginBean) cadastro;
login = lbd.buscarLogin(login);
if (login != null) {
throw new RegistroDuplicadoException();
}
if ((bd.buscarCpf(cadastro) != 0) || !cadastro.isCPF()) {
throw new CPFException();
}
login = (LoginBean) cadastro;
lbd.inserir(login);
login = lbd.buscar(login);
cadastro.setId(login.getId());
bd.inserir(cadastro);
} catch (DAOException e) {
throw new FacadeException("Erro ao inserir cadastro: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void editar(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException, RegistroComUsoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
CadastroBean aux = bd.buscar(cadastro);
if (aux == null) {
throw new RegistroInexistenteException();
}
bd.editar(cadastro);
} catch (DAOException e) {
throw new FacadeException("Erro ao editar cadastro: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void remover(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException, RegistroComUsoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
cadastro = bd.buscar(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
LoginDAO lbd = new LoginDAO(factory.getConnection());
LoginBean login = (LoginBean) cadastro;
AtendimentoDAO dbd = new AtendimentoDAO(factory.getConnection());
int registros = dbd.buscarPorCliente(login);
if (registros > 0) {
throw new RegistroComUsoException(registros);
}
bd.remover(cadastro);
lbd.remover(login);
} catch (DAOException e) {
throw new FacadeException("Erro ao deletar cadastros: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
}
| UTF-8 | Java | 6,808 | java | CadastroFacade.java | Java | []
| null | []
| package com.ufpr.tads.web2.facade;
import com.ufpr.tads.web2.beans.CadastroBean;
import com.ufpr.tads.web2.beans.LoginBean;
import com.ufpr.tads.web2.beans.PerfilBean;
import com.ufpr.tads.web2.dao.AtendimentoDAO;
import com.ufpr.tads.web2.dao.CadastroDAO;
import com.ufpr.tads.web2.dao.CidadeDAO;
import com.ufpr.tads.web2.dao.EstadoDAO;
import com.ufpr.tads.web2.dao.LoginDAO;
import com.ufpr.tads.web2.dao.PerfilDAO;
import com.ufpr.tads.web2.dao.utils.ConnectionFactory;
import com.ufpr.tads.web2.exceptions.BeanInvalidoException;
import com.ufpr.tads.web2.exceptions.CPFException;
import com.ufpr.tads.web2.exceptions.RegistroDuplicadoException;
import com.ufpr.tads.web2.exceptions.RegistroInexistenteException;
import com.ufpr.tads.web2.exceptions.DAOException;
import com.ufpr.tads.web2.exceptions.FacadeException;
import com.ufpr.tads.web2.exceptions.RegistroComUsoException;
import java.util.List;
public class CadastroFacade {
public static CadastroBean buscarBasico(CadastroBean cadastro) throws FacadeException, BeanInvalidoException, RegistroInexistenteException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bCad = new CadastroDAO(factory.getConnection());
cadastro = bCad.buscarBasico(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
return cadastro;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar cadastro " + cadastro.getId(), e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static CadastroBean buscar(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bCad = new CadastroDAO(factory.getConnection());
CidadeDAO cCad = new CidadeDAO(factory.getConnection());
EstadoDAO dCad = new EstadoDAO(factory.getConnection());
PerfilDAO eCad = new PerfilDAO(factory.getConnection());
cadastro = bCad.buscar(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
cadastro.setPerfil(eCad.buscar(cadastro.getPerfil()));
cadastro.setCidade(cCad.buscar(cadastro.getCidade()));
cadastro.getCidade().setEstado(dCad.buscar(cadastro.getCidade().getEstado()));
return cadastro;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar cadastro " + cadastro.getId(), e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static List<CadastroBean> buscarTodos() throws FacadeException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
List<CadastroBean> cadastros = bd.buscarTodos();
return cadastros;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar todos os cadastros: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static List<CadastroBean> buscarTodosPorPerfil(PerfilBean perfil) throws FacadeException, BeanInvalidoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
List<CadastroBean> cadastros = bd.buscarTodosPorPerfil(perfil);
return cadastros;
} catch (DAOException e) {
throw new FacadeException("Erro ao buscar todos os cadastros por perfil: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void inserir(CadastroBean cadastro) throws FacadeException, BeanInvalidoException, RegistroDuplicadoException, CPFException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
LoginDAO lbd = new LoginDAO(factory.getConnection());
LoginBean login = (LoginBean) cadastro;
login = lbd.buscarLogin(login);
if (login != null) {
throw new RegistroDuplicadoException();
}
if ((bd.buscarCpf(cadastro) != 0) || !cadastro.isCPF()) {
throw new CPFException();
}
login = (LoginBean) cadastro;
lbd.inserir(login);
login = lbd.buscar(login);
cadastro.setId(login.getId());
bd.inserir(cadastro);
} catch (DAOException e) {
throw new FacadeException("Erro ao inserir cadastro: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void editar(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException, RegistroComUsoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
CadastroBean aux = bd.buscar(cadastro);
if (aux == null) {
throw new RegistroInexistenteException();
}
bd.editar(cadastro);
} catch (DAOException e) {
throw new FacadeException("Erro ao editar cadastro: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
public static void remover(CadastroBean cadastro) throws FacadeException, RegistroInexistenteException, BeanInvalidoException, RegistroComUsoException {
try (ConnectionFactory factory = new ConnectionFactory()) {
CadastroDAO bd = new CadastroDAO(factory.getConnection());
cadastro = bd.buscar(cadastro);
if (cadastro == null) {
throw new RegistroInexistenteException();
}
LoginDAO lbd = new LoginDAO(factory.getConnection());
LoginBean login = (LoginBean) cadastro;
AtendimentoDAO dbd = new AtendimentoDAO(factory.getConnection());
int registros = dbd.buscarPorCliente(login);
if (registros > 0) {
throw new RegistroComUsoException(registros);
}
bd.remover(cadastro);
lbd.remover(login);
} catch (DAOException e) {
throw new FacadeException("Erro ao deletar cadastros: ", e);
} catch (NullPointerException e) {
throw new BeanInvalidoException();
}
}
}
| 6,808 | 0.652761 | 0.649824 | 158 | 42.088608 | 32.479084 | 156 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.64557 | false | false | 4 |
03721ab887f883d0213d78a33da93f8746e30c20 | 16,552,803,972,933 | 93201dde26d4ef89338030ef58fa9ce5c40c89f7 | /TourGuide/microservice-rewards/src/main/java/com/tourguide/microservice/rewards/service/RewardsService.java | bf389d1610fe07db5e5d4da476221837b86fbe23 | []
| no_license | noemiemenu/JavaPathENProject8 | https://github.com/noemiemenu/JavaPathENProject8 | 5e2bbcbc2915ae71d3f06d9c8e5e85fddbf9cdf2 | ff4114080d3cdc74050c6a09140f30819e8e668f | refs/heads/master | 2023-07-28T20:30:32.748000 | 2021-09-15T13:42:16 | 2021-09-15T13:42:16 | 380,516,835 | 0 | 0 | null | true | 2021-09-15T13:04:48 | 2021-06-26T14:06:39 | 2021-09-12T16:13:14 | 2021-09-15T13:04:47 | 2,973 | 0 | 0 | 0 | Java | false | false | package com.tourguide.microservice.rewards.service;
import com.tourguide.feign_clients.UsersAPI;
import com.tourguide.library.user.User;
import com.tourguide.library.user.UserReward;
import gpsUtil.GpsUtil;
import gpsUtil.location.Attraction;
import gpsUtil.location.Location;
import gpsUtil.location.VisitedLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rewardCentral.RewardCentral;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The type Rewards service.
*/
@Service
public class RewardsService {
private static final double STATUTE_MILES_PER_NAUTICAL_MILE = 1.15077945;
/**
* @newFixedThreadPool fixe the number of Thread
*/
private ExecutorService executorService = Executors.newFixedThreadPool(64);
// proximity in miles
private final int defaultProximityBuffer = 10;
private int proximityBuffer = defaultProximityBuffer;
private final RewardCentral rewardsCentral;
private final List<gpsUtil.location.Attraction> attractions = new CopyOnWriteArrayList<gpsUtil.location.Attraction>();
@Autowired
private UsersAPI usersAPI;
/**
* Instantiates a new Rewards service.
*
* @param gpsUtil the gps util
* @param rewardCentral the reward central
*/
public RewardsService(GpsUtil gpsUtil, RewardCentral rewardCentral) {
this.rewardsCentral = rewardCentral;
attractions.addAll(gpsUtil.getAttractions());
}
/**
* Sets proximity buffer.
*
* @param proximityBuffer the proximity buffer
*/
public void setProximityBuffer(int proximityBuffer) {
this.proximityBuffer = proximityBuffer;
}
/**
* Calculate rewards list.
*
* @param userName the user name
* @return the list
*/
public List<UserReward> calculateRewards(String userName) {
User user = usersAPI.getUser(userName);
return calculateRewards(user);
}
/**
* Reset thread pool.
*/
public void resetThreadPool() {
executorService = Executors.newFixedThreadPool(64);
}
/**
* Calculate rewards list.
*
* @param user the user
* @return the rewards for this user calculateRewards use executorService
*/
public List<UserReward> calculateRewards(User user) {
List<VisitedLocation> userLocations = user.getVisitedLocations();
String userName = user.getUserName();
List<UserReward> newUserRewards = new ArrayList<>();
for (VisitedLocation visitedLocation : userLocations) {
for (Attraction attraction : attractions) {
if (user.getUserRewards().stream().noneMatch(reward -> reward.attraction.attractionName.equals(attraction.attractionName))) {
if (nearAttraction(visitedLocation, attraction)) {
UserReward userReward = new UserReward(visitedLocation, attraction, 0);
user.addUserReward(userReward);
newUserRewards.add(userReward);
}
}
}
}
for (UserReward userReward : newUserRewards) {
CompletableFuture
.supplyAsync(() -> getRewardPoints(userReward.attraction, user), executorService)
.thenAccept((points) -> {
userReward.setRewardPoints(points);
usersAPI.createUserReward(userName, userReward);
});
}
return user.getUserRewards();
}
/**
* Gets executor service.
*
* @return the executor service
*/
public ExecutorService getExecutorService() {
return executorService;
}
/**
* Is within attraction proximity boolean.
*
* @param attraction the attraction
* @param location the location
* @return the boolean
*/
public boolean isWithinAttractionProximity(Attraction attraction, Location location) {
int attractionProximityRange = 200;
return !(getDistance(attraction, location) > attractionProximityRange);
}
private boolean nearAttraction(VisitedLocation visitedLocation, Attraction attraction) {
return !(getDistance(attraction, visitedLocation.location) > proximityBuffer);
}
/**
* Gets reward points.
*
* @param attraction the attraction
* @param user the user
* @return the reward points
*/
public int getRewardPoints(Attraction attraction, User user) {
return rewardsCentral.getAttractionRewardPoints(attraction.attractionId, user.getUserId());
}
/**
* Gets distance.
*
* @param loc1 the loc 1
* @param loc2 the loc 2
* @return the distance
*/
public double getDistance(Location loc1, Location loc2) {
double latitude1 = Math.toRadians(loc1.latitude);
double longitude1 = Math.toRadians(loc1.longitude);
double latitude2 = Math.toRadians(loc2.latitude);
double longitude2 = Math.toRadians(loc2.longitude);
double angle = Math.acos(Math.sin(latitude1) * Math.sin(latitude2)
+ Math.cos(latitude1) * Math.cos(latitude2) * Math.cos(longitude1 - longitude2));
double nauticalMiles = 60 * Math.toDegrees(angle);
return STATUTE_MILES_PER_NAUTICAL_MILE * nauticalMiles;
}
}
| UTF-8 | Java | 5,609 | java | RewardsService.java | Java | [
{
"context": "isitedLocations();\n String userName = user.getUserName();\n List<UserReward> newUserRewards = new ",
"end": 2662,
"score": 0.7956606149673462,
"start": 2651,
"tag": "USERNAME",
"value": "getUserName"
}
]
| null | []
| package com.tourguide.microservice.rewards.service;
import com.tourguide.feign_clients.UsersAPI;
import com.tourguide.library.user.User;
import com.tourguide.library.user.UserReward;
import gpsUtil.GpsUtil;
import gpsUtil.location.Attraction;
import gpsUtil.location.Location;
import gpsUtil.location.VisitedLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import rewardCentral.RewardCentral;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* The type Rewards service.
*/
@Service
public class RewardsService {
private static final double STATUTE_MILES_PER_NAUTICAL_MILE = 1.15077945;
/**
* @newFixedThreadPool fixe the number of Thread
*/
private ExecutorService executorService = Executors.newFixedThreadPool(64);
// proximity in miles
private final int defaultProximityBuffer = 10;
private int proximityBuffer = defaultProximityBuffer;
private final RewardCentral rewardsCentral;
private final List<gpsUtil.location.Attraction> attractions = new CopyOnWriteArrayList<gpsUtil.location.Attraction>();
@Autowired
private UsersAPI usersAPI;
/**
* Instantiates a new Rewards service.
*
* @param gpsUtil the gps util
* @param rewardCentral the reward central
*/
public RewardsService(GpsUtil gpsUtil, RewardCentral rewardCentral) {
this.rewardsCentral = rewardCentral;
attractions.addAll(gpsUtil.getAttractions());
}
/**
* Sets proximity buffer.
*
* @param proximityBuffer the proximity buffer
*/
public void setProximityBuffer(int proximityBuffer) {
this.proximityBuffer = proximityBuffer;
}
/**
* Calculate rewards list.
*
* @param userName the user name
* @return the list
*/
public List<UserReward> calculateRewards(String userName) {
User user = usersAPI.getUser(userName);
return calculateRewards(user);
}
/**
* Reset thread pool.
*/
public void resetThreadPool() {
executorService = Executors.newFixedThreadPool(64);
}
/**
* Calculate rewards list.
*
* @param user the user
* @return the rewards for this user calculateRewards use executorService
*/
public List<UserReward> calculateRewards(User user) {
List<VisitedLocation> userLocations = user.getVisitedLocations();
String userName = user.getUserName();
List<UserReward> newUserRewards = new ArrayList<>();
for (VisitedLocation visitedLocation : userLocations) {
for (Attraction attraction : attractions) {
if (user.getUserRewards().stream().noneMatch(reward -> reward.attraction.attractionName.equals(attraction.attractionName))) {
if (nearAttraction(visitedLocation, attraction)) {
UserReward userReward = new UserReward(visitedLocation, attraction, 0);
user.addUserReward(userReward);
newUserRewards.add(userReward);
}
}
}
}
for (UserReward userReward : newUserRewards) {
CompletableFuture
.supplyAsync(() -> getRewardPoints(userReward.attraction, user), executorService)
.thenAccept((points) -> {
userReward.setRewardPoints(points);
usersAPI.createUserReward(userName, userReward);
});
}
return user.getUserRewards();
}
/**
* Gets executor service.
*
* @return the executor service
*/
public ExecutorService getExecutorService() {
return executorService;
}
/**
* Is within attraction proximity boolean.
*
* @param attraction the attraction
* @param location the location
* @return the boolean
*/
public boolean isWithinAttractionProximity(Attraction attraction, Location location) {
int attractionProximityRange = 200;
return !(getDistance(attraction, location) > attractionProximityRange);
}
private boolean nearAttraction(VisitedLocation visitedLocation, Attraction attraction) {
return !(getDistance(attraction, visitedLocation.location) > proximityBuffer);
}
/**
* Gets reward points.
*
* @param attraction the attraction
* @param user the user
* @return the reward points
*/
public int getRewardPoints(Attraction attraction, User user) {
return rewardsCentral.getAttractionRewardPoints(attraction.attractionId, user.getUserId());
}
/**
* Gets distance.
*
* @param loc1 the loc 1
* @param loc2 the loc 2
* @return the distance
*/
public double getDistance(Location loc1, Location loc2) {
double latitude1 = Math.toRadians(loc1.latitude);
double longitude1 = Math.toRadians(loc1.longitude);
double latitude2 = Math.toRadians(loc2.latitude);
double longitude2 = Math.toRadians(loc2.longitude);
double angle = Math.acos(Math.sin(latitude1) * Math.sin(latitude2)
+ Math.cos(latitude1) * Math.cos(latitude2) * Math.cos(longitude1 - longitude2));
double nauticalMiles = 60 * Math.toDegrees(angle);
return STATUTE_MILES_PER_NAUTICAL_MILE * nauticalMiles;
}
}
| 5,609 | 0.661972 | 0.654662 | 172 | 31.610466 | 28.492237 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.383721 | false | false | 4 |
16cea9cb9ca53fc38fd9e35d10de8a6bc83db37d | 1,675,037,264,682 | b97fca8c5f3e6e49f3952c3cc985a6befd640142 | /src/Test.java | 2f8f4d5a3ce5251b7a3912791dcfd8d7be41a3bc | []
| no_license | Alarnti/TutorHibernate | https://github.com/Alarnti/TutorHibernate | bbd61f57a6b3249d18be00e67a302bd4b7824c27 | 41ff2c51c47ba139503604384b36d81ac9340b5a | refs/heads/master | 2015-07-14T16:25:09 | 2014-11-26T22:18:34 | 2014-11-26T22:18:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import Service.TutorService;
import Service.*;
import domain.City;
import domain.Tutor;
import org.hibernate.Session;
import util.HibernateUtil;
import java.util.ArrayList;
public class Test {
public static final TutorService tutorService = new TutorService();
public static final CityService cityService = new CityService();
public static void main(String[] args) {
try{
//testConnection();
/*City city = new City();
Tutor tutor = new Tutor("Adam","Hollow",2.4F,city);
city.setCityName("Kazan");
ArrayList<Tutor> tutors = new ArrayList<Tutor>();
tutors.add(tutor);
city.setTutors(tutors);
tutor.setCity(city);
cityService.addCity(city);
tutorService.addTutor(tutor);
city= new City();
city.setCityName("Moscow");
tutor = new Tutor("Ben", "Hoffman",3.4F,city);
tutors.add(tutor);
city.setTutors(tutors);
cityService.addCity(city);
tutorService.addTutor(tutor);*/
System.out.println(tutorService.getAllTutors() + "\n" + cityService.getAllCities());
} catch(Exception e) {
e.printStackTrace();
} finally {
if (!HibernateUtil.getSessionFactory().isClosed())
HibernateUtil.getSessionFactory().close();
}
}
public static void testConnection(){
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
} catch (Exception e) {
System.err.println("Error in testConnection(): " + e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
}
| UTF-8 | Java | 1,824 | java | Test.java | Java | [
{
"context": " new City();\n Tutor tutor = new Tutor(\"Adam\",\"Hollow\",2.4F,city);\n\n city.setCityNa",
"end": 507,
"score": 0.9998481273651123,
"start": 503,
"tag": "NAME",
"value": "Adam"
},
{
"context": "ty();\n Tutor tutor = new Tutor(\"Adam\",\"Hollow\",2.4F,city);\n\n city.setCityName(\"Kazan",
"end": 516,
"score": 0.9997985363006592,
"start": 510,
"tag": "NAME",
"value": "Hollow"
},
{
"context": "ityName(\"Moscow\");\n tutor = new Tutor(\"Ben\", \"Hoffman\",3.4F,city);\n tutors.add(tu",
"end": 919,
"score": 0.9998476505279541,
"start": 916,
"tag": "NAME",
"value": "Ben"
},
{
"context": "(\"Moscow\");\n tutor = new Tutor(\"Ben\", \"Hoffman\",3.4F,city);\n tutors.add(tutor);\n ",
"end": 930,
"score": 0.9997965693473816,
"start": 923,
"tag": "NAME",
"value": "Hoffman"
}
]
| null | []
| import Service.TutorService;
import Service.*;
import domain.City;
import domain.Tutor;
import org.hibernate.Session;
import util.HibernateUtil;
import java.util.ArrayList;
public class Test {
public static final TutorService tutorService = new TutorService();
public static final CityService cityService = new CityService();
public static void main(String[] args) {
try{
//testConnection();
/*City city = new City();
Tutor tutor = new Tutor("Adam","Hollow",2.4F,city);
city.setCityName("Kazan");
ArrayList<Tutor> tutors = new ArrayList<Tutor>();
tutors.add(tutor);
city.setTutors(tutors);
tutor.setCity(city);
cityService.addCity(city);
tutorService.addTutor(tutor);
city= new City();
city.setCityName("Moscow");
tutor = new Tutor("Ben", "Hoffman",3.4F,city);
tutors.add(tutor);
city.setTutors(tutors);
cityService.addCity(city);
tutorService.addTutor(tutor);*/
System.out.println(tutorService.getAllTutors() + "\n" + cityService.getAllCities());
} catch(Exception e) {
e.printStackTrace();
} finally {
if (!HibernateUtil.getSessionFactory().isClosed())
HibernateUtil.getSessionFactory().close();
}
}
public static void testConnection(){
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
} catch (Exception e) {
System.err.println("Error in testConnection(): " + e.getMessage());
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
}
| 1,824 | 0.571272 | 0.569079 | 58 | 30.448277 | 22.560396 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.672414 | false | false | 4 |
24ea1cba7d7521900732c5bdee32f7bd87b060af | 26,955,214,769,067 | 5b72cc90fdcd6f793d5102a54dcafc5c87a0fc26 | /GroceryBackground.java | 7598b4bd8038e2847edb9f750109c780fe40a0b2 | []
| no_license | zulhafizazmi/Assignment-1 | https://github.com/zulhafizazmi/Assignment-1 | 8fbcc3a63a7151b49d97b78f8deffa331a1618da | d2cf742de5a992085a34e81d48c2263fe5e4ad63 | refs/heads/main | 2023-06-18T06:13:16.365000 | 2021-07-18T02:51:47 | 2021-07-18T02:51:47 | 372,941,607 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Assignment1;
import java.util.Scanner;
public class GroceryBackground { //superclass
protected String name;
protected String location;
protected String contact;
GroceryBackground() { //cunstructor no argument
this.name = "Watsun";
this.location = "Tumpat";
this.contact = "097193642";
print();
}
public void print() {
System.out.println("Name : " + this.name);
System.out.println("Location : " + this.location);
System.out.println("Contact: " + this.contact);
}
}
| UTF-8 | Java | 542 | java | GroceryBackground.java | Java | [
{
"context": ") { //cunstructor no argument\r\n\t\t\r\n\t\tthis.name = \"Watsun\";\r\n\t\tthis.location = \"Tumpat\";\r\n\t\tthis.contact = ",
"end": 263,
"score": 0.999810516834259,
"start": 257,
"tag": "NAME",
"value": "Watsun"
}
]
| null | []
| package Assignment1;
import java.util.Scanner;
public class GroceryBackground { //superclass
protected String name;
protected String location;
protected String contact;
GroceryBackground() { //cunstructor no argument
this.name = "Watsun";
this.location = "Tumpat";
this.contact = "097193642";
print();
}
public void print() {
System.out.println("Name : " + this.name);
System.out.println("Location : " + this.location);
System.out.println("Contact: " + this.contact);
}
}
| 542 | 0.643911 | 0.625461 | 27 | 17.925926 | 17.971018 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.407407 | false | false | 4 |
64b506bc819ffebd646baa987817df7d1958fc46 | 30,193,620,106,925 | 8236c0cdf2173db2c005d6fe18b16c3a2a737cb0 | /app/src/main/java/com/coolopool/coolopool/Fragments/RestaurantsFragment.java | d534ba939723b9413622aaa6a04a2ce4a43dcbb3 | []
| no_license | Sjsingh101/CooloPoolAndroid | https://github.com/Sjsingh101/CooloPoolAndroid | 146bb4ef59707f720e95bf21fc1dd988c0475678 | 8e83b9f12241af48e4e34687b9a4b790cd8f7770 | refs/heads/master | 2020-05-25T05:59:13.064000 | 2019-08-01T10:32:21 | 2019-08-01T10:32:21 | 187,657,304 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.coolopool.coolopool.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.coolopool.coolopool.R;
/**
* A simple {@link Fragment} subclass.
*/
public class RestaurantsFragment extends Fragment {
View v;
public RestaurantsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_resturants, container, false);
return v;
}
public View getView() {
return v;
}
}
| UTF-8 | Java | 800 | java | RestaurantsFragment.java | Java | []
| null | []
| package com.coolopool.coolopool.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.coolopool.coolopool.R;
/**
* A simple {@link Fragment} subclass.
*/
public class RestaurantsFragment extends Fragment {
View v;
public RestaurantsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_resturants, container, false);
return v;
}
public View getView() {
return v;
}
}
| 800 | 0.675 | 0.67375 | 41 | 18.512196 | 21.833206 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.365854 | false | false | 4 |
47903a90973f877f1433486bd005421949e2e927 | 6,966,436,974,337 | 57ba6af9a41ab677d2e82aeef8c572fead0456f5 | /cerealista2.2/src/java/classe/entidade/Usuario.java | 0b3a3e9e57b54c447ce10a86d95a2efd12273f19 | []
| no_license | edersonjasper/Cerealista | https://github.com/edersonjasper/Cerealista | 6c6962aa0fbc8cd4f30c1ba552cb8d4fdff84dfa | 618cddb803a1dab58ea21262162f2635da92406e | refs/heads/master | 2021-11-30T05:55:58.263000 | 2014-06-01T14:33:15 | 2014-06-01T14:33:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package classe.entidade;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author Eder
*/
@Entity
//define que ira somente inserir e atualizar o que for modificado, e não todos os registros mesmo que não tenha modificado
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@SequenceGenerator(name="seq",sequenceName="usuario_usu_codigo_seq",allocationSize=1)
@Table(name = "usuario")
public class Usuario implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")
@Column(name = "usu_codigo", nullable = false)
private Integer usuCodigo;
@Basic(optional = false)
@Column(name = "usu_usuario", nullable = false,length=20)
private String usuUsuario;
@Basic(optional = false)
@Column(name = "usu_senha", nullable = false,length=20)
private String usuSenha;
@Basic(optional = false)
@Column(name = "usu_nome", nullable = false,length=40)
private String usuNome;
@Basic(optional = false)
@Column(name = "usu_status", nullable = false,length=1)
private String usuStatus;
// @ManyToMany
// @JoinTable(name = "acesso_usuario",
// joinColumns = {@JoinColumn(name = "usu_codigo")},
// inverseJoinColumns = {@JoinColumn(name = "ace_codigo")})
// private Set<Acesso> aceCodigo;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Auditoria> auditorias;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Despesa> despesas;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Ordem> ordens;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Pessoa> pessoas;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<PagamentoFuncionario> pagamentoFuncionarios;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Caixa> caixa;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Quebra> quebras;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<PagamentoOrdem> pagamentoOrdens;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Venda> vendas;
public String getUsuStatus() {
return usuStatus;
}
public void setUsuStatus(String usuStatus) {
this.usuStatus = usuStatus;
}
public List<Venda> getVendas() {
return vendas;
}
public void setVendas(List<Venda> vendas) {
this.vendas = vendas;
}
public List<PagamentoOrdem> getPagamentoOrdens() {
return pagamentoOrdens;
}
public void setPagamentoOrdens(List<PagamentoOrdem> pagamentoOrdens) {
this.pagamentoOrdens = pagamentoOrdens;
}
public List<Quebra> getQuebras() {
return quebras;
}
public void setQuebras(List<Quebra> quebras) {
this.quebras = quebras;
}
public List<Caixa> getCaixa() {
return caixa;
}
public void setCaixa(List<Caixa> caixa) {
this.caixa = caixa;
}
public List<PagamentoFuncionario> getPagamentoFuncionarios() {
return pagamentoFuncionarios;
}
public void setPagamentoFuncionarios(List<PagamentoFuncionario> pagamentoFuncionarios) {
this.pagamentoFuncionarios = pagamentoFuncionarios;
}
public List<Pessoa> getPessoas() {
return pessoas;
}
public void setPessoas(List<Pessoa> pessoas) {
this.pessoas = pessoas;
}
public List<Ordem> getOrdens() {
return ordens;
}
public void setOrdens(List<Ordem> ordens) {
this.ordens = ordens;
}
public List<Despesa> getDespesas() {
return despesas;
}
public void setDespesas(List<Despesa> despesas) {
this.despesas = despesas;
}
public List<Auditoria> getAuditorias() {
return auditorias;
}
public void setAuditorias(List<Auditoria> auditorias) {
this.auditorias = auditorias;
}
public Integer getUsuCodigo() {
return usuCodigo;
}
public void setUsuCodigo(Integer usuCodigo) {
this.usuCodigo = usuCodigo;
}
public String getUsuNome() {
return usuNome;
}
public void setUsuNome(String usuNome) {
this.usuNome = usuNome;
}
public String getUsuSenha() {
return usuSenha;
}
public void setUsuSenha(String usuSenha) {
this.usuSenha = usuSenha;
}
public String getUsuUsuario() {
return usuUsuario;
}
public void setUsuUsuario(String usuUsuario) {
this.usuUsuario = usuUsuario;
}
public Boolean isValidPassword(String password) {
return password.equals(usuSenha);
}
public Usuario() {
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Usuario other = (Usuario) obj;
if (this.usuCodigo != other.usuCodigo && (this.usuCodigo == null || !this.usuCodigo.equals(other.usuCodigo))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (this.usuCodigo != null ? this.usuCodigo.hashCode() : 0);
return hash;
}
@Override
public String toString(){
return usuNome;
}
}
| UTF-8 | Java | 5,920 | java | Usuario.java | Java | [
{
"context": "import javax.persistence.Table;\n\n/**\n *\n * @author Eder\n */\n@Entity\n//define que ira somente inserir e at",
"end": 558,
"score": 0.998924970626831,
"start": 554,
"tag": "USERNAME",
"value": "Eder"
}
]
| null | []
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package classe.entidade;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author Eder
*/
@Entity
//define que ira somente inserir e atualizar o que for modificado, e não todos os registros mesmo que não tenha modificado
@org.hibernate.annotations.Entity(dynamicInsert = true, dynamicUpdate = true)
@SequenceGenerator(name="seq",sequenceName="usuario_usu_codigo_seq",allocationSize=1)
@Table(name = "usuario")
public class Usuario implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seq")
@Column(name = "usu_codigo", nullable = false)
private Integer usuCodigo;
@Basic(optional = false)
@Column(name = "usu_usuario", nullable = false,length=20)
private String usuUsuario;
@Basic(optional = false)
@Column(name = "usu_senha", nullable = false,length=20)
private String usuSenha;
@Basic(optional = false)
@Column(name = "usu_nome", nullable = false,length=40)
private String usuNome;
@Basic(optional = false)
@Column(name = "usu_status", nullable = false,length=1)
private String usuStatus;
// @ManyToMany
// @JoinTable(name = "acesso_usuario",
// joinColumns = {@JoinColumn(name = "usu_codigo")},
// inverseJoinColumns = {@JoinColumn(name = "ace_codigo")})
// private Set<Acesso> aceCodigo;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Auditoria> auditorias;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Despesa> despesas;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Ordem> ordens;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Pessoa> pessoas;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<PagamentoFuncionario> pagamentoFuncionarios;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Caixa> caixa;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Quebra> quebras;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<PagamentoOrdem> pagamentoOrdens;
@OneToMany(mappedBy = "usuCodigo", fetch = FetchType.LAZY)
private List<Venda> vendas;
public String getUsuStatus() {
return usuStatus;
}
public void setUsuStatus(String usuStatus) {
this.usuStatus = usuStatus;
}
public List<Venda> getVendas() {
return vendas;
}
public void setVendas(List<Venda> vendas) {
this.vendas = vendas;
}
public List<PagamentoOrdem> getPagamentoOrdens() {
return pagamentoOrdens;
}
public void setPagamentoOrdens(List<PagamentoOrdem> pagamentoOrdens) {
this.pagamentoOrdens = pagamentoOrdens;
}
public List<Quebra> getQuebras() {
return quebras;
}
public void setQuebras(List<Quebra> quebras) {
this.quebras = quebras;
}
public List<Caixa> getCaixa() {
return caixa;
}
public void setCaixa(List<Caixa> caixa) {
this.caixa = caixa;
}
public List<PagamentoFuncionario> getPagamentoFuncionarios() {
return pagamentoFuncionarios;
}
public void setPagamentoFuncionarios(List<PagamentoFuncionario> pagamentoFuncionarios) {
this.pagamentoFuncionarios = pagamentoFuncionarios;
}
public List<Pessoa> getPessoas() {
return pessoas;
}
public void setPessoas(List<Pessoa> pessoas) {
this.pessoas = pessoas;
}
public List<Ordem> getOrdens() {
return ordens;
}
public void setOrdens(List<Ordem> ordens) {
this.ordens = ordens;
}
public List<Despesa> getDespesas() {
return despesas;
}
public void setDespesas(List<Despesa> despesas) {
this.despesas = despesas;
}
public List<Auditoria> getAuditorias() {
return auditorias;
}
public void setAuditorias(List<Auditoria> auditorias) {
this.auditorias = auditorias;
}
public Integer getUsuCodigo() {
return usuCodigo;
}
public void setUsuCodigo(Integer usuCodigo) {
this.usuCodigo = usuCodigo;
}
public String getUsuNome() {
return usuNome;
}
public void setUsuNome(String usuNome) {
this.usuNome = usuNome;
}
public String getUsuSenha() {
return usuSenha;
}
public void setUsuSenha(String usuSenha) {
this.usuSenha = usuSenha;
}
public String getUsuUsuario() {
return usuUsuario;
}
public void setUsuUsuario(String usuUsuario) {
this.usuUsuario = usuUsuario;
}
public Boolean isValidPassword(String password) {
return password.equals(usuSenha);
}
public Usuario() {
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Usuario other = (Usuario) obj;
if (this.usuCodigo != other.usuCodigo && (this.usuCodigo == null || !this.usuCodigo.equals(other.usuCodigo))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (this.usuCodigo != null ? this.usuCodigo.hashCode() : 0);
return hash;
}
@Override
public String toString(){
return usuNome;
}
}
| 5,920 | 0.658837 | 0.65681 | 215 | 26.525581 | 23.402605 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44186 | false | false | 4 |
7aa7ed5ac20f68e94df7965cf328cc96c2082db3 | 21,552,145,907,899 | 086b180e4e66bdcda5be5b57d3495701732b35bf | /BrightEdge_onsite/RestaurantApp/src/Crawler/Parser.java | 3bb6da38a67d8b9af0cb6710266ea0c745075c16 | []
| no_license | Tianzhang0809/Crawler_projects | https://github.com/Tianzhang0809/Crawler_projects | 76052a760f8b470411075b2d73cb8cea9131a6d4 | 70de14112cc9f6fbf5c3f411162280704a483444 | refs/heads/master | 2016-09-06T05:47:31.142000 | 2014-10-05T00:10:36 | 2014-10-05T00:10:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Crawler;
import java.io.IOException;
import java.sql.SQLException;
public interface Parser {
public String getUrl();
public void setUrl(String url);
public void process() throws IOException, SQLException;
}
| UTF-8 | Java | 223 | java | Parser.java | Java | []
| null | []
| package Crawler;
import java.io.IOException;
import java.sql.SQLException;
public interface Parser {
public String getUrl();
public void setUrl(String url);
public void process() throws IOException, SQLException;
}
| 223 | 0.7713 | 0.7713 | 13 | 16.153847 | 17.087315 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.769231 | false | false | 4 |
26f4b556ff3edfa9288cc91a9d16d2f3d8715d15 | 21,552,145,906,357 | 18762b7d22b0af8dbe09abe09518c768622d5549 | /TP1_Modele/TP1_Modele/src/main/java/modele/Dictionnaire.java | e296506cf7d996b884d0a1e73b52b155d7918229 | []
| no_license | corentinngako/CorentinTP2 | https://github.com/corentinngako/CorentinTP2 | 8ad311290e0f0c6251e628de70abf6a413b1f471 | 7eb2a4d4c70c3bc1ba48204555dd432c1167dae3 | refs/heads/master | 2020-12-13T14:10:20.730000 | 2020-01-17T00:57:46 | 2020-01-17T00:57:46 | 234,441,415 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package modele;
import java.text.Collator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* TP1-CORENTIN ET HUGO
*
*/
public class Dictionnaire {
private static Dictionnaire instance = null;
private Properties properties = new Properties();
private static Collator collator = Collator.getInstance(Locale.CANADA);
private Map<String, Mot> dictionary = new TreeMap<String, Mot>(collator);
/**
* Sert a obtenire la map du dictionnaire
*
* @return la map du dictionnaire
*/
public Map<String, Mot> getMapDico() {
return dictionary;
}
/**
* Sert a obtenir l'instance du dictionnaire
*
* @return l'instance du dictionnaire
*/
public static Dictionnaire getInstance() {
// TODO Auto-generated method stub
return null;
}
}
| UTF-8 | Java | 817 | java | Dictionnaire.java | Java | []
| null | []
| package modele;
import java.text.Collator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* TP1-CORENTIN ET HUGO
*
*/
public class Dictionnaire {
private static Dictionnaire instance = null;
private Properties properties = new Properties();
private static Collator collator = Collator.getInstance(Locale.CANADA);
private Map<String, Mot> dictionary = new TreeMap<String, Mot>(collator);
/**
* Sert a obtenire la map du dictionnaire
*
* @return la map du dictionnaire
*/
public Map<String, Mot> getMapDico() {
return dictionary;
}
/**
* Sert a obtenir l'instance du dictionnaire
*
* @return l'instance du dictionnaire
*/
public static Dictionnaire getInstance() {
// TODO Auto-generated method stub
return null;
}
}
| 817 | 0.718482 | 0.717258 | 39 | 19.948717 | 20.272438 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 4 |
0da8ab218845c1eb40d3ffb697c625d5c07737a6 | 4,741,643,904,573 | 2f7e0bd89124b91ed5493a5bc4146b67a0b7efad | /FactoryMS/src/fms/HR/servlet/AddPerfromanceTrackingServlet.java | 916666befa6a4580f026788c135d05ff5d92f4ee | []
| no_license | AkeelMNM/ITProject | https://github.com/AkeelMNM/ITProject | 4dd7206da8c9100e9519ec28e3a4bf78cefd9caf | 5ba3b04b5951dd46851eef83267b686f90741f73 | refs/heads/master | 2023-01-07T19:29:51.007000 | 2021-05-25T17:29:10 | 2021-05-25T17:29:10 | 288,714,876 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fms.HR.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fms.model.PerformanceTracking;
import fms.HR.service.EmployeeService;
import fms.HR.service.EmployeeServiceImpt;
import fms.HR.service.PerformanceTrackingService;
import fms.HR.service.PerformanceTrackingServiceImpt;
/**
* Servlet implementation class AddPerfromanceTrackingServlet
*/
@WebServlet("/AddPerfromanceTrackingServlet")
public class AddPerfromanceTrackingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddPerfromanceTrackingServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("Get Employees".equals(request.getParameter("getJob"))) {
request.setAttribute("jName", request.getParameter("job"));
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Interfaces/HR/HR_Add_Performance_Tracking.jsp");
dispatcher.forward(request, response);
}
else if("Submit".equals(request.getParameter("add"))) {
String name = request.getParameter("name");
EmployeeService emp = new EmployeeServiceImpt();
String id = emp.getEmployeeID(name);
PerformanceTracking pr = new PerformanceTracking();
pr.setEmpID(id);
pr.setJobTitle(request.getParameter("job"));
pr.setEmpName(name);
pr.setMonth(request.getParameter("month"));
pr.setDate(request.getParameter("date"));
pr.setTimeIn(request.getParameter("timein"));
pr.setLunchIn(request.getParameter("lunchin"));
pr.setLunchOut(request.getParameter("lunchout"));
pr.setTimeOut(request.getParameter("timeout"));
pr.setOvetTime(request.getParameter("overtime"));
pr.setPerformace(request.getParameter("performance"));
pr.setDescription(request.getParameter("description"));
PerformanceTrackingService ptservice = new PerformanceTrackingServiceImpt();
ptservice.addPerformanceTracking(pr);
request.setAttribute("pr", pr);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Interfaces/HR/HR_Add_Performance_Tracking.jsp");
dispatcher.forward(request, response);
}
}
}
| UTF-8 | Java | 2,982 | java | AddPerfromanceTrackingServlet.java | Java | []
| null | []
| package fms.HR.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fms.model.PerformanceTracking;
import fms.HR.service.EmployeeService;
import fms.HR.service.EmployeeServiceImpt;
import fms.HR.service.PerformanceTrackingService;
import fms.HR.service.PerformanceTrackingServiceImpt;
/**
* Servlet implementation class AddPerfromanceTrackingServlet
*/
@WebServlet("/AddPerfromanceTrackingServlet")
public class AddPerfromanceTrackingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddPerfromanceTrackingServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("Get Employees".equals(request.getParameter("getJob"))) {
request.setAttribute("jName", request.getParameter("job"));
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Interfaces/HR/HR_Add_Performance_Tracking.jsp");
dispatcher.forward(request, response);
}
else if("Submit".equals(request.getParameter("add"))) {
String name = request.getParameter("name");
EmployeeService emp = new EmployeeServiceImpt();
String id = emp.getEmployeeID(name);
PerformanceTracking pr = new PerformanceTracking();
pr.setEmpID(id);
pr.setJobTitle(request.getParameter("job"));
pr.setEmpName(name);
pr.setMonth(request.getParameter("month"));
pr.setDate(request.getParameter("date"));
pr.setTimeIn(request.getParameter("timein"));
pr.setLunchIn(request.getParameter("lunchin"));
pr.setLunchOut(request.getParameter("lunchout"));
pr.setTimeOut(request.getParameter("timeout"));
pr.setOvetTime(request.getParameter("overtime"));
pr.setPerformace(request.getParameter("performance"));
pr.setDescription(request.getParameter("description"));
PerformanceTrackingService ptservice = new PerformanceTrackingServiceImpt();
ptservice.addPerformanceTracking(pr);
request.setAttribute("pr", pr);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Interfaces/HR/HR_Add_Performance_Tracking.jsp");
dispatcher.forward(request, response);
}
}
}
| 2,982 | 0.759893 | 0.759557 | 87 | 33.275864 | 31.020456 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.