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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
72bf2531c37b9f0d3422160efe146980da8fac5e | 13,125,420,067,106 | 5dfadc8ad305030c31c657490d7aa847aaf81744 | /timing-scheduler/src/main/java/com/timing/job/admin/core/thread/JobFailMonitorHelper.java | dc1bf35eab2ce8f4bf21b9b417a7897ed6bdc507 | [] | no_license | winstonelei/timing | https://github.com/winstonelei/timing | b4df7eebf0c50e1cac1684926f1f2fcad6da79ef | 4bad524c0c0d21921bb790ccbbd9e7ae6bacb8a5 | refs/heads/master | 2021-01-20T03:56:36.193000 | 2018-05-11T08:08:57 | 2018-05-11T08:08:57 | 101,376,544 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.timing.job.admin.core.thread;
import com.timing.executor.core.biz.model.ReturnT;
import com.timing.job.admin.core.model.TimingJobGroup;
import com.timing.job.admin.core.model.TimingJobInfo;
import com.timing.job.admin.core.model.TimingJobLog;
import com.timing.job.admin.core.schedule.TimingJobScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Created by winstone on 2017/8/23.
*/
@Deprecated
public class JobFailMonitorHelper {
private static Logger logger = LoggerFactory.getLogger(JobFailMonitorHelper.class);
private static JobFailMonitorHelper instance = new JobFailMonitorHelper();
public static JobFailMonitorHelper getInstance(){
return instance;
}
private LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(0xfff8);
private Thread monitorThread;
private boolean toStop = false;
public void start(){
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!toStop){
try {
logger.info("monitor beat");
Integer jobLogId = JobFailMonitorHelper.instance.queue.take();
if(jobLogId!=null && jobLogId>0){
TimingJobLog log = TimingJobScheduler.timingJobLogDao.load(jobLogId);
if(log!=null){
if (ReturnT.SUCCESS_CODE==log.getTriggerCode() && log.getHandleCode()==0) {
// running
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
JobFailMonitorHelper.monitor(jobLogId);
}
if (ReturnT.SUCCESS_CODE==log.getTriggerCode() && ReturnT.SUCCESS_CODE==log.getHandleCode()) {
// pass
}
if (ReturnT.FAIL_CODE == log.getTriggerCode()|| ReturnT.FAIL_CODE==log.getHandleCode()) {
TimingJobInfo info = TimingJobScheduler.timingJobInfoDao.loadById(log.getJobId());
if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
for (String email: emailSet) {
String title = "《调度监控报警》(任务调度中心 Timing-JOB)";
TimingJobGroup group = TimingJobScheduler.timingJobGroupDao.load(Integer.valueOf(info.getJobGroup()));
String content = MessageFormat.format("任务调度失败, 执行器名称:{0}, 任务描述:{1}.", group!=null?group.getTitle():"null", info.getJobDesc());
//MailUtil.sendMail(email, title, content, false, null);
}
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
monitorThread.setDaemon(true);
monitorThread.start();
}
public static void monitor(int jobId){
getInstance().queue.offer(jobId);
}
public void toStop(){
toStop = true;
}
}
| UTF-8 | Java | 4,154 | java | JobFailMonitorHelper.java | Java | [
{
"context": " java.util.concurrent.TimeUnit;\n\n/**\n * Created by winstone on 2017/8/23.\n */\n@Deprecated\npublic class JobFai",
"end": 595,
"score": 0.9996867179870605,
"start": 587,
"tag": "USERNAME",
"value": "winstone"
}
] | null | [] | package com.timing.job.admin.core.thread;
import com.timing.executor.core.biz.model.ReturnT;
import com.timing.job.admin.core.model.TimingJobGroup;
import com.timing.job.admin.core.model.TimingJobInfo;
import com.timing.job.admin.core.model.TimingJobLog;
import com.timing.job.admin.core.schedule.TimingJobScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Created by winstone on 2017/8/23.
*/
@Deprecated
public class JobFailMonitorHelper {
private static Logger logger = LoggerFactory.getLogger(JobFailMonitorHelper.class);
private static JobFailMonitorHelper instance = new JobFailMonitorHelper();
public static JobFailMonitorHelper getInstance(){
return instance;
}
private LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>(0xfff8);
private Thread monitorThread;
private boolean toStop = false;
public void start(){
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
while(!toStop){
try {
logger.info("monitor beat");
Integer jobLogId = JobFailMonitorHelper.instance.queue.take();
if(jobLogId!=null && jobLogId>0){
TimingJobLog log = TimingJobScheduler.timingJobLogDao.load(jobLogId);
if(log!=null){
if (ReturnT.SUCCESS_CODE==log.getTriggerCode() && log.getHandleCode()==0) {
// running
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
JobFailMonitorHelper.monitor(jobLogId);
}
if (ReturnT.SUCCESS_CODE==log.getTriggerCode() && ReturnT.SUCCESS_CODE==log.getHandleCode()) {
// pass
}
if (ReturnT.FAIL_CODE == log.getTriggerCode()|| ReturnT.FAIL_CODE==log.getHandleCode()) {
TimingJobInfo info = TimingJobScheduler.timingJobInfoDao.loadById(log.getJobId());
if (info!=null && info.getAlarmEmail()!=null && info.getAlarmEmail().trim().length()>0) {
Set<String> emailSet = new HashSet<String>(Arrays.asList(info.getAlarmEmail().split(",")));
for (String email: emailSet) {
String title = "《调度监控报警》(任务调度中心 Timing-JOB)";
TimingJobGroup group = TimingJobScheduler.timingJobGroupDao.load(Integer.valueOf(info.getJobGroup()));
String content = MessageFormat.format("任务调度失败, 执行器名称:{0}, 任务描述:{1}.", group!=null?group.getTitle():"null", info.getJobDesc());
//MailUtil.sendMail(email, title, content, false, null);
}
}
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
monitorThread.setDaemon(true);
monitorThread.start();
}
public static void monitor(int jobId){
getInstance().queue.offer(jobId);
}
public void toStop(){
toStop = true;
}
}
| 4,154 | 0.49707 | 0.492676 | 95 | 42.115791 | 38.256989 | 174 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515789 | false | false | 9 |
903b8c54474036f16807ee10c122f0a560a3a613 | 1,022,202,233,968 | c8c42734757df03806b8dd7792ddc4718ce52d9a | /flashsale/src/main/java/cn/edu/xmu/flashsale/model/vo/FlashsaleItemRetVo.java | 6b48ec1c0cff33ba8b598279088ec188be3b627a | [] | no_license | liangyingshao/goods | https://github.com/liangyingshao/goods | eb0c4d85b73066dacba16138f230889bc94110c4 | 74ba572ea601cd3d558f7817c3e77b2376405c19 | refs/heads/ym | 2023-02-09T23:41:01.092000 | 2020-12-21T13:22:11 | 2020-12-21T13:22:11 | 316,247,924 | 1 | 0 | null | false | 2020-11-29T12:36:04 | 2020-11-26T14:02:28 | 2020-11-29T11:53:20 | 2020-11-29T12:36:03 | 9,940 | 0 | 0 | 1 | Java | false | false | package cn.edu.xmu.flashsale.model.vo;
import cn.edu.xmu.flashsale.model.bo.FlashSaleItem;
import cn.edu.xmu.flashsale.model.po.FlashSaleItemPo;
import cn.edu.xmu.ooad.model.VoObject;
import cn.edu.xmu.oomall.goods.model.SkuInfoDTO;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class FlashsaleItemRetVo implements VoObject {
private Long id;
private SkuInfoDTO goodsSku;
private Long price;
private Integer quantity;
private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
public FlashsaleItemRetVo(FlashSaleItemPo po) {
this.id = po.getId();
this.price = po.getPrice();
this.quantity = po.getQuantity();
this.gmtCreate = po.getGmtCreate();
this.gmtModified = po.getGmtModified();
}
public FlashsaleItemRetVo(FlashSaleItem bo) {
this.id = bo.getId();
this.price = bo.getPrice();
this.quantity = bo.getQuantity();
this.gmtCreate = bo.getGmtCreate();
this.gmtModified = bo.getGmtModified();
}
public FlashsaleItemRetVo() {
}
@Override
public Object createVo() {
return null;
}
@Override
public Object createSimpleVo() {
return null;
}
}
| UTF-8 | Java | 1,244 | java | FlashsaleItemRetVo.java | Java | [] | null | [] | package cn.edu.xmu.flashsale.model.vo;
import cn.edu.xmu.flashsale.model.bo.FlashSaleItem;
import cn.edu.xmu.flashsale.model.po.FlashSaleItemPo;
import cn.edu.xmu.ooad.model.VoObject;
import cn.edu.xmu.oomall.goods.model.SkuInfoDTO;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class FlashsaleItemRetVo implements VoObject {
private Long id;
private SkuInfoDTO goodsSku;
private Long price;
private Integer quantity;
private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
public FlashsaleItemRetVo(FlashSaleItemPo po) {
this.id = po.getId();
this.price = po.getPrice();
this.quantity = po.getQuantity();
this.gmtCreate = po.getGmtCreate();
this.gmtModified = po.getGmtModified();
}
public FlashsaleItemRetVo(FlashSaleItem bo) {
this.id = bo.getId();
this.price = bo.getPrice();
this.quantity = bo.getQuantity();
this.gmtCreate = bo.getGmtCreate();
this.gmtModified = bo.getGmtModified();
}
public FlashsaleItemRetVo() {
}
@Override
public Object createVo() {
return null;
}
@Override
public Object createSimpleVo() {
return null;
}
}
| 1,244 | 0.672026 | 0.672026 | 49 | 24.387754 | 18.244167 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510204 | false | false | 9 |
a0c2dbed65fd6b425e4762671e19049a6bdf3447 | 15,994,458,255,746 | f5480247ac15ef4c776c721a8cc0d7d5281e1a2f | /src/main/java/com/duxuewei/onjava/string/StringEQ.java | 00f14e155b701035114608f6cd715b5f212c9382 | [] | no_license | duxuewei-flinty/onjava8-practice | https://github.com/duxuewei-flinty/onjava8-practice | edbf1fde10f5fb814febc55bf88ddeabe589fe4b | 17fea882b308ead422a8a02ceeb26cf799411258 | refs/heads/main | 2023-04-09T14:39:05.563000 | 2021-03-24T07:00:20 | 2021-03-24T07:00:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.duxuewei.onjava.string;
public class StringEQ {
public static void main(String[] args) {
// String a = "1";
// String a1 = "1";
// String iss = "isOper";
// System.err.println(iss == "isOper");
String a = "上山打老虎";
String b = a;
a = a +"123";
System.err.println(b);
}
}
| UTF-8 | Java | 367 | java | StringEQ.java | Java | [] | null | [] | package com.duxuewei.onjava.string;
public class StringEQ {
public static void main(String[] args) {
// String a = "1";
// String a1 = "1";
// String iss = "isOper";
// System.err.println(iss == "isOper");
String a = "上山打老虎";
String b = a;
a = a +"123";
System.err.println(b);
}
}
| 367 | 0.498599 | 0.481793 | 17 | 20 | 15.586571 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.529412 | false | false | 9 |
aa52cf1933a7f19ef52485f30584131bb06e91a4 | 17,557,826,344,719 | 64057936ad3a42a57ed73c6469a55c2e3fe841ba | /src/test/java/com/cucumber/MavenCucumberProject/TitleVerifySteps.java | 695b197f6e0d4f8328d40c34584059ab09d17555 | [] | no_license | AdarshaRangarajan/Cucumber-Selenium | https://github.com/AdarshaRangarajan/Cucumber-Selenium | a19a07552e803bca9a4bc89d37f10da2ae20dd1a | 632eb9b75a179999e3975a42d0f270ffcdab5d3e | refs/heads/master | 2021-01-12T04:47:27.506000 | 2017-01-02T02:16:04 | 2017-01-02T02:16:04 | 77,794,977 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cucumber.MavenCucumberProject;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import com.cucumber.MavenCucumberProject.PageObject.TitleverifyPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class TitleVerifySteps extends AbstractPageDriverStep {
WebDriver driver = null;
@Before
public void testStartUp() {
driver = super.getDriver();
System.out.println("Before method executed, Opening your browser!!");
}
@After
public void testShutDown() {
if (driver != null)
driver.quit();
super.driver = null;
System.out.println("After method executed, closing your browser!!!!!");
}
@When("^I navigate to \"([^\"]*)\"$")
public void shouldnavigateToLink(String link) throws Throwable {
TitleverifyPage titleverifyPage = new TitleverifyPage(driver);
titleverifyPage.navigateToLink(link);
}
@Then("^I check page title is \"([^\"]*)\"$")
public void shouldcheckPageTitle(String title) throws Throwable {
TitleverifyPage titleverifyPage = new TitleverifyPage(driver);
titleverifyPage.checkPageTitle();
Assert.assertEquals(titleverifyPage.checkPageTitle(), title);
}
}
| UTF-8 | Java | 1,229 | java | TitleVerifySteps.java | Java | [] | null | [] | package com.cucumber.MavenCucumberProject;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import com.cucumber.MavenCucumberProject.PageObject.TitleverifyPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class TitleVerifySteps extends AbstractPageDriverStep {
WebDriver driver = null;
@Before
public void testStartUp() {
driver = super.getDriver();
System.out.println("Before method executed, Opening your browser!!");
}
@After
public void testShutDown() {
if (driver != null)
driver.quit();
super.driver = null;
System.out.println("After method executed, closing your browser!!!!!");
}
@When("^I navigate to \"([^\"]*)\"$")
public void shouldnavigateToLink(String link) throws Throwable {
TitleverifyPage titleverifyPage = new TitleverifyPage(driver);
titleverifyPage.navigateToLink(link);
}
@Then("^I check page title is \"([^\"]*)\"$")
public void shouldcheckPageTitle(String title) throws Throwable {
TitleverifyPage titleverifyPage = new TitleverifyPage(driver);
titleverifyPage.checkPageTitle();
Assert.assertEquals(titleverifyPage.checkPageTitle(), title);
}
}
| 1,229 | 0.74939 | 0.74939 | 48 | 24.604166 | 24.63715 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.208333 | false | false | 9 |
cce2b5130f686ec0902034cbdeb833890cf99fb8 | 31,542,239,862,381 | 8bf238a9e48f7a9da2c4d2fc53ad84584b8e9f4d | /src/main/java/com/demo/reader/core/PhoneNumberValidationRule.java | 78d3ef886d754c3fb80c157d6c4b7c72e17abdf6 | [] | no_license | soleiana/country-finder | https://github.com/soleiana/country-finder | 5e891cf6af1e1de4d1e45335ec96db8246dd4402 | 936433e033a76ed43b247f1df4070b7db00dce41 | refs/heads/master | 2021-01-22T21:59:22.711000 | 2017-12-13T19:18:56 | 2017-12-13T19:18:56 | 85,497,585 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.reader.core;
abstract class PhoneNumberValidationRule {
final PhoneNumberRegexFactory phoneNumberRegexFactory;
PhoneNumberValidationRule(PhoneNumberRegexFactory phoneNumberRegexFactory) {
this.phoneNumberRegexFactory = phoneNumberRegexFactory;
}
abstract boolean apply(String phoneNumber);
}
| UTF-8 | Java | 337 | java | PhoneNumberValidationRule.java | Java | [] | null | [] | package com.demo.reader.core;
abstract class PhoneNumberValidationRule {
final PhoneNumberRegexFactory phoneNumberRegexFactory;
PhoneNumberValidationRule(PhoneNumberRegexFactory phoneNumberRegexFactory) {
this.phoneNumberRegexFactory = phoneNumberRegexFactory;
}
abstract boolean apply(String phoneNumber);
}
| 337 | 0.804154 | 0.804154 | 12 | 27.083334 | 28.534945 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
76e74ab14491832fec9f83c6e0d8c5be933d0872 | 3,006,477,149,200 | 7c9f40c50e5cabcb320195e3116384de139002c6 | /Plugin_Preprocessor/src/tinyos/yeti/preprocessor/IncludeFile.java | dd8dcbda0175fe1bb9d749f9c59872783746914c | [] | no_license | phsommer/yeti | https://github.com/phsommer/yeti | 8e89ad89f1a4053e46693244256d03e71fe830a8 | dec8c79e75b99c2a2a43aa5425f608128b883e39 | refs/heads/master | 2021-01-10T05:33:57.285000 | 2015-05-21T19:41:02 | 2015-05-21T19:41:02 | 36,033,399 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Yeti 2, NesC development in Eclipse.
* Copyright (C) 2009 ETH Zurich
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Web: http://tos-ide.ethz.ch
* Mail: tos-ide@tik.ee.ethz.ch
*/
package tinyos.yeti.preprocessor;
import java.io.Reader;
/**
* A representation of a file that gets included into another file.
* @author Benjamin Sigg
*/
public interface IncludeFile {
/**
* Opens a reader for this file.
* @return the reader or <code>null</code> if the file can't be read.
*/
public Reader read();
/**
* Gets the full path to this file. The path can be used to find
* the file again by a {@link IncludeProvider}.
* @return the path
*/
public FileInfo getFile();
}
| UTF-8 | Java | 1,343 | java | IncludeFile.java | Java | [
{
"context": "ses/>.\n *\n * Web: http://tos-ide.ethz.ch\n * Mail: tos-ide@tik.ee.ethz.ch\n */\npackage tinyos.yeti.preprocessor;\n\nimport jav",
"end": 793,
"score": 0.9999271631240845,
"start": 771,
"tag": "EMAIL",
"value": "tos-ide@tik.ee.ethz.ch"
},
{
"context": " that gets incl... | null | [] | /*
* Yeti 2, NesC development in Eclipse.
* Copyright (C) 2009 ETH Zurich
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Web: http://tos-ide.ethz.ch
* Mail: <EMAIL>
*/
package tinyos.yeti.preprocessor;
import java.io.Reader;
/**
* A representation of a file that gets included into another file.
* @author <NAME>
*/
public interface IncludeFile {
/**
* Opens a reader for this file.
* @return the reader or <code>null</code> if the file can't be read.
*/
public Reader read();
/**
* Gets the full path to this file. The path can be used to find
* the file again by a {@link IncludeProvider}.
* @return the path
*/
public FileInfo getFile();
}
| 1,321 | 0.688012 | 0.683544 | 43 | 30.232557 | 26.349915 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232558 | false | false | 9 |
b2997655f041728aba376144cb1164dfde274841 | 8,358,006,404,151 | 1f7f63205e9ea7c620895b70b6eb72b15c80331f | /src/test/java/be/hehehe/geekbot/utils/BundleServiceTest.java | cbe849913cabab5dbc99f94c7d57db3a27dba4ac | [] | no_license | Oxxan/GeekBot | https://github.com/Oxxan/GeekBot | 76782192ad6703eaf991e579a72576d4fa417d73 | d34290d9a5caa8e8cb350da15ddc4f7796e64049 | refs/heads/master | 2021-01-15T16:06:00.362000 | 2012-02-22T13:52:10 | 2012-02-22T13:52:10 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.hehehe.geekbot.utils;
import javax.inject.Inject;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import be.hehehe.geekbot.WeldRunner;
@RunWith(WeldRunner.class)
public class BundleServiceTest {
@Inject
private BundleService bundleService;
@Test
public void testBotName() {
Assert.assertTrue(StringUtils.isNotBlank(bundleService.getBotName()));
}
}
| UTF-8 | Java | 482 | java | BundleServiceTest.java | Java | [] | null | [] | package be.hehehe.geekbot.utils;
import javax.inject.Inject;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import be.hehehe.geekbot.WeldRunner;
@RunWith(WeldRunner.class)
public class BundleServiceTest {
@Inject
private BundleService bundleService;
@Test
public void testBotName() {
Assert.assertTrue(StringUtils.isNotBlank(bundleService.getBotName()));
}
}
| 482 | 0.753112 | 0.753112 | 24 | 18.083334 | 18.92951 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
4a06960b3f8815f07abaf924f3faf8f0c211c0ee | 10,823,317,631,393 | 46259f0e31770a5193595a53a9c58c41cd8ecb46 | /src/com/companyJD1/lecture15_io_stream/Mission7.java | a825e5742b5b1347601718e25f44e2bef4ca9b18 | [] | no_license | IvanLapa/HelloWorld | https://github.com/IvanLapa/HelloWorld | 7760fdbfb1b44549b64d901fcacbe7a453286c49 | 7ba7aece57b8223456994081feab1350cf4fc9c0 | refs/heads/master | 2021-01-13T23:51:13.099000 | 2020-10-31T07:21:02 | 2020-10-31T07:21:17 | 242,531,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.companyJD1.lecture15_io_stream;
import java.io.*;
/**Задан файл с java-кодом. Прочитать текст программы из файла и записать
* в другой файл в обратном порядке символы каждой строки.
*/
public class Mission7 {
public static void main(String[] args) {
File fileRead = new File("C:\\Users\\Иван\\IdeaProjects\\HelloWorld\\src\\com\\companyJD1\\lecture15_io_stream\\resources\\for_lecture15_7_read.txt");
File fileWrite = new File("C:\\Users\\Иван\\IdeaProjects\\HelloWorld\\src\\com\\companyJD1\\lecture15_io_stream\\resources\\for_lecture15_7_write.txt");
reverse(fileRead, fileWrite);
}
private static void reverse(File mainFile, File reverseFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(mainFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(reverseFile));
String line;
while ((line = reader.readLine()) != null) {
for (int i = line.length() - 1; i >= 0; i--) {
writer.write(line.charAt(i));
}
writer.write("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,340 | java | Mission7.java | Java | [
{
"context": "s) {\n File fileRead = new File(\"C:\\\\Users\\\\Иван\\\\IdeaProjects\\\\HelloWorld\\\\src\\\\com\\\\companyJD1\\\\",
"end": 320,
"score": 0.9996724128723145,
"start": 316,
"tag": "NAME",
"value": "Иван"
},
{
"context": "\");\n File fileWrite = new File(\"... | null | [] | package com.companyJD1.lecture15_io_stream;
import java.io.*;
/**Задан файл с java-кодом. Прочитать текст программы из файла и записать
* в другой файл в обратном порядке символы каждой строки.
*/
public class Mission7 {
public static void main(String[] args) {
File fileRead = new File("C:\\Users\\Иван\\IdeaProjects\\HelloWorld\\src\\com\\companyJD1\\lecture15_io_stream\\resources\\for_lecture15_7_read.txt");
File fileWrite = new File("C:\\Users\\Иван\\IdeaProjects\\HelloWorld\\src\\com\\companyJD1\\lecture15_io_stream\\resources\\for_lecture15_7_write.txt");
reverse(fileRead, fileWrite);
}
private static void reverse(File mainFile, File reverseFile) {
try {
BufferedReader reader = new BufferedReader(new FileReader(mainFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(reverseFile));
String line;
while ((line = reader.readLine()) != null) {
for (int i = line.length() - 1; i >= 0; i--) {
writer.write(line.charAt(i));
}
writer.write("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,340 | 0.61039 | 0.595779 | 31 | 38.741936 | 40.455444 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.483871 | false | false | 9 |
73c11b28fd1ff0224bb1993649c14f11ba815499 | 1,176,821,041,212 | 8e37ded6ffd463f6fa04be12bc6981b51331505f | /src/main/java/com/mark/csdn/concurrent/thread/MultiThread.java | 35c452d3bafbdf230935dd201dc5bb1f69354366 | [] | no_license | 25Dong/CSDN-CONCURRENT | https://github.com/25Dong/CSDN-CONCURRENT | f1f91c7f7c95cead2a29a9fa3fe990cb5b2dc3f0 | bdaf55473138373f673802451818a6bb956cb276 | refs/heads/master | 2021-04-23T07:10:40.046000 | 2020-07-01T15:10:24 | 2020-07-01T15:10:24 | 249,908,321 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mark.csdn.concurrent.thread;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* @Description: 查看一个普通的Java程序包含了那些线程
* @Author: Mark
* @CreateDate: 2020/3/7 11:47
* @Version: 1.0
* @Copyright : 豆浆油条个人非正式工作室
*
* 摘抄于《Java并发编程的艺术-4.1.1》
* 总结:一个Java程序的运行不仅仅是main()方法的运行,而是main线程和其他线程同时执行
*/
public class MultiThread {
public static void main(String[] args) {
//获取Java线程管理MXBean
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
//获取线程和堆栈信息
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
//遍历打印线程信息
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "]" + threadInfo.getThreadName());
//[6]Monitor Ctrl-Break
//[5]Attach Listener
//[4]Signal Dispatcher
//[3]Finalizer
//[2]Reference Handler
//[1]main
}
}
}
| UTF-8 | Java | 1,231 | java | MultiThread.java | Java | [
{
"context": "\n * @Description: 查看一个普通的Java程序包含了那些线程\n * @Author: Mark\n * @CreateDate: 2020/3/7 11:47\n * @Version: 1.0\n ",
"end": 230,
"score": 0.9975664615631104,
"start": 226,
"tag": "NAME",
"value": "Mark"
}
] | null | [] | package com.mark.csdn.concurrent.thread;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
/**
* @Description: 查看一个普通的Java程序包含了那些线程
* @Author: Mark
* @CreateDate: 2020/3/7 11:47
* @Version: 1.0
* @Copyright : 豆浆油条个人非正式工作室
*
* 摘抄于《Java并发编程的艺术-4.1.1》
* 总结:一个Java程序的运行不仅仅是main()方法的运行,而是main线程和其他线程同时执行
*/
public class MultiThread {
public static void main(String[] args) {
//获取Java线程管理MXBean
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
//获取线程和堆栈信息
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
//遍历打印线程信息
for (ThreadInfo threadInfo : threadInfos) {
System.out.println("[" + threadInfo.getThreadId() + "]" + threadInfo.getThreadName());
//[6]Monitor Ctrl-Break
//[5]Attach Listener
//[4]Signal Dispatcher
//[3]Finalizer
//[2]Reference Handler
//[1]main
}
}
}
| 1,231 | 0.643888 | 0.623677 | 35 | 28.685715 | 22.618288 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.228571 | false | false | 9 |
0062a67938183c872523a3be72f8f39a6ab747c5 | 16,277,926,082,166 | eba867ce83b4b5f8747a5cbb993c73fb58cbded1 | /line/TokenType.java | 2f36298e756d0fc168209d5cd1aab2dd64a0ed2e | [] | no_license | alonaviv/SJavaVerifier | https://github.com/alonaviv/SJavaVerifier | 53acf67e35f2c16190376bd97b1e871cea3665be | 17499577fc777231cbb51ba8126912048dfb89b0 | refs/heads/master | 2020-12-24T19:04:07.628000 | 2016-05-22T17:30:04 | 2016-05-22T17:30:04 | 59,425,012 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package oop.ex6.line;
public enum TokenType {
//Note: DOUBLEVAL only finds "pure" doubles - with a decimal point.
//When checking a double variable, it can be both DOUBLEVAL and INTVAL.
DOUBLEVAL("-?\\d++(?:\\.\\d+)",TokenType.VALUE_SYMBOL),
INTVAL("-?\\d+",TokenType.VALUE_SYMBOL),
STRINGVAL("\".+\"+",TokenType.VALUE_SYMBOL),
CHARVAL("\'.\'",TokenType.VALUE_SYMBOL),
//Same for boolean, is only the "pure" true/false attributes.
//When checking for a boolean, it can be both BOOLEANVAL and INTVAL.
BOOLEANVAL("true|false",TokenType.VALUE_SYMBOL),
INT("int ",TokenType.TYPE_SYMBOL),
DOUBLE("double ",TokenType.TYPE_SYMBOL),
STRING("String ",TokenType.TYPE_SYMBOL),
CHAR("char ",TokenType.TYPE_SYMBOL),
BOOLEAN("boolean ",TokenType.TYPE_SYMBOL),
VOID("void "),
FINAL("final "),
IF("if\\s*\\("),
WHILE("while\\s*\\("),
RETURN("return;"),
WHITESPACE("\\s+"),
COMMA("\\,"),
OPENINGBRACKET("\\{"),
CLOSINGBRACKET("\\}"),
OPENINGPARENTHESIS("\\("),
CLOSINGPARENTHESIS("\\)"),
EQUALS("="),
ANDBOOL("&&"),
ORBOOL("\\|{2}"),
SEMICOLON(";"),
COMMENTDECLARE("//"),
METHODNAME("[a-zA-Z]\\w*\\s*\\("),
VARNAME("[a-zA-Z][a-zA-Z-0-9_]*|_\\w+"),
OTHERTOKEN(".");
private static final int VALUE_SYMBOL = 1;
private static final int TYPE_SYMBOL= 2;
public final String pattern;
private int valueOrTypeMarker;
/**
* Token Type constructor
* @param pattern The token's regex pattern.
*/
private TokenType(String pattern) {
this.pattern = pattern;
}
/**
* Token Type constructor
* @param pattern The token's regex pattern.
*/
private TokenType(String pattern, int valueOrTypeMarker) {
this.pattern = pattern;
this.valueOrTypeMarker = valueOrTypeMarker;
}
/**
* Checks if the given token type is a type of variable declaration
* @param tokenType A token type
* @return True iff the token type is a variable declaration
*/
public static boolean isVarType(TokenType tokenType) {
return tokenType.valueOrTypeMarker == TYPE_SYMBOL;
}
/**
* Checks if the given token type is a type of variable value
* @param tokenType A token type
* @return True iff the token type is a variable value
*/
public static boolean isVarValue(TokenType tokenType) {
return tokenType.valueOrTypeMarker == VALUE_SYMBOL;
}
}
| UTF-8 | Java | 2,309 | java | TokenType.java | Java | [] | null | [] | package oop.ex6.line;
public enum TokenType {
//Note: DOUBLEVAL only finds "pure" doubles - with a decimal point.
//When checking a double variable, it can be both DOUBLEVAL and INTVAL.
DOUBLEVAL("-?\\d++(?:\\.\\d+)",TokenType.VALUE_SYMBOL),
INTVAL("-?\\d+",TokenType.VALUE_SYMBOL),
STRINGVAL("\".+\"+",TokenType.VALUE_SYMBOL),
CHARVAL("\'.\'",TokenType.VALUE_SYMBOL),
//Same for boolean, is only the "pure" true/false attributes.
//When checking for a boolean, it can be both BOOLEANVAL and INTVAL.
BOOLEANVAL("true|false",TokenType.VALUE_SYMBOL),
INT("int ",TokenType.TYPE_SYMBOL),
DOUBLE("double ",TokenType.TYPE_SYMBOL),
STRING("String ",TokenType.TYPE_SYMBOL),
CHAR("char ",TokenType.TYPE_SYMBOL),
BOOLEAN("boolean ",TokenType.TYPE_SYMBOL),
VOID("void "),
FINAL("final "),
IF("if\\s*\\("),
WHILE("while\\s*\\("),
RETURN("return;"),
WHITESPACE("\\s+"),
COMMA("\\,"),
OPENINGBRACKET("\\{"),
CLOSINGBRACKET("\\}"),
OPENINGPARENTHESIS("\\("),
CLOSINGPARENTHESIS("\\)"),
EQUALS("="),
ANDBOOL("&&"),
ORBOOL("\\|{2}"),
SEMICOLON(";"),
COMMENTDECLARE("//"),
METHODNAME("[a-zA-Z]\\w*\\s*\\("),
VARNAME("[a-zA-Z][a-zA-Z-0-9_]*|_\\w+"),
OTHERTOKEN(".");
private static final int VALUE_SYMBOL = 1;
private static final int TYPE_SYMBOL= 2;
public final String pattern;
private int valueOrTypeMarker;
/**
* Token Type constructor
* @param pattern The token's regex pattern.
*/
private TokenType(String pattern) {
this.pattern = pattern;
}
/**
* Token Type constructor
* @param pattern The token's regex pattern.
*/
private TokenType(String pattern, int valueOrTypeMarker) {
this.pattern = pattern;
this.valueOrTypeMarker = valueOrTypeMarker;
}
/**
* Checks if the given token type is a type of variable declaration
* @param tokenType A token type
* @return True iff the token type is a variable declaration
*/
public static boolean isVarType(TokenType tokenType) {
return tokenType.valueOrTypeMarker == TYPE_SYMBOL;
}
/**
* Checks if the given token type is a type of variable value
* @param tokenType A token type
* @return True iff the token type is a variable value
*/
public static boolean isVarValue(TokenType tokenType) {
return tokenType.valueOrTypeMarker == VALUE_SYMBOL;
}
}
| 2,309 | 0.667822 | 0.665223 | 83 | 26.819277 | 21.210445 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.60241 | false | false | 9 |
fa93d7e78b3ad3619e64079b1408fb0d0846280e | 12,360,915,901,645 | b7f50eb906e525f70eb07030519e3a7484050e65 | /LanSongSDK/src/main/java/com/lansosdk/videoeditor/LSOCameraView.java | c02b513e9327a4e9bc412447ea27fbe805cff6a8 | [] | no_license | RubinTry/LanSoEditor_advance | https://github.com/RubinTry/LanSoEditor_advance | 5e81543967e9db90d6e5cd14702b9ef396a02401 | bf4890f551efb02bf72288e966db8cbfdd4b5a51 | refs/heads/master | 2022-12-29T16:51:19.687000 | 2020-10-19T03:24:21 | 2020-10-19T03:24:21 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lansosdk.videoeditor;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import com.lansosdk.LanSongFilter.LanSongFilter;
import com.lansosdk.box.BitmapLayer;
import com.lansosdk.box.CameraLayer;
import com.lansosdk.box.GifLayer;
import com.lansosdk.box.LSOCameraLayer;
import com.lansosdk.box.LSOCameraRunnable;
import com.lansosdk.box.LSOLog;
import com.lansosdk.box.LSOMVAsset2;
import com.lansosdk.box.LSOScaleType;
import com.lansosdk.box.Layer;
import com.lansosdk.box.MVLayer2;
import com.lansosdk.box.VideoLayer2;
import com.lansosdk.box.onDrawPadCompletedListener;
import com.lansosdk.box.onDrawPadErrorListener;
import com.lansosdk.box.onDrawPadOutFrameListener;
import com.lansosdk.box.onDrawPadProgressListener;
import com.lansosdk.box.onDrawPadRecordCompletedListener;
import com.lansosdk.box.onDrawPadSizeChangedListener;
import com.lansosdk.box.onDrawPadSnapShotListener;
import java.util.concurrent.atomic.AtomicBoolean;
public class LSOCameraView extends FrameLayout {
private int compWidth=1080;
private int compHeight=1920;
private LSOCameraRunnable renderer;
// ----------------------------------------------
private TextureRenderView textureRenderView;
private SurfaceTexture mSurfaceTexture = null;
public onViewAvailable viewAvailable = null;
private boolean layoutOk = false;
public LSOCameraView(Context context) {
super(context);
initVideoView(context);
}
public LSOCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView(context);
}
public LSOCameraView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initVideoView(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LSOCameraView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initVideoView(context);
}
private void initVideoView(Context context) {
setTextureView();
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
}
private int viewWidth, viewHeight;
private void setTextureView() {
textureRenderView = new TextureRenderView(getContext());
textureRenderView.setSurfaceTextureListener(new SurfaceCallback());
textureRenderView.setDisplayRatio(0);
View renderUIView = textureRenderView.getView();
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER);
renderUIView.setLayoutParams(lp);
addView(renderUIView);
textureRenderView.setVideoRotation(0);
}
public void onResume(onViewAvailable listener) {
viewAvailable = listener;
if (mSurfaceTexture != null && viewAvailable !=null) {
if (viewHeight > 0 && viewWidth >0) {
float wantRadio = (float) compWidth / (float) compHeight;
float viewRadio = (float) viewWidth / (float) viewHeight;
if (wantRadio == viewRadio) {
layoutOk = true;
viewAvailable.viewAvailable();
} else if (Math.abs(wantRadio - viewRadio) * 1000 < 16.0f) {
layoutOk = true;
viewAvailable.viewAvailable();
} else {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
LSOLog.d("setOnViewAvailable layout again...");
requestLayoutPreview();
}
}
}
}
public void onPause(){
viewAvailable =null;
stopCamera();
}
public Surface getSurface() {
if (mSurfaceTexture != null) {
return new Surface(mSurfaceTexture);
}
return null;
}
public interface onViewAvailable {
void viewAvailable();
}
private class SurfaceCallback implements TextureView.SurfaceTextureListener {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
mSurfaceTexture = surface;
viewWidth = width;
viewHeight = height;
checkLayoutSize();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface,int width, int height) {
mSurfaceTexture = surface;
viewWidth = width;
viewHeight = height;
checkLayoutSize();
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mSurfaceTexture = null;
layoutOk = false;
release();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
private OnCompositionSizeReadyListener onCompositionSizeReadyListener;
/**
*准备容器的宽高;
* 在设置后, 我们会根据这个大小来调整 这个类的大小, 从而让画面不变形;
* @param listener 自适应屏幕后的回调
*/
public void prepareAsync(OnCompositionSizeReadyListener listener) {
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
if(dm.widthPixels * dm.heightPixels<1080*1920){
compWidth=720;
compHeight=1280;
}
requestLayoutCount = 0;
onCompositionSizeReadyListener = listener;
if (viewWidth == 0 || viewHeight == 0) { //直接重新布局UI
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
} else {
float setRatio = (float) compWidth / (float) compHeight;
float setViewRatio = (float) viewWidth / (float) viewHeight;
if (setRatio == setViewRatio) { // 如果比例已经相等,不需要再调整,则直接显示.
layoutOk = true;
sendCompositionSizeListener();
} else if (Math.abs(setRatio - setViewRatio) * 1000 < 16.0f) {
if (listener != null) {
layoutOk = true;
sendCompositionSizeListener();
}
} else if (textureRenderView != null) {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
}
}
requestLayoutPreview();
}
private void sendCompositionSizeListener() {
if (onCompositionSizeReadyListener != null) {
onCompositionSizeReadyListener.onSizeReady();
onCompositionSizeReadyListener = null;
}
}
private int requestLayoutCount = 0;
private void checkLayoutSize() {
DisplayMetrics dm = getResources().getDisplayMetrics();
if(viewWidth ==dm.widthPixels){
float wantRatio = (float) compWidth / (float) compHeight;
float padRatio = (float) viewWidth / (float) viewHeight;
if (wantRatio == padRatio) { // 如果比例已经相等,不需要再调整,则直接显示.
layoutOk = true;
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
} else if (Math.abs(wantRatio - padRatio) * 1000 < 16.0f) {
layoutOk = true;
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
}
} else {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
LSOLog.d("checkLayoutSize no right, layout again...");
requestLayoutPreview();
}
}
private void requestLayoutPreview() {
requestLayoutCount++;
if (requestLayoutCount > 3) {
LSOLog.e("LSOCameraView layout view error. return callback");
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
} else {
requestLayout();
}
}
//---------------render start--------------------------------------------------------------------------------------
private static boolean isCameraOpened = false;
private int encWidth, encHeight;
private String encPath;
private boolean isFrontCam = false;
private LanSongFilter initFilter = null;
private float encodeSpeed = 1.0f;
private onDrawPadSizeChangedListener sizeChangedCB = null;
private onDrawPadProgressListener drawPadProgressListener = null;
private onDrawPadRecordCompletedListener drawPadRecordCompletedListener = null;
private boolean frameListenerInDrawPad = false;
private onDrawPadCompletedListener drawPadCompletedListener = null;
private onDrawPadErrorListener drawPadErrorListener = null;
private boolean recordMic = false;
private boolean isPauseRefresh = false;
private boolean isPauseRecord = false;
private boolean isZoomEvent = false;
private float touching;
private OnFocusEventListener onFocusListener;
private boolean isCheckPadSize = true;
private boolean isEnableTouch = true;
public void setCameraFront(boolean front) {
isFrontCam = front;
}
public void setEncodeParam(String path) {
encWidth = 1088;
encHeight = 1920;
encPath = path;
}
public void setOnDrawPadProgressListener(onDrawPadProgressListener listener) {
if (renderer != null) {
renderer.setDrawPadProgressListener(listener);
}
drawPadProgressListener = listener;
}
public void getPhotoAsync(onDrawPadSnapShotListener listener) {
if (renderer != null && renderer.isRunning()) {
renderer.setDrawPadSnapShotListener(listener);
renderer.toggleSnapShot(compWidth, compHeight);
} else if (listener != null) {
LSOLog.e("getPhotoAsync error.");
listener.onSnapShot(null, null);
}
}
public void setOnDrawPadCompletedListener(onDrawPadCompletedListener listener) {
if (renderer != null) {
renderer.setDrawPadCompletedListener(listener);
}
drawPadCompletedListener = listener;
}
public void setOnDrawPadErrorListener(onDrawPadErrorListener listener) {
if (renderer != null) {
renderer.setDrawPadErrorListener(listener);
}
drawPadErrorListener = listener;
}
private boolean setupDrawPad() {
if (renderer == null) {
pauseRecord();
pausePreview();
return startDrawPad(true);
} else {
return false;
}
}
private boolean startDrawPad(boolean pauseRecord) {
boolean ret = false;
if (isCameraOpened) {
LSOLog.e("DrawPad opened...");
return false;
}
if (mSurfaceTexture != null && renderer == null) {
// renderer = new LSOCameraRunnable(getContext(), compWidth,compHeight);
renderer = new LSOCameraRunnable(getContext(), viewWidth,viewHeight);
renderer.setCameraParam(isFrontCam, initFilter);
if (renderer != null) {
renderer.setDisplaySurface(textureRenderView, new Surface(mSurfaceTexture));
if (isCheckPadSize) {
encWidth = LanSongUtil.make16Multi(encWidth);
encHeight = LanSongUtil.make16Multi(encHeight);
}
renderer.setEncoderParams(encWidth, encHeight, encPath);
// 设置DrawPad处理的进度监听, 回传的currentTimeUs单位是微秒.
renderer.setDrawPadProgressListener(drawPadProgressListener);
renderer.setDrawPadCompletedListener(drawPadCompletedListener);
renderer.setOutFrameInDrawPad(frameListenerInDrawPad);
renderer.setDrawPadRecordCompletedListener(drawPadRecordCompletedListener);
renderer.setDrawPadErrorListener(drawPadErrorListener);
renderer.setRecordMic(true);
if (pauseRecord || isPauseRecord) {
renderer.pauseRecordDrawPad();
}
if (isPauseRefresh) {
renderer.pauseRefreshDrawPad();
}
renderer.adjustEncodeSpeed(encodeSpeed);
LSOLog.d("starting run draw pad thread...");
ret = renderer.startDrawPad();
isCameraOpened = ret;
if (!ret) {
LSOLog.e("open LSOCameraView error.\n");
} else {
renderer.setDisplaySurface(textureRenderView, new Surface(mSurfaceTexture));
}
}
} else {
LSOLog.w("start draw pad error.");
}
return ret;
}
protected BitmapLayer bgBitmapLayer = null;
protected VideoLayer2 bgVideoLayer = null;
protected BitmapLayer fgBitmapLayer = null;
protected MVLayer2 fgMvLayer = null;
public void setBackGroundBitmap(Bitmap bmp, boolean recycle) {
if (renderer != null && isRunning() && bmp != null && !bmp.isRecycled()) {
removeBackGroundLayer();
bgBitmapLayer = renderer.addBitmapLayer(bmp, recycle);
bgBitmapLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
renderer.bringToBack(bgBitmapLayer);
}
}
public void setBackGroundVideoPath(String path) {
if (renderer != null && isRunning() && path != null) {
removeBackGroundLayer();
bgVideoLayer = renderer.addVideoLayer2(path);
if (bgVideoLayer != null) {
bgVideoLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
bgVideoLayer.setPlayerLooping(true);
bgVideoLayer.setAudioVolume(0.0f);
renderer.bringToBack(bgVideoLayer);
}
}
}
public void setForeGroundBitmap(Bitmap bmp, boolean recycle) {
if (renderer != null && isRunning() && bmp != null && !bmp.isRecycled()) {
removeForeGroundLayer();
fgBitmapLayer = renderer.addBitmapLayer(bmp, recycle);
if (fgBitmapLayer != null) {
fgBitmapLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
}
}
}
public void setForeGroundVideoPath(String colorPath, String maskPath) {
if (renderer != null && isRunning() && colorPath != null && maskPath != null) {
removeForeGroundLayer();
try {
LSOMVAsset2 lsomvAsset2 = new LSOMVAsset2(colorPath, maskPath, false);
fgMvLayer = renderer.addMVLayer(lsomvAsset2);
if (fgMvLayer != null) {
fgMvLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
fgMvLayer.setLooping(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected LSOCameraLayer cameraLayer = null;
public void removeBackGroundLayer() {
if (renderer != null) {
renderer.removeLayer(bgBitmapLayer);
bgBitmapLayer = null;
renderer.removeLayer(bgVideoLayer);
bgVideoLayer = null;
}
}
public void removeForeGroundLayer() {
if (renderer != null) {
renderer.removeLayer(fgBitmapLayer);
renderer.removeLayer(fgMvLayer);
fgBitmapLayer = null;
fgMvLayer = null;
}
}
public boolean isGreenMatting() {
return cameraLayer != null && cameraLayer.isGreenMatting();
}
public void setGreenMatting() {
if (cameraLayer != null && !cameraLayer.isGreenMatting()) {
cameraLayer.setGreenMatting();
}
}
public void cancelGreenMatting() {
if (cameraLayer != null && cameraLayer.isGreenMatting()) {
cameraLayer.cancelGreenMatting();
}
}
public void setFilter(LanSongFilter filter) {
if (cameraLayer != null) {
cameraLayer.switchFilterTo(filter);
}
}
public void setBeautyLevel(float level) {
if (cameraLayer != null) {
cameraLayer.setBeautyLevel(level);
}
}
public void changeCamera() {
if (cameraLayer != null && isRunning() && CameraLayer.isSupportFrontCamera()) {
// 先把DrawPad暂停运行.
pausePreview();
cameraLayer.changeCamera();
resumePreview(); // 再次开启.
}
}
public void changeFlash() {
if (cameraLayer != null) {
cameraLayer.changeFlash();
}
}
public void pausePreview() {
if (renderer != null) {
renderer.pauseRefreshDrawPad();
}
isPauseRefresh = true;
}
public void resumePreview() {
if (renderer != null) {
renderer.resumeRefreshDrawPad();
}
isPauseRefresh = false;
}
public void startRecord() {
if (renderer != null) {
renderer.resumeRecordDrawPad();
}
isPauseRecord = false;
}
public void pauseRecord() {
if (renderer != null) {
renderer.pauseRecordDrawPad();
}
isPauseRecord = true;
}
public void resumeRecord() {
if (renderer != null) {
renderer.resumeRecordDrawPad();
}
isPauseRecord = false;
}
public boolean isRecording() {
if (renderer != null) {
boolean ret = renderer.isRecording();
return ret;
} else
return false;
}
public boolean isRunning() {
if (renderer != null)
return renderer.isRunning();
else
return false;
}
public boolean startCamera() {
if (setupDrawPad()) // 建立容器
{
cameraLayer = getCameraLayer();
if (cameraLayer != null) {
renderer.resumeRefreshDrawPad();
isPauseRefresh = false;
cameraLayer.setGreenMatting();
return true;
}
}
return false;
}
public void stopCamera() {
if (renderer != null) {
renderer.release();
renderer = null;
}
isCameraOpened = false;
cameraLayer = null;
bgBitmapLayer = null;
bgVideoLayer = null;
}
public void bringLayerToFront(Layer layer) {
if (renderer != null) {
renderer.bringToFront(layer);
}
}
private LSOCameraLayer getCameraLayer() {
if (renderer != null && renderer.isRunning())
return renderer.getCameraLayer();
else {
LSOLog.e("getCameraLayer error.");
return null;
}
}
public BitmapLayer addBitmapLayer(Bitmap bmp) {
if (bmp != null) {
if (renderer != null) {
return renderer.addBitmapLayer(bmp, null);
}
}
LSOLog.e("addBitmapLayer error.");
return null;
}
/**
* 增加一个gif图层.
*
* @param gifPath gif的绝对地址,
* @return
*/
public GifLayer addGifLayer(String gifPath) {
if (renderer != null)
return renderer.addGifLayer(gifPath);
else {
LSOLog.e("addGifLayer error");
return null;
}
}
public GifLayer addGifLayer(int resId) {
if (renderer != null)
return renderer.addGifLayer(resId);
else {
LSOLog.e("addGifLayer error");
return null;
}
}
public MVLayer2 addMVLayer(LSOMVAsset2 mvAsset) {
if (renderer != null)
return renderer.addMVLayer(mvAsset);
else {
LSOLog.e("addMVLayer error render is null");
return null;
}
}
public void removeLayer(Layer layer) {
if (layer != null) {
if (renderer != null)
renderer.removeLayer(layer);
else {
LSOLog.e("removeLayer error render is null");
}
}
}
float x1 = 0;
float x2 = 0;
float y1 = 0;
float y2 = 0;
public boolean onTouchEvent(MotionEvent event) {
if (!isEnableTouch) { // 如果禁止了touch事件,则直接返回false;
return false;
}
if (getCameraLayer() == null) {
return false;
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
// 手指压下屏幕
case MotionEvent.ACTION_DOWN:
isZoomEvent = false;
x1 = event.getX();
y1 = event.getY();
break;
case MotionEvent.ACTION_POINTER_DOWN:
// 计算两个手指间的距离
if (isRunning()) {
touching = spacing(event);
isZoomEvent = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (isZoomEvent && isRunning()) {
LSOCameraLayer layer = getCameraLayer();
if (layer != null && event.getPointerCount() >= 2) {// 触屏两个点时才执行
float endDis = spacing(event);// 结束距离
int scale = (int) ((endDis - touching) / 10f); // 每变化10f
// zoom变1, 拉近拉远;
if (scale >= 1 || scale <= -1) {
int zoom = layer.getZoom() + scale;
layer.setZoom(zoom);
touching = endDis;
}
}
}
break;
// 手指离开屏幕
case MotionEvent.ACTION_UP:
if (isRunning()) {
if (!isZoomEvent) {
LSOCameraLayer layer = getCameraLayer();
if (layer != null) {
float x = event.getX();
float y = event.getY();
if (renderer != null) {
x = renderer.getTouchX(x);
y = renderer.getTouchY(y);
}
layer.doFocus((int) x, (int) y);
if (onFocusListener != null) {
onFocusListener.onFocus((int) x, (int) y);
}
}
}
}
isZoomEvent = false;
break;
}
return true;
}
private float spacing(MotionEvent event) {
if (event == null) {
return 0;
}
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
public void setCameraFocusListener(OnFocusEventListener listener) {
this.onFocusListener = listener;
}
public void setNotCheckDrawPadSize() {
isCheckPadSize = false;
}
public void setEnableTouch(boolean enable) {
isEnableTouch = enable;
}
public interface OnFocusEventListener {
void onFocus(int x, int y);
}
/**
* 释放所有.
*/
public void release() {
// cancel();
}
}
| UTF-8 | Java | 24,529 | java | LSOCameraView.java | Java | [] | null | [] | package com.lansosdk.videoeditor;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import com.lansosdk.LanSongFilter.LanSongFilter;
import com.lansosdk.box.BitmapLayer;
import com.lansosdk.box.CameraLayer;
import com.lansosdk.box.GifLayer;
import com.lansosdk.box.LSOCameraLayer;
import com.lansosdk.box.LSOCameraRunnable;
import com.lansosdk.box.LSOLog;
import com.lansosdk.box.LSOMVAsset2;
import com.lansosdk.box.LSOScaleType;
import com.lansosdk.box.Layer;
import com.lansosdk.box.MVLayer2;
import com.lansosdk.box.VideoLayer2;
import com.lansosdk.box.onDrawPadCompletedListener;
import com.lansosdk.box.onDrawPadErrorListener;
import com.lansosdk.box.onDrawPadOutFrameListener;
import com.lansosdk.box.onDrawPadProgressListener;
import com.lansosdk.box.onDrawPadRecordCompletedListener;
import com.lansosdk.box.onDrawPadSizeChangedListener;
import com.lansosdk.box.onDrawPadSnapShotListener;
import java.util.concurrent.atomic.AtomicBoolean;
public class LSOCameraView extends FrameLayout {
private int compWidth=1080;
private int compHeight=1920;
private LSOCameraRunnable renderer;
// ----------------------------------------------
private TextureRenderView textureRenderView;
private SurfaceTexture mSurfaceTexture = null;
public onViewAvailable viewAvailable = null;
private boolean layoutOk = false;
public LSOCameraView(Context context) {
super(context);
initVideoView(context);
}
public LSOCameraView(Context context, AttributeSet attrs) {
super(context, attrs);
initVideoView(context);
}
public LSOCameraView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initVideoView(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public LSOCameraView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initVideoView(context);
}
private void initVideoView(Context context) {
setTextureView();
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
}
private int viewWidth, viewHeight;
private void setTextureView() {
textureRenderView = new TextureRenderView(getContext());
textureRenderView.setSurfaceTextureListener(new SurfaceCallback());
textureRenderView.setDisplayRatio(0);
View renderUIView = textureRenderView.getView();
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.CENTER);
renderUIView.setLayoutParams(lp);
addView(renderUIView);
textureRenderView.setVideoRotation(0);
}
public void onResume(onViewAvailable listener) {
viewAvailable = listener;
if (mSurfaceTexture != null && viewAvailable !=null) {
if (viewHeight > 0 && viewWidth >0) {
float wantRadio = (float) compWidth / (float) compHeight;
float viewRadio = (float) viewWidth / (float) viewHeight;
if (wantRadio == viewRadio) {
layoutOk = true;
viewAvailable.viewAvailable();
} else if (Math.abs(wantRadio - viewRadio) * 1000 < 16.0f) {
layoutOk = true;
viewAvailable.viewAvailable();
} else {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
LSOLog.d("setOnViewAvailable layout again...");
requestLayoutPreview();
}
}
}
}
public void onPause(){
viewAvailable =null;
stopCamera();
}
public Surface getSurface() {
if (mSurfaceTexture != null) {
return new Surface(mSurfaceTexture);
}
return null;
}
public interface onViewAvailable {
void viewAvailable();
}
private class SurfaceCallback implements TextureView.SurfaceTextureListener {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
mSurfaceTexture = surface;
viewWidth = width;
viewHeight = height;
checkLayoutSize();
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface,int width, int height) {
mSurfaceTexture = surface;
viewWidth = width;
viewHeight = height;
checkLayoutSize();
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
mSurfaceTexture = null;
layoutOk = false;
release();
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
}
private OnCompositionSizeReadyListener onCompositionSizeReadyListener;
/**
*准备容器的宽高;
* 在设置后, 我们会根据这个大小来调整 这个类的大小, 从而让画面不变形;
* @param listener 自适应屏幕后的回调
*/
public void prepareAsync(OnCompositionSizeReadyListener listener) {
DisplayMetrics dm = new DisplayMetrics();
dm = getResources().getDisplayMetrics();
if(dm.widthPixels * dm.heightPixels<1080*1920){
compWidth=720;
compHeight=1280;
}
requestLayoutCount = 0;
onCompositionSizeReadyListener = listener;
if (viewWidth == 0 || viewHeight == 0) { //直接重新布局UI
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
} else {
float setRatio = (float) compWidth / (float) compHeight;
float setViewRatio = (float) viewWidth / (float) viewHeight;
if (setRatio == setViewRatio) { // 如果比例已经相等,不需要再调整,则直接显示.
layoutOk = true;
sendCompositionSizeListener();
} else if (Math.abs(setRatio - setViewRatio) * 1000 < 16.0f) {
if (listener != null) {
layoutOk = true;
sendCompositionSizeListener();
}
} else if (textureRenderView != null) {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
}
}
requestLayoutPreview();
}
private void sendCompositionSizeListener() {
if (onCompositionSizeReadyListener != null) {
onCompositionSizeReadyListener.onSizeReady();
onCompositionSizeReadyListener = null;
}
}
private int requestLayoutCount = 0;
private void checkLayoutSize() {
DisplayMetrics dm = getResources().getDisplayMetrics();
if(viewWidth ==dm.widthPixels){
float wantRatio = (float) compWidth / (float) compHeight;
float padRatio = (float) viewWidth / (float) viewHeight;
if (wantRatio == padRatio) { // 如果比例已经相等,不需要再调整,则直接显示.
layoutOk = true;
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
} else if (Math.abs(wantRatio - padRatio) * 1000 < 16.0f) {
layoutOk = true;
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
}
} else {
textureRenderView.setVideoSize(compWidth, compHeight);
textureRenderView.setVideoSampleAspectRatio(1, 1);
LSOLog.d("checkLayoutSize no right, layout again...");
requestLayoutPreview();
}
}
private void requestLayoutPreview() {
requestLayoutCount++;
if (requestLayoutCount > 3) {
LSOLog.e("LSOCameraView layout view error. return callback");
sendCompositionSizeListener();
if (viewAvailable != null) {
viewAvailable.viewAvailable();
}
} else {
requestLayout();
}
}
//---------------render start--------------------------------------------------------------------------------------
private static boolean isCameraOpened = false;
private int encWidth, encHeight;
private String encPath;
private boolean isFrontCam = false;
private LanSongFilter initFilter = null;
private float encodeSpeed = 1.0f;
private onDrawPadSizeChangedListener sizeChangedCB = null;
private onDrawPadProgressListener drawPadProgressListener = null;
private onDrawPadRecordCompletedListener drawPadRecordCompletedListener = null;
private boolean frameListenerInDrawPad = false;
private onDrawPadCompletedListener drawPadCompletedListener = null;
private onDrawPadErrorListener drawPadErrorListener = null;
private boolean recordMic = false;
private boolean isPauseRefresh = false;
private boolean isPauseRecord = false;
private boolean isZoomEvent = false;
private float touching;
private OnFocusEventListener onFocusListener;
private boolean isCheckPadSize = true;
private boolean isEnableTouch = true;
public void setCameraFront(boolean front) {
isFrontCam = front;
}
public void setEncodeParam(String path) {
encWidth = 1088;
encHeight = 1920;
encPath = path;
}
public void setOnDrawPadProgressListener(onDrawPadProgressListener listener) {
if (renderer != null) {
renderer.setDrawPadProgressListener(listener);
}
drawPadProgressListener = listener;
}
public void getPhotoAsync(onDrawPadSnapShotListener listener) {
if (renderer != null && renderer.isRunning()) {
renderer.setDrawPadSnapShotListener(listener);
renderer.toggleSnapShot(compWidth, compHeight);
} else if (listener != null) {
LSOLog.e("getPhotoAsync error.");
listener.onSnapShot(null, null);
}
}
public void setOnDrawPadCompletedListener(onDrawPadCompletedListener listener) {
if (renderer != null) {
renderer.setDrawPadCompletedListener(listener);
}
drawPadCompletedListener = listener;
}
public void setOnDrawPadErrorListener(onDrawPadErrorListener listener) {
if (renderer != null) {
renderer.setDrawPadErrorListener(listener);
}
drawPadErrorListener = listener;
}
private boolean setupDrawPad() {
if (renderer == null) {
pauseRecord();
pausePreview();
return startDrawPad(true);
} else {
return false;
}
}
private boolean startDrawPad(boolean pauseRecord) {
boolean ret = false;
if (isCameraOpened) {
LSOLog.e("DrawPad opened...");
return false;
}
if (mSurfaceTexture != null && renderer == null) {
// renderer = new LSOCameraRunnable(getContext(), compWidth,compHeight);
renderer = new LSOCameraRunnable(getContext(), viewWidth,viewHeight);
renderer.setCameraParam(isFrontCam, initFilter);
if (renderer != null) {
renderer.setDisplaySurface(textureRenderView, new Surface(mSurfaceTexture));
if (isCheckPadSize) {
encWidth = LanSongUtil.make16Multi(encWidth);
encHeight = LanSongUtil.make16Multi(encHeight);
}
renderer.setEncoderParams(encWidth, encHeight, encPath);
// 设置DrawPad处理的进度监听, 回传的currentTimeUs单位是微秒.
renderer.setDrawPadProgressListener(drawPadProgressListener);
renderer.setDrawPadCompletedListener(drawPadCompletedListener);
renderer.setOutFrameInDrawPad(frameListenerInDrawPad);
renderer.setDrawPadRecordCompletedListener(drawPadRecordCompletedListener);
renderer.setDrawPadErrorListener(drawPadErrorListener);
renderer.setRecordMic(true);
if (pauseRecord || isPauseRecord) {
renderer.pauseRecordDrawPad();
}
if (isPauseRefresh) {
renderer.pauseRefreshDrawPad();
}
renderer.adjustEncodeSpeed(encodeSpeed);
LSOLog.d("starting run draw pad thread...");
ret = renderer.startDrawPad();
isCameraOpened = ret;
if (!ret) {
LSOLog.e("open LSOCameraView error.\n");
} else {
renderer.setDisplaySurface(textureRenderView, new Surface(mSurfaceTexture));
}
}
} else {
LSOLog.w("start draw pad error.");
}
return ret;
}
protected BitmapLayer bgBitmapLayer = null;
protected VideoLayer2 bgVideoLayer = null;
protected BitmapLayer fgBitmapLayer = null;
protected MVLayer2 fgMvLayer = null;
public void setBackGroundBitmap(Bitmap bmp, boolean recycle) {
if (renderer != null && isRunning() && bmp != null && !bmp.isRecycled()) {
removeBackGroundLayer();
bgBitmapLayer = renderer.addBitmapLayer(bmp, recycle);
bgBitmapLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
renderer.bringToBack(bgBitmapLayer);
}
}
public void setBackGroundVideoPath(String path) {
if (renderer != null && isRunning() && path != null) {
removeBackGroundLayer();
bgVideoLayer = renderer.addVideoLayer2(path);
if (bgVideoLayer != null) {
bgVideoLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
bgVideoLayer.setPlayerLooping(true);
bgVideoLayer.setAudioVolume(0.0f);
renderer.bringToBack(bgVideoLayer);
}
}
}
public void setForeGroundBitmap(Bitmap bmp, boolean recycle) {
if (renderer != null && isRunning() && bmp != null && !bmp.isRecycled()) {
removeForeGroundLayer();
fgBitmapLayer = renderer.addBitmapLayer(bmp, recycle);
if (fgBitmapLayer != null) {
fgBitmapLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
}
}
}
public void setForeGroundVideoPath(String colorPath, String maskPath) {
if (renderer != null && isRunning() && colorPath != null && maskPath != null) {
removeForeGroundLayer();
try {
LSOMVAsset2 lsomvAsset2 = new LSOMVAsset2(colorPath, maskPath, false);
fgMvLayer = renderer.addMVLayer(lsomvAsset2);
if (fgMvLayer != null) {
fgMvLayer.setScaleType(LSOScaleType.CROP_FILL_COMPOSITION);
fgMvLayer.setLooping(true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
protected LSOCameraLayer cameraLayer = null;
public void removeBackGroundLayer() {
if (renderer != null) {
renderer.removeLayer(bgBitmapLayer);
bgBitmapLayer = null;
renderer.removeLayer(bgVideoLayer);
bgVideoLayer = null;
}
}
public void removeForeGroundLayer() {
if (renderer != null) {
renderer.removeLayer(fgBitmapLayer);
renderer.removeLayer(fgMvLayer);
fgBitmapLayer = null;
fgMvLayer = null;
}
}
public boolean isGreenMatting() {
return cameraLayer != null && cameraLayer.isGreenMatting();
}
public void setGreenMatting() {
if (cameraLayer != null && !cameraLayer.isGreenMatting()) {
cameraLayer.setGreenMatting();
}
}
public void cancelGreenMatting() {
if (cameraLayer != null && cameraLayer.isGreenMatting()) {
cameraLayer.cancelGreenMatting();
}
}
public void setFilter(LanSongFilter filter) {
if (cameraLayer != null) {
cameraLayer.switchFilterTo(filter);
}
}
public void setBeautyLevel(float level) {
if (cameraLayer != null) {
cameraLayer.setBeautyLevel(level);
}
}
public void changeCamera() {
if (cameraLayer != null && isRunning() && CameraLayer.isSupportFrontCamera()) {
// 先把DrawPad暂停运行.
pausePreview();
cameraLayer.changeCamera();
resumePreview(); // 再次开启.
}
}
public void changeFlash() {
if (cameraLayer != null) {
cameraLayer.changeFlash();
}
}
public void pausePreview() {
if (renderer != null) {
renderer.pauseRefreshDrawPad();
}
isPauseRefresh = true;
}
public void resumePreview() {
if (renderer != null) {
renderer.resumeRefreshDrawPad();
}
isPauseRefresh = false;
}
public void startRecord() {
if (renderer != null) {
renderer.resumeRecordDrawPad();
}
isPauseRecord = false;
}
public void pauseRecord() {
if (renderer != null) {
renderer.pauseRecordDrawPad();
}
isPauseRecord = true;
}
public void resumeRecord() {
if (renderer != null) {
renderer.resumeRecordDrawPad();
}
isPauseRecord = false;
}
public boolean isRecording() {
if (renderer != null) {
boolean ret = renderer.isRecording();
return ret;
} else
return false;
}
public boolean isRunning() {
if (renderer != null)
return renderer.isRunning();
else
return false;
}
public boolean startCamera() {
if (setupDrawPad()) // 建立容器
{
cameraLayer = getCameraLayer();
if (cameraLayer != null) {
renderer.resumeRefreshDrawPad();
isPauseRefresh = false;
cameraLayer.setGreenMatting();
return true;
}
}
return false;
}
public void stopCamera() {
if (renderer != null) {
renderer.release();
renderer = null;
}
isCameraOpened = false;
cameraLayer = null;
bgBitmapLayer = null;
bgVideoLayer = null;
}
public void bringLayerToFront(Layer layer) {
if (renderer != null) {
renderer.bringToFront(layer);
}
}
private LSOCameraLayer getCameraLayer() {
if (renderer != null && renderer.isRunning())
return renderer.getCameraLayer();
else {
LSOLog.e("getCameraLayer error.");
return null;
}
}
public BitmapLayer addBitmapLayer(Bitmap bmp) {
if (bmp != null) {
if (renderer != null) {
return renderer.addBitmapLayer(bmp, null);
}
}
LSOLog.e("addBitmapLayer error.");
return null;
}
/**
* 增加一个gif图层.
*
* @param gifPath gif的绝对地址,
* @return
*/
public GifLayer addGifLayer(String gifPath) {
if (renderer != null)
return renderer.addGifLayer(gifPath);
else {
LSOLog.e("addGifLayer error");
return null;
}
}
public GifLayer addGifLayer(int resId) {
if (renderer != null)
return renderer.addGifLayer(resId);
else {
LSOLog.e("addGifLayer error");
return null;
}
}
public MVLayer2 addMVLayer(LSOMVAsset2 mvAsset) {
if (renderer != null)
return renderer.addMVLayer(mvAsset);
else {
LSOLog.e("addMVLayer error render is null");
return null;
}
}
public void removeLayer(Layer layer) {
if (layer != null) {
if (renderer != null)
renderer.removeLayer(layer);
else {
LSOLog.e("removeLayer error render is null");
}
}
}
float x1 = 0;
float x2 = 0;
float y1 = 0;
float y2 = 0;
public boolean onTouchEvent(MotionEvent event) {
if (!isEnableTouch) { // 如果禁止了touch事件,则直接返回false;
return false;
}
if (getCameraLayer() == null) {
return false;
}
switch (event.getAction() & MotionEvent.ACTION_MASK) {
// 手指压下屏幕
case MotionEvent.ACTION_DOWN:
isZoomEvent = false;
x1 = event.getX();
y1 = event.getY();
break;
case MotionEvent.ACTION_POINTER_DOWN:
// 计算两个手指间的距离
if (isRunning()) {
touching = spacing(event);
isZoomEvent = true;
}
break;
case MotionEvent.ACTION_MOVE:
if (isZoomEvent && isRunning()) {
LSOCameraLayer layer = getCameraLayer();
if (layer != null && event.getPointerCount() >= 2) {// 触屏两个点时才执行
float endDis = spacing(event);// 结束距离
int scale = (int) ((endDis - touching) / 10f); // 每变化10f
// zoom变1, 拉近拉远;
if (scale >= 1 || scale <= -1) {
int zoom = layer.getZoom() + scale;
layer.setZoom(zoom);
touching = endDis;
}
}
}
break;
// 手指离开屏幕
case MotionEvent.ACTION_UP:
if (isRunning()) {
if (!isZoomEvent) {
LSOCameraLayer layer = getCameraLayer();
if (layer != null) {
float x = event.getX();
float y = event.getY();
if (renderer != null) {
x = renderer.getTouchX(x);
y = renderer.getTouchY(y);
}
layer.doFocus((int) x, (int) y);
if (onFocusListener != null) {
onFocusListener.onFocus((int) x, (int) y);
}
}
}
}
isZoomEvent = false;
break;
}
return true;
}
private float spacing(MotionEvent event) {
if (event == null) {
return 0;
}
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
public void setCameraFocusListener(OnFocusEventListener listener) {
this.onFocusListener = listener;
}
public void setNotCheckDrawPadSize() {
isCheckPadSize = false;
}
public void setEnableTouch(boolean enable) {
isEnableTouch = enable;
}
public interface OnFocusEventListener {
void onFocus(int x, int y);
}
/**
* 释放所有.
*/
public void release() {
// cancel();
}
}
| 24,529 | 0.564584 | 0.559945 | 766 | 30.523499 | 23.520977 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509138 | false | false | 9 |
33895aed39ba6388aef9f5bb949847c2af873a63 | 29,996,051,621,636 | fc782d99d56928dc2a37d177f316cb72c8bfe741 | /src/main/java/com/computationalproteomics/icelogoserver/webapplication/IceLogoWepAppSingelton.java | a32f40960c7619774a80d318b7fa31293d392bb2 | [] | no_license | compomics/icelogoserver | https://github.com/compomics/icelogoserver | e5a51a96210252fd3795352ae79511d5f2a31174 | 69bad0bb0db74d1e8ec8e5105ffa418a018c8dd9 | refs/heads/master | 2021-03-12T19:40:58.173000 | 2018-01-18T10:15:17 | 2018-01-18T10:15:17 | 32,521,966 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by IntelliJ IDEA.
* User: Niklaas
* Date: 11-Oct-2009
* Time: 09:47:45
* To change this template use File | Settings | File Templates.
*/
package com.computationalproteomics.icelogoserver.webapplication;
import com.compomics.icelogo.core.dbComposition.SwissProtComposition;
import java.util.Vector;
/**
* The IceLogoWepAppSingelton. This singelton will hold all the SwissProtCompositions for all the species.
*/
public class IceLogoWepAppSingelton {
/**
* The instance
*/
private static IceLogoWepAppSingelton ourInstance = new IceLogoWepAppSingelton();
/**
* Vector with the possible compositions
*/
private Vector<SwissProtComposition> iAllSpecies;
public static IceLogoWepAppSingelton getInstance() {
return ourInstance;
}
private IceLogoWepAppSingelton() {
}
/**
* Set the compositions
* @param lSpecies Vector with the SwissProtCompositions
*/
public void setCompositions(Vector<SwissProtComposition> lSpecies){
iAllSpecies = lSpecies;
}
/**
* Check if the species compositions are set
* @return Boolean is true if the species are set
*/
public boolean speciesSet(){
if(iAllSpecies == null){
return false;
}
return true;
}
/**
* Get a specific SwissProtComposition for a specific species
* @param aSpecies String with the scientific name of the species for the asked composition
* @return SwissProtComposition
*/
public SwissProtComposition getComposition(String aSpecies){
for(int i = 0; i<iAllSpecies.size(); i ++){
if(iAllSpecies.get(i).getSpecieName().equalsIgnoreCase(aSpecies)){
return iAllSpecies.get(i);
}
}
return null;
}
}
| UTF-8 | Java | 1,894 | java | IceLogoWepAppSingelton.java | Java | [
{
"context": "/**\r\n * Created by IntelliJ IDEA.\r\n * User: Niklaas\r\n * Date: 11-Oct-2009\r\n * Time: 09:47:45\r\n * To c",
"end": 51,
"score": 0.9994549751281738,
"start": 44,
"tag": "NAME",
"value": "Niklaas"
}
] | null | [] | /**
* Created by IntelliJ IDEA.
* User: Niklaas
* Date: 11-Oct-2009
* Time: 09:47:45
* To change this template use File | Settings | File Templates.
*/
package com.computationalproteomics.icelogoserver.webapplication;
import com.compomics.icelogo.core.dbComposition.SwissProtComposition;
import java.util.Vector;
/**
* The IceLogoWepAppSingelton. This singelton will hold all the SwissProtCompositions for all the species.
*/
public class IceLogoWepAppSingelton {
/**
* The instance
*/
private static IceLogoWepAppSingelton ourInstance = new IceLogoWepAppSingelton();
/**
* Vector with the possible compositions
*/
private Vector<SwissProtComposition> iAllSpecies;
public static IceLogoWepAppSingelton getInstance() {
return ourInstance;
}
private IceLogoWepAppSingelton() {
}
/**
* Set the compositions
* @param lSpecies Vector with the SwissProtCompositions
*/
public void setCompositions(Vector<SwissProtComposition> lSpecies){
iAllSpecies = lSpecies;
}
/**
* Check if the species compositions are set
* @return Boolean is true if the species are set
*/
public boolean speciesSet(){
if(iAllSpecies == null){
return false;
}
return true;
}
/**
* Get a specific SwissProtComposition for a specific species
* @param aSpecies String with the scientific name of the species for the asked composition
* @return SwissProtComposition
*/
public SwissProtComposition getComposition(String aSpecies){
for(int i = 0; i<iAllSpecies.size(); i ++){
if(iAllSpecies.get(i).getSpecieName().equalsIgnoreCase(aSpecies)){
return iAllSpecies.get(i);
}
}
return null;
}
}
| 1,894 | 0.637804 | 0.63094 | 69 | 25.449276 | 26.88221 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.217391 | false | false | 9 |
e73ce64a44042859a01546e531bea64f2db6f849 | 10,058,813,425,733 | fa15d2becaf80b4f17d6db6b3ff5cf66b4e2f62a | /app/src/main/java/com/depex/odepto/CardLabelViewAdapter.java | db0f31610570c5ae5155499533957d21c20df862 | [] | no_license | kapil061287/mypro | https://github.com/kapil061287/mypro | 23c724a9ba455d8b1061cf788559a2a447dae271 | c8d4bbea0fa9fdb52c7c7f1dd803d31471bff5d7 | refs/heads/master | 2021-05-01T18:51:56.173000 | 2018-04-04T10:46:33 | 2018-04-04T10:46:33 | 121,010,091 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.depex.odepto;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.List;
public class CardLabelViewAdapter extends RecyclerView.Adapter<CardLabelViewAdapter.CardLabelViewholder>{
List<Label> labelButtons;
Activity activity;
public CardLabelViewAdapter(List<Label> labelButtons, Activity activity ){
this.labelButtons=labelButtons;
this.activity=activity;
}
@Override
public CardLabelViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=activity.getLayoutInflater().inflate(R.layout.card_label_layout_list_for_recyclerview, null, false);
return new CardLabelViewholder(view);
}
@Override
public void onBindViewHolder(final CardLabelViewholder holder, int position) {
Label cardLabelButton=labelButtons.get(position);
GradientDrawable drawable=(GradientDrawable) holder.card_label_color_button.getBackground();
drawable.setColor(Color.parseColor(cardLabelButton.getColor()));
//holder.card_label_color_button.setBackgroundColor(Color.parseColor(cardLabelButton.getColor()));
}
@Override
public int getItemCount() {
return labelButtons.size();
}
class CardLabelViewholder extends RecyclerView.ViewHolder {
View labelView;
Button card_label_color_button;
public CardLabelViewholder(View labelView) {
super(labelView);
this.labelView=labelView;
card_label_color_button=labelView.findViewById(R.id.card_label_color_button);
}
}
} | UTF-8 | Java | 1,912 | java | CardLabelViewAdapter.java | Java | [] | null | [] | package com.depex.odepto;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.List;
public class CardLabelViewAdapter extends RecyclerView.Adapter<CardLabelViewAdapter.CardLabelViewholder>{
List<Label> labelButtons;
Activity activity;
public CardLabelViewAdapter(List<Label> labelButtons, Activity activity ){
this.labelButtons=labelButtons;
this.activity=activity;
}
@Override
public CardLabelViewholder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=activity.getLayoutInflater().inflate(R.layout.card_label_layout_list_for_recyclerview, null, false);
return new CardLabelViewholder(view);
}
@Override
public void onBindViewHolder(final CardLabelViewholder holder, int position) {
Label cardLabelButton=labelButtons.get(position);
GradientDrawable drawable=(GradientDrawable) holder.card_label_color_button.getBackground();
drawable.setColor(Color.parseColor(cardLabelButton.getColor()));
//holder.card_label_color_button.setBackgroundColor(Color.parseColor(cardLabelButton.getColor()));
}
@Override
public int getItemCount() {
return labelButtons.size();
}
class CardLabelViewholder extends RecyclerView.ViewHolder {
View labelView;
Button card_label_color_button;
public CardLabelViewholder(View labelView) {
super(labelView);
this.labelView=labelView;
card_label_color_button=labelView.findViewById(R.id.card_label_color_button);
}
}
} | 1,912 | 0.743201 | 0.742155 | 56 | 33.160713 | 31.695976 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.589286 | false | false | 9 |
433a7a71a85207af1936d4261c138952845b4225 | 20,976,620,302,549 | 006114bd7ae3b90a1e38cdbab54b6f70837b18e6 | /src/main/java/pe/edu/upeu/SISRA/service/DocumentoService.java | 64a9747cfd24762afd1a2a3541606f63d51b9cd5 | [] | no_license | viviansolis/Proyecto_Bakend | https://github.com/viviansolis/Proyecto_Bakend | 3cab9931dd26a6e3643549b6178741cb92068be8 | 1f4dc34cfc2b0cadda9fd2a0ab8eef582c3f4655 | refs/heads/master | 2023-01-28T16:55:34.100000 | 2020-12-15T16:24:49 | 2020-12-15T16:24:49 | 321,691,999 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pe.edu.upeu.SISRA.service;
import java.util.Map;
public interface DocumentoService {
Map<String, Object> read(int id_req_asc);
}
| UTF-8 | Java | 144 | java | DocumentoService.java | Java | [] | null | [] | package pe.edu.upeu.SISRA.service;
import java.util.Map;
public interface DocumentoService {
Map<String, Object> read(int id_req_asc);
}
| 144 | 0.736111 | 0.736111 | 9 | 15 | 16.878653 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.777778 | false | false | 9 |
5f3ace1aa3b02a9c1f514f4201b123405288f8f3 | 6,975,026,928,745 | 678eba9d03b2404bda49eeb8f979a8ca793246cf | /robot/src/main/java/lujgame/robot/robot/config/RobotConfig.java | 4337fcee30a39eddb246ba3260b7910b50b86bf7 | [] | no_license | lowZoom/LujGame | https://github.com/lowZoom/LujGame | 7456b6c36ce8b97a5b755c78686830bad3fb47cd | 5675751183e62449866317f17c63e21a523e6176 | refs/heads/master | 2020-04-05T08:53:27.638000 | 2018-03-25T10:12:55 | 2018-03-25T10:12:55 | 81,704,611 | 2 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lujgame.robot.robot.config;
import com.typesafe.config.Config;
public class RobotConfig {
public enum Abstract {
YES, NO,
}
public RobotConfig(String name, Config config, Abstract anAbstract, String anExtends) {
_name = name;
_config = config;
_abstract = anAbstract;
_extends = anExtends;
}
public String getName() {
return _name;
}
public Config getConfig() {
return _config;
}
public Abstract getAbstract() {
return _abstract;
}
public String getExtends() {
return _extends;
}
private final String _name;
private final Config _config;
private final Abstract _abstract;
private final String _extends;
}
| UTF-8 | Java | 693 | java | RobotConfig.java | Java | [] | null | [] | package lujgame.robot.robot.config;
import com.typesafe.config.Config;
public class RobotConfig {
public enum Abstract {
YES, NO,
}
public RobotConfig(String name, Config config, Abstract anAbstract, String anExtends) {
_name = name;
_config = config;
_abstract = anAbstract;
_extends = anExtends;
}
public String getName() {
return _name;
}
public Config getConfig() {
return _config;
}
public Abstract getAbstract() {
return _abstract;
}
public String getExtends() {
return _extends;
}
private final String _name;
private final Config _config;
private final Abstract _abstract;
private final String _extends;
}
| 693 | 0.670996 | 0.670996 | 41 | 15.902439 | 17.509308 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.463415 | false | false | 9 |
15776c57c6914eca40d2740630d6dc6e9ef97af8 | 12,000,138,662,440 | 7234a8ff870d5cfab3779d8fd19915d93229bab4 | /src/main/java/WordPattern.java | e9e88237cc32f90761513ad485043fbcf097fcae | [] | no_license | snehasishroy/leetcode-practice | https://github.com/snehasishroy/leetcode-practice | 6b723b2366cdacd9864e2807f99d4e9bbd66f8cb | 2116625b77af211897036df0539df257826b1245 | refs/heads/master | 2023-03-10T03:06:04.726000 | 2023-03-08T19:42:51 | 2023-03-08T19:42:51 | 181,065,505 | 15 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/word-pattern/
* <pre>
* Given a pattern and a string s, find if s follows the same pattern.
*
* Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
*
* Input: pattern = "abba", s = "dog cat cat dog"
* Output: true
*
* Input: pattern = "abba", s = "dog cat cat fish"
* Output: false
*
* Input: pattern = "aaaa", s = "dog cat cat dog"
* Output: false
*
* Constraints:
* 1 <= pattern.length <= 300
* pattern contains only lower-case English letters.
* 1 <= s.length <= 3000
* s contains only lowercase English letters and spaces ' '.
* s does not contain any leading or trailing spaces.
* All the words in s are separated by a single space.
* </pre>
*/
public class WordPattern {
/**
* Approach: Keep track of the mapping from every char in pattern -> word in str and every string in str -> every char in pattern.
* {@link WordPattern2} {@link IsomorphicStrings}
*/
public boolean wordPattern(String pattern, String str) {
String[] split = str.split(" ");
if (pattern.length() != split.length) {
return false;
}
int n = pattern.length();
Map<Character, String> forward = new HashMap<>();
Map<String, Character> reverse = new HashMap<>();
for (int i = 0; i < n; i++) {
char c = pattern.charAt(i);
String word = split[i];
if (!forward.getOrDefault(c, word).equals(word) || !reverse.getOrDefault(word, c).equals(c)) {
return false;
} else {
forward.put(c, word);
reverse.put(word, c);
}
}
return true;
}
}
| UTF-8 | Java | 1,795 | java | WordPattern.java | Java | [] | null | [] | import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/word-pattern/
* <pre>
* Given a pattern and a string s, find if s follows the same pattern.
*
* Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
*
* Input: pattern = "abba", s = "dog cat cat dog"
* Output: true
*
* Input: pattern = "abba", s = "dog cat cat fish"
* Output: false
*
* Input: pattern = "aaaa", s = "dog cat cat dog"
* Output: false
*
* Constraints:
* 1 <= pattern.length <= 300
* pattern contains only lower-case English letters.
* 1 <= s.length <= 3000
* s contains only lowercase English letters and spaces ' '.
* s does not contain any leading or trailing spaces.
* All the words in s are separated by a single space.
* </pre>
*/
public class WordPattern {
/**
* Approach: Keep track of the mapping from every char in pattern -> word in str and every string in str -> every char in pattern.
* {@link WordPattern2} {@link IsomorphicStrings}
*/
public boolean wordPattern(String pattern, String str) {
String[] split = str.split(" ");
if (pattern.length() != split.length) {
return false;
}
int n = pattern.length();
Map<Character, String> forward = new HashMap<>();
Map<String, Character> reverse = new HashMap<>();
for (int i = 0; i < n; i++) {
char c = pattern.charAt(i);
String word = split[i];
if (!forward.getOrDefault(c, word).equals(word) || !reverse.getOrDefault(word, c).equals(c)) {
return false;
} else {
forward.put(c, word);
reverse.put(word, c);
}
}
return true;
}
}
| 1,795 | 0.592758 | 0.58663 | 54 | 32.240742 | 29.058647 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.537037 | false | false | 9 |
daf2013479ad41d2f20428e032d7a97ea00886c7 | 6,485,400,626,161 | 57fd725f28e4c90612d03d792592ca10bc23a55c | /Restaurant.java | 72022cdea4378f15517eaf88f0695de7a6acdcbc | [] | no_license | barka91/Mini-Projet-Java | https://github.com/barka91/Mini-Projet-Java | b8a74eff010ad3779bf9a7d40bcc61d1b9de095f | 353531e274fa6f7a28c376761f61918921ac2b70 | refs/heads/master | 2023-01-10T09:48:16.309000 | 2020-11-17T20:10:36 | 2020-11-17T20:10:36 | 313,718,302 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Restaurant {
private boolean etat;
private Point position;
private Plat Commande;
public Restaurant(x,y){
etat=True;
position=new Point(x,y);
Commande=plat();
}
}
| UTF-8 | Java | 221 | java | Restaurant.java | Java | [] | null | [] | public class Restaurant {
private boolean etat;
private Point position;
private Plat Commande;
public Restaurant(x,y){
etat=True;
position=new Point(x,y);
Commande=plat();
}
}
| 221 | 0.606335 | 0.606335 | 11 | 19.09091 | 10.974802 | 32 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.727273 | false | false | 9 |
9244dfffe24853964959163d6e553c5fdec7ef39 | 23,794,118,828,880 | e4a8a9d6a61d57cfa0aaa37ad0b1ee97ae11a765 | /slace-app/src/main/java/ua/yware/slace/web/rest/form/CreateUserForm.java | 30450fe49f3b7e90dbe34f66fd5ebbe6ac9316bf | [] | no_license | Yneth/slace | https://github.com/Yneth/slace | 0922fb86929ec8c4bd97f39ee6db8e10ef56c997 | eb5573524f675972101c934ef037088d1b37608a | refs/heads/master | 2021-07-13T14:55:03.686000 | 2017-06-17T08:54:23 | 2017-06-17T08:54:23 | 96,470,119 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.yware.slace.web.rest.form;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CreateUserForm {
private String login;
private String password;
private String email;
private String phone;
private String firstName;
private String lastName;
private String city;
private String about;
}
| UTF-8 | Java | 358 | java | CreateUserForm.java | Java | [
{
"context": "il;\n\n private String phone;\n\n private String firstName;\n\n private String lastName;\n\n private Strin",
"end": 270,
"score": 0.9432174563407898,
"start": 261,
"tag": "NAME",
"value": "firstName"
},
{
"context": "\n private String firstName;\n\n pr... | null | [] | package ua.yware.slace.web.rest.form;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CreateUserForm {
private String login;
private String password;
private String email;
private String phone;
private String firstName;
private String lastName;
private String city;
private String about;
}
| 358 | 0.715084 | 0.715084 | 26 | 12.769231 | 13.062888 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 9 |
9afab5c9b094e57b07c2e77124de524eb9f4629e | 31,714,038,542,051 | c1d05faa23796eeb23ce6c238361fcedc98b8430 | /src/main/java/com/andredealmei/sgos/persistence/entity/Situacao.java | 32f4a2a0af60a6ae18b0f293456c315c3ad61fac | [] | no_license | andredealmei/SGOS | https://github.com/andredealmei/SGOS | 7b1090aaba5b6ee79eff235718ddaf342e6bb7bb | 5062ab449c46c9e1f4b63dfe6ade08c5372ab719 | refs/heads/master | 2018-07-03T02:58:59.738000 | 2018-06-29T16:25:11 | 2018-06-29T16:25:11 | 133,174,166 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.andredealmei.sgos.persistence.entity;
public enum Situacao {
ABERTO,
ORCAMENTO,
EM_ANDAMENTO,
AGUARDANDO_RETORNO_CLIENTE,
AGUARDANDO_RETIRADA,
FINALIZADO,
CANCELADO
}
| UTF-8 | Java | 211 | java | Situacao.java | Java | [
{
"context": "package com.andredealmei.sgos.persistence.entity;\n\npublic enum Situacao {\n",
"end": 24,
"score": 0.9653615355491638,
"start": 17,
"tag": "USERNAME",
"value": "dealmei"
}
] | null | [] | package com.andredealmei.sgos.persistence.entity;
public enum Situacao {
ABERTO,
ORCAMENTO,
EM_ANDAMENTO,
AGUARDANDO_RETORNO_CLIENTE,
AGUARDANDO_RETIRADA,
FINALIZADO,
CANCELADO
}
| 211 | 0.701422 | 0.701422 | 14 | 14.071428 | 13.760525 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
5cce8aff7aa474724b10a58745af28fb0401654f | 3,607,772,557,401 | d145e0a7c747f9d550d8e19842589dc2a9ca8f6b | /Minigames/src/main/java/au/com/mineauz/minigames/commands/set/SetLivesCommand.java | 8c6eaa0fda30c00cdcc392e1548337b4b9ce5e01 | [
"MIT"
] | permissive | AddstarMC/Minigames | https://github.com/AddstarMC/Minigames | 4f05eef4e152afc347936aed183393af961f1e37 | a323148b32d5eea9b391b6d52ea265ebdbedcaac | refs/heads/master | 2023-08-17T01:35:06.169000 | 2023-07-14T02:52:42 | 2023-07-14T02:52:42 | 7,033,568 | 75 | 79 | MIT | false | 2023-08-03T11:36:14 | 2012-12-06T10:10:27 | 2023-06-27T08:46:08 | 2023-08-03T11:36:13 | 8,808 | 72 | 61 | 38 | Java | false | false | package au.com.mineauz.minigames.commands.set;
import au.com.mineauz.minigames.commands.ICommand;
import au.com.mineauz.minigames.minigame.Minigame;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class SetLivesCommand implements ICommand {
@Override
public String getName() {
return "lives";
}
@Override
public String[] getAliases() {
return null;
}
@Override
public boolean canBeConsole() {
return true;
}
@Override
public String getDescription() {
return "Sets the amount of lives a player has in the Minigame. If they run out, they are booted from the game. 0 means unlimited.";
}
@Override
public String[] getParameters() {
return null;
}
@Override
public String[] getUsage() {
return new String[]{"/minigame set <Minigame> lives <number>"};
}
@Override
public String getPermissionMessage() {
return "You do not have permission to set the number of lives in a Minigame!";
}
@Override
public String getPermission() {
return "minigame.set.lives";
}
@Override
public boolean onCommand(CommandSender sender, Minigame minigame,
String label, String[] args) {
if (args != null) {
if (args[0].matches("[0-9]+")) {
int lives = Integer.parseInt(args[0]);
minigame.setLives(lives);
sender.sendMessage(ChatColor.GRAY + minigame.getName(false) + "'s lives has been set to " + lives);
return true;
}
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Minigame minigame,
String alias, String[] args) {
return null;
}
}
| UTF-8 | Java | 1,881 | java | SetLivesCommand.java | Java | [] | null | [] | package au.com.mineauz.minigames.commands.set;
import au.com.mineauz.minigames.commands.ICommand;
import au.com.mineauz.minigames.minigame.Minigame;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class SetLivesCommand implements ICommand {
@Override
public String getName() {
return "lives";
}
@Override
public String[] getAliases() {
return null;
}
@Override
public boolean canBeConsole() {
return true;
}
@Override
public String getDescription() {
return "Sets the amount of lives a player has in the Minigame. If they run out, they are booted from the game. 0 means unlimited.";
}
@Override
public String[] getParameters() {
return null;
}
@Override
public String[] getUsage() {
return new String[]{"/minigame set <Minigame> lives <number>"};
}
@Override
public String getPermissionMessage() {
return "You do not have permission to set the number of lives in a Minigame!";
}
@Override
public String getPermission() {
return "minigame.set.lives";
}
@Override
public boolean onCommand(CommandSender sender, Minigame minigame,
String label, String[] args) {
if (args != null) {
if (args[0].matches("[0-9]+")) {
int lives = Integer.parseInt(args[0]);
minigame.setLives(lives);
sender.sendMessage(ChatColor.GRAY + minigame.getName(false) + "'s lives has been set to " + lives);
return true;
}
}
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Minigame minigame,
String alias, String[] args) {
return null;
}
}
| 1,881 | 0.600744 | 0.598086 | 73 | 24.767124 | 27.60808 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369863 | false | false | 9 |
16ba03e69ef96bda21f2ee82f17f4db364949eb3 | 19,920,058,342,077 | 84d8aafd90d33e329949f686a68bb884d859ec07 | /src/test/java/org/generationcp/middleware/manager/OntologyDataManagerImplIntegrationTest.java | bbf249bc0edac8521b9f80b12a449dccbb9f1199 | [] | no_license | qatestuser2019/Middleware | https://github.com/qatestuser2019/Middleware | b27d3395a948d3873efa9b38b0291d78788889e8 | a562605fcdb2fcdf4cb17562e1e39279de683bc7 | refs/heads/master | 2022-02-09T05:10:47.493000 | 2019-07-22T14:41:03 | 2019-07-22T14:41:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public License (http://bit.ly/8Ztv8M) and the provisions of Part F
* of the Generation Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.middleware.manager;
import org.apache.commons.lang3.RandomStringUtils;
import org.generationcp.middleware.ContextHolder;
import org.generationcp.middleware.IntegrationTestBase;
import org.generationcp.middleware.dao.oms.CVTermDao;
import org.generationcp.middleware.domain.dms.Enumeration;
import org.generationcp.middleware.domain.dms.PhenotypicType;
import org.generationcp.middleware.domain.dms.StandardVariable;
import org.generationcp.middleware.domain.dms.StandardVariableSummary;
import org.generationcp.middleware.domain.dms.VariableConstraints;
import org.generationcp.middleware.domain.oms.CvId;
import org.generationcp.middleware.domain.oms.Property;
import org.generationcp.middleware.domain.oms.Term;
import org.generationcp.middleware.domain.oms.TermId;
import org.generationcp.middleware.domain.oms.TermSummary;
import org.generationcp.middleware.domain.oms.TraitClassReference;
import org.generationcp.middleware.domain.ontology.DataType;
import org.generationcp.middleware.exceptions.MiddlewareQueryException;
import org.generationcp.middleware.pojos.oms.CVTerm;
import org.generationcp.middleware.utils.test.OntologyDataManagerImplTestConstants;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
public class OntologyDataManagerImplIntegrationTest extends IntegrationTestBase {
private static final String PROGRAM_UUID = UUID.randomUUID().toString();
@BeforeClass
public static void setUpOnce() {
// Variable caching relies on the context holder to determine current crop database in use
ContextHolder.setCurrentCrop("maize");
ContextHolder.setCurrentProgram(PROGRAM_UUID);
}
private OntologyDataManagerImpl ontologyDataManager;
private CVTermDao cvTermDao;
@Before
public void init() {
this.ontologyDataManager = new OntologyDataManagerImpl(this.sessionProvder);
this.cvTermDao = new CVTermDao();
this.cvTermDao.setSession(this.sessionProvder.getSession());
}
@Test
public void testGetCvTermById() {
final Term term = this.ontologyDataManager.getTermById(6040);
Assert.assertNotNull(term);
}
@Test
public void testGetStandardVariable() {
final StandardVariable standardVariable =
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
Assert.assertNotNull(standardVariable);
}
@Test
public void getStandVariableList() {
final StandardVariable standardVariable1 = this.createStandardVariable("StandardVariable1");
final StandardVariable standardVariable2 = this.createStandardVariable("StandardVariable2");
final List<Integer> ids = Arrays.asList(standardVariable1.getId(), standardVariable2.getId());
final List<StandardVariable> standardVariables = this.ontologyDataManager.getStandardVariables(ids, PROGRAM_UUID);
Assert.assertEquals(2, standardVariables.size());
Assert.assertEquals(standardVariable1.getId(), standardVariables.get(0).getId());
Assert.assertEquals(standardVariable2.getId(), standardVariables.get(1).getId());
}
@Test
public void testGetStandardVariableSummaries() {
final StandardVariable standardVariable1 = this.createStandardVariable("StandardVariable1");
final StandardVariable standardVariable2 = this.createStandardVariable("StandardVariable2");
final List<Integer> ids = Arrays.asList(standardVariable1.getId(), standardVariable2.getId());
final List<StandardVariableSummary> summaries = this.ontologyDataManager.getStandardVariableSummaries(ids);
Assert.assertNotNull(summaries);
Assert.assertEquals(ids.size(), summaries.size());
for (final StandardVariableSummary summary : summaries) {
Assert.assertTrue(ids.contains(summary.getId()));
}
}
@Test
public void testGetStandardVariableSummary() {
// First create a new Standardvariable
final StandardVariable testStandardVariable = this.createStandardVariable("TestVariable");
// Load summary from the view based method
final StandardVariableSummary summary = this.ontologyDataManager.getStandardVariableSummary(testStandardVariable.getId());
Assert.assertNotNull(summary);
// Make sure that the summary data loaded from view matches with details
// data loaded using the usual method.
this.assertVariableDataMatches(testStandardVariable, summary);
}
private void assertVariableDataMatches(final StandardVariable standardVariable, final StandardVariableSummary summary) {
Assert.assertEquals(new Integer(standardVariable.getId()), summary.getId());
Assert.assertEquals(standardVariable.getName(), summary.getName());
Assert.assertEquals(standardVariable.getDescription(), summary.getDescription());
this.assertTermDataMatches(standardVariable.getProperty(), summary.getProperty());
this.assertTermDataMatches(standardVariable.getMethod(), summary.getMethod());
this.assertTermDataMatches(standardVariable.getScale(), summary.getScale());
this.assertTermDataMatches(standardVariable.getDataType(), summary.getDataType());
Assert.assertEquals(standardVariable.getPhenotypicType(), summary.getPhenotypicType());
}
private void assertTermDataMatches(final Term termDetails, final TermSummary termSummary) {
Assert.assertEquals(new Integer(termDetails.getId()), termSummary.getId());
Assert.assertEquals(termDetails.getName(), termSummary.getName());
Assert.assertEquals(termDetails.getDefinition(), termSummary.getDefinition());
}
@Test
public void testCopyStandardVariable() {
final StandardVariable stdVar =
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
final StandardVariable stdVar2 = stdVar.copy();
Assert.assertNotSame(stdVar.getId(), stdVar2.getId());
Assert.assertSame(stdVar.getProperty(), stdVar2.getProperty());
Assert.assertSame(stdVar.getScale(), stdVar2.getScale());
Assert.assertSame(stdVar.getMethod(), stdVar2.getMethod());
Assert.assertSame(stdVar.getDataType(), stdVar2.getDataType());
Assert.assertSame(stdVar.getPhenotypicType(), stdVar2.getPhenotypicType());
Assert.assertSame(stdVar.getConstraints(), stdVar2.getConstraints());
if (stdVar.getName() != null) {
Assert.assertTrue(stdVar.getName().equals(stdVar2.getName()));
}
if (stdVar.getDescription() != null) {
Assert.assertTrue(stdVar.getDescription().equals(stdVar2.getDescription()));
}
Assert.assertSame(stdVar.getEnumerations(), stdVar2.getEnumerations());
}
@Test
public void testStandardVariableCache() {
// First call to getStandardVariable() will put the value to the cache
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
// Second (and subsequent) calls will retrieve the value from the cache
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
}
@Test
public void testNameSynonyms() {
final StandardVariable sv = this.ontologyDataManager.getStandardVariable(8383, PROGRAM_UUID);
sv.print(IntegrationTestBase.INDENT);
}
@Test
public void testAddStandardVariable() {
// create new trait
final String propertyName = "property name " + new Random().nextInt(10000);
this.ontologyDataManager.addProperty(propertyName, "test property", 1087);
final StandardVariable stdVariable = new StandardVariable();
stdVariable.setName("variable name " + new Random().nextInt(10000));
stdVariable.setDescription("variable description");
// stdVariable.setProperty(new Term(2002, "User", "Database user"));
stdVariable.setProperty(this.ontologyDataManager.findTermByName(propertyName, CvId.PROPERTIES));
stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned"));
stdVariable.setScale(new Term(6000, "DBCV", "Controlled vocabulary from a database"));
stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values"));
stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class"));
stdVariable.setEnumerations(new ArrayList<Enumeration>());
stdVariable.getEnumerations().add(new Enumeration(10000, "N", "Nursery", 1));
stdVariable.getEnumerations().add(new Enumeration(10001, "HB", "Hybridization Nursery", 2));
stdVariable.getEnumerations().add(new Enumeration(10002, "PN", "Pedigree Nursery", 3));
stdVariable.setConstraints(new VariableConstraints(100.0, 999.0));
stdVariable.setCropOntologyId("CROP-TEST");
try {
this.ontologyDataManager.addStandardVariable(stdVariable, PROGRAM_UUID);
} catch (final MiddlewareQueryException e) {
if (e.getMessage().contains("already exists")) {
// Ignore. The test run successfully before.
}
}
}
@Test(expected = MiddlewareQueryException.class)
public void testAddStandardVariableWithMissingScalePropertyMethod() {
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName("Test SPM" + new Random().nextInt(10000));
standardVariable.setDescription("Std variable with new scale, property, method");
final Term newProperty = new Term(2451, "Environment", "Environment");
Term property = this.ontologyDataManager.findTermByName(newProperty.getName(), CvId.PROPERTIES);
if (property == null) {
property = newProperty;
}
final Term newScale = new Term(6020, "Text", "Text");
Term scale = this.ontologyDataManager.findTermByName(newScale.getName(), CvId.SCALES);
if (scale == null) {
scale = newScale;
}
final Term newMethod = new Term(0, "Test Method", "Test Method");
Term method = this.ontologyDataManager.findTermByName(newMethod.getName(), CvId.METHODS);
if (method == null) {
method = newMethod;
}
standardVariable.setProperty(property);
standardVariable.setScale(scale);
standardVariable.setMethod(method);
this.ontologyDataManager.addStandardVariable(standardVariable, PROGRAM_UUID);
}
@Test
public void testAddStandardVariableEnumeration() {
final int standardVariableId = OntologyDataManagerImplTestConstants.CATEGORICAL_VARIABLE_TERM_ID;
final String name = "Name_" + new Random().nextInt(10000);
final String description = "Test Valid Value" + new Random().nextInt(10000);
StandardVariable standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
final Enumeration validValue = new Enumeration(null, name, description, 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
}
@Test
public void testUpdateStandardVariableEnumeration() {
// Case 1: NEW VALID VALUE
final int standardVariableId = OntologyDataManagerImplTestConstants.CATEGORICAL_VARIABLE_TERM_ID;
String name = "Name_" + new Random().nextInt(10000);
String description = "Test Valid Value" + new Random().nextInt(10000);
StandardVariable standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Enumeration validValue = new Enumeration(null, name, description, standardVariable.getEnumerations().size() + 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
final Integer validValueGeneratedId1 = standardVariable.getEnumerationByName(name).getId();
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
// Case 2: UPDATE CENTRAL VALID VALUE
final Integer validValueId = OntologyDataManagerImplTestConstants.CROP_SESCND_VALID_VALUE_FROM_CENTRAL;
name = "Name_" + new Random().nextInt(10000);
description = "Test Valid Value " + new Random().nextInt(10000); // Original
// value
// in
// central:
// "Moderately well exserted"
validValue = new Enumeration(validValueId, name, description, 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
// Case 3: UPDATE LOCAL VALID VALUE
description = "Test Valid Value " + new Random().nextInt(10000);
validValue.setDescription(description);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertTrue(standardVariable.getEnumeration(validValue.getId()).getDescription().equals(description));
// (*) clean up
this.ontologyDataManager.deleteStandardVariableEnumeration(standardVariableId, validValueGeneratedId1);
this.ontologyDataManager.deleteStandardVariableEnumeration(standardVariableId, validValue.getId());
}
@Test
public void testAddMethod() {
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
Term term = this.ontologyDataManager.addMethod(name, definition);
Assert.assertTrue(term.getId() > 0);
term = this.ontologyDataManager.getTermById(term.getId());
}
/**
* This tests an expected property of the ontology data manager to return a non empty map, even for entries that cannot be matched to a
* standard variable in the database
*
* @
*/
@Test
public void testGetStandardVariablesInProjectsNonNullEvenIfNotPresent() {
final String baseVariableName = "TEST_VARIABLE_NAME";
final Random random = new Random();
final int testItemCount = random.nextInt(10);
final List<String> headers = new ArrayList<>(testItemCount);
for (int i = 0; i < testItemCount; i++) {
headers.add(baseVariableName + i);
}
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
Assert.assertNotNull("Application is unable to return non empty output even on non present variables", results);
Assert
.assertEquals("Application is unable to return non empty output even on non present variables", testItemCount, results.size());
for (final String header : headers) {
Assert.assertTrue(
"Application is unable to return non empty output for each of the passed header parameters",
results.containsKey(header));
}
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> vars = entry.getValue();
Assert.assertNotNull(
"Application should give a non null list of standard variables for a given header name, even if not present", vars);
Assert.assertTrue("Application shouldn't be able to give values for dummy input", vars.isEmpty());
}
}
/**
* This tests the ability of the application to retrieve the standard variables associated with known headers
*
* @
*/
@Test
public void testGetStandardVariablesInProjectsKnownHeaders() {
final List<String> headers = Arrays.asList(OntologyDataManagerImplTestConstants.COMMON_HEADERS);
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> variableList = entry.getValue();
Assert.assertTrue(
"Application is unable to return a list of standard variables for known existing central headers ",
variableList.size() > 0);
}
}
/**
* This tests the ability of the application to retrieve standard variables for newly created items
*
* @
*/
@Test
public void testGetStandardVariablesForNewlyCreatedEntries() {
// set up and create a new standard variable for this test
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<String> headers = Arrays.asList(standardVariable.getName());
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> variableList = entry.getValue();
Assert.assertTrue(
"Application is unable to return a proper sized list of standard variables for newly added standard variables",
variableList.size() == 1);
final StandardVariable retrieved = variableList.get(0);
Assert.assertEquals("Application is unable to retrieve the proper standard variable for newly created entries",
standardVariable.getName(), retrieved.getName());
}
}
protected StandardVariable constructDummyStandardVariable() {
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName("TestVariable" + new Random().nextLong());
standardVariable.setDescription("For unit testing purposes");
final Term propertyTerm = this.ontologyDataManager.findTermByName("Yield", CvId.PROPERTIES);
standardVariable.setProperty(propertyTerm);
final Term scaleTerm = this.ontologyDataManager.findTermByName("g", CvId.SCALES);
standardVariable.setScale(scaleTerm);
final Term methodTerm = this.ontologyDataManager.findTermByName("Counting", CvId.METHODS);
standardVariable.setMethod(methodTerm);
final Term dataType = this.ontologyDataManager.getTermById(TermId.NUMERIC_VARIABLE.getId());
standardVariable.setDataType(dataType);
standardVariable.setPhenotypicType(PhenotypicType.VARIATE);
return standardVariable;
}
@Test
public void testFindStandardVariablesByNameOrSynonym() {
Set<StandardVariable> standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING,
PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 0);
standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS, PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_SYNONYM,
PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testFindStandardVariablesByNameOrSynonymWithProperties() {
final Set<StandardVariable> standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS, PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
final Term term = this.ontologyDataManager.getTermById(stdVar.getId());
term.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testFindMethodById() {
// term doesn't exist
Term term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_NOT_EXISTING);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_NOT_METHOD);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_IN_CENTRAL);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
// add a method to local
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
term = this.ontologyDataManager.addMethod(name, definition);
// term does exist in local
term = this.ontologyDataManager.findMethodById(term.getId());
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testFindMethodByName() {
// term doesn't exist
Term term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testFindStandardVariableByTraitScaleMethodNames() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final StandardVariable result =
this.ontologyDataManager.findStandardVariableByTraitScaleMethodNames(standardVariable.getProperty().getName(),
standardVariable.getScale().getName(), standardVariable.getMethod().getName(), PROGRAM_UUID);
Assert.assertNotNull(result);
}
@Test
public void testGetAllTermsByCvId() {
List<Term> terms = this.ontologyDataManager.getAllTermsByCvId(CvId.METHODS);
Assert.assertNotNull(terms);
terms = this.ontologyDataManager.getAllTermsByCvId(CvId.PROPERTIES);
Assert.assertNotNull(terms);
terms = this.ontologyDataManager.getAllTermsByCvId(CvId.SCALES);
Assert.assertNotNull(terms);
}
@Test
public void testCountTermsByCvId() {
long count = this.ontologyDataManager.countTermsByCvId(CvId.METHODS);
count = this.ontologyDataManager.countTermsByCvId(CvId.PROPERTIES);
Assert.assertTrue(count != 0);
count = this.ontologyDataManager.countTermsByCvId(CvId.SCALES);
Assert.assertTrue(count != 0);
}
@Test
public void testGetMethodsForTrait() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<Term> terms = this.ontologyDataManager.getMethodsForTrait(standardVariable.getProperty().getId());
Assert.assertFalse(terms.isEmpty());
}
@Test
public void testGetScalesForTrait() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<Term> terms = this.ontologyDataManager.getScalesForTrait(standardVariable.getProperty().getId());
Assert.assertFalse(terms.isEmpty());
}
@Test
public void testAddTerm() {
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
// add a method, should allow insert
final CvId cvId = CvId.METHODS;
Term term = this.ontologyDataManager.addTerm(name, definition, cvId);
Assert.assertNotNull(term);
Assert.assertTrue(term.getId() > 0);
term = this.ontologyDataManager.getTermById(term.getId());
}
@Test
public void testFindTermByName() {
// term doesn't exist
Term term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING, CvId.METHODS);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD, CvId.METHODS);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL, CvId.METHODS);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testGetDataTypes() {
final List<Term> terms = this.ontologyDataManager.getDataTypes();
Assert.assertNotNull(terms);
}
@Test
public void testGetStandardVariablesInProjects() {
final String entry = "ENTRY";
final String entryno = "ENTRYNO";
final String plot = "PLOT";
final List<String> headers =
Arrays.asList(entry, entryno, plot);
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
Assert.assertTrue(results.get(entry).isEmpty());
Assert.assertFalse(results.get(entryno).isEmpty());
Assert.assertFalse(results.get(plot).isEmpty());
}
@Test
public void testFindTermsByNameOrSynonym() {
// term doesn't exist
List<Term> terms =
this.ontologyDataManager
.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING, CvId.METHODS);
Assert.assertSame(terms.size(), 0);
// term exist but isn't a method
terms = this.ontologyDataManager.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD, CvId.METHODS);
Assert.assertSame(terms.size(), 0);
// term does exist in central
terms = this.ontologyDataManager.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL, CvId.METHODS);
Assert.assertNotNull(terms);
Assert.assertTrue(!terms.isEmpty());
terms.get(0).print(IntegrationTestBase.INDENT);
// name is in synonyms
terms =
this.ontologyDataManager.findTermsByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS,
CvId.VARIABLES);
Assert.assertNotNull(terms);
terms.get(0).print(IntegrationTestBase.INDENT);
// name is both in term and in synonyms
// need to modify the entry in cvterm where name = "Cooperator" to have
// cv_id = 1010
terms = this.ontologyDataManager.findTermsByNameOrSynonym("Cooperator", CvId.PROPERTIES);
Assert.assertNotNull(terms);
for (final Term term : terms) {
term.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testCountIsAOfProperties() {
final long asOf = this.ontologyDataManager.countIsAOfProperties();
Assert.assertTrue(asOf != 0);
}
@Test
public void testAddProperty() {
final int isA = 1087;
final Term term =
this.ontologyDataManager.addProperty(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10), isA);
Assert.assertNotNull(term);
}
@Test
public void testGetProperty() {
final int isA = 1087;
final Term term =
this.ontologyDataManager.addProperty(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10), isA);
final Property property = this.ontologyDataManager.getProperty(term.getId());
Assert.assertNotNull(property);
}
@Test
public void testGetAllTraitGroupsHierarchy() {
final List<TraitClassReference> traitGroups = this.ontologyDataManager.getAllTraitGroupsHierarchy(true);
for (final TraitClassReference traitGroup : traitGroups) {
traitGroup.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testGetPropertyByName() {
final String name = "Season";
final Property property = this.ontologyDataManager.getProperty(name);
}
@Test
@Ignore(value = "Skipping this test. It takes minute+ to run and does not have any assertions anyway. Needs revising.")
public void testGetAllStandardVariable() {
final Set<StandardVariable> standardVariables = this.ontologyDataManager.getAllStandardVariables(PROGRAM_UUID);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testGetStandardVariablesByTraitClass() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(OntologyDataManagerImplTestConstants.NONEXISTING_TERM_TRAIT_CLASS_ID, null,
null, null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(OntologyDataManagerImplTestConstants.EXPECTED_TERM_TRAIT_CLASS_ID, null,
null, null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByProperty() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, OntologyDataManagerImplTestConstants.NONEXISTING_TERM_PROPERTY_ID,
null, null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, OntologyDataManagerImplTestConstants.EXPECTED_TERM_PROPERTY_ID, null,
null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByMethod() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, null, OntologyDataManagerImplTestConstants.NONEXISTING_TERM_METHOD_ID,
null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, null, OntologyDataManagerImplTestConstants.EXPECTED_TERM_METHOD_ID,
null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByScale() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, null, null,
OntologyDataManagerImplTestConstants.NONEXISTING_TERM_SCALE_ID, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, null, null,
OntologyDataManagerImplTestConstants.EXPECTED_TERM_SCALE_ID, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testAddOrUpdateTermAndRelationship() {
final String name = "Study condition NEW";
final String definition = "Study condition NEW class " + (int) (Math.random() * 100);
final Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
final Term newTerm =
this.ontologyDataManager.addOrUpdateTermAndRelationship(name, definition, CvId.PROPERTIES, TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
if (origTerm != null) { // if the operation is update, the ids must be
// same
Assert.assertEquals(origTerm.getId(), newTerm.getId());
}
}
@Test
public void testUpdateTermAndRelationship() {
final String name = "Slope NEW";
final String definition = "Slope NEW class " + (int) (Math.random() * 100);
Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
if (origTerm == null) { // first run, add before update
origTerm =
this.ontologyDataManager.addOrUpdateTermAndRelationship(name, definition, CvId.PROPERTIES, TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
}
this.ontologyDataManager.updateTermAndRelationship(new Term(origTerm.getId(), name, definition), TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
final Term newTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
if (newTerm != null) {
Assert.assertTrue(newTerm.getDefinition().equals(definition));
}
}
@Test
public void testAddOrUpdateTerm() {
final String name = "Real";
// add random number to see the update
final String definition = "Real Description NEW " + (int) (Math.random() * 100);
final Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
final Term newTerm = this.ontologyDataManager.addOrUpdateTerm(name, definition, CvId.SCALES);
if (origTerm != null) { // if the operation is update, the ids must be same
Assert.assertEquals(origTerm.getId(), newTerm.getId());
}
}
@Test
public void testUpdateTerm() {
final String name = "Integer2";
// add random number to see the update
final String definition = "Integer NEW " + (int) (Math.random() * 100);
Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
if (origTerm == null) { // first run, add before update
origTerm = this.ontologyDataManager.addTerm(name, definition, CvId.SCALES);
}
this.ontologyDataManager.updateTerm(new Term(origTerm.getId(), name, definition));
final Term newTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
if (origTerm != null && newTerm != null) {
Assert.assertTrue(newTerm.getDefinition().equals(definition));
}
}
@Test
public void testUpdateTerms() {
final String termName1 = "Sample Term 1";
final String termName2 = "Sample Term 2";
final String termDescription1 = "Sample Term Description 1";
final String termDescription2 = "Sample Term Description 2";
final Term term1 = this.ontologyDataManager.addTerm(termName1, termDescription1, CvId.SCALES);
final Term term2 = this.ontologyDataManager.addTerm(termName2, termDescription2, CvId.SCALES);
// Update the added terms name with new names.
final List<Term> terms = new ArrayList<>();
term1.setName("New Term Name 1");
term2.setName("New Term Name 2");
terms.add(term1);
terms.add(term2);
this.ontologyDataManager.updateTerms(terms);
final Term newTerm1 = this.ontologyDataManager.getTermById(term1.getId());
final Term newTerm2 = this.ontologyDataManager.getTermById(term2.getId());
Assert.assertEquals("The term's name should be updated", "New Term Name 1", newTerm1.getName());
Assert.assertEquals("The term's name should be updated", "New Term Name 2", newTerm2.getName());
}
@Test
public void testGetStandardVariableIdByTermId() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final Integer stdVariableId =
this.ontologyDataManager.getStandardVariableIdByTermId(standardVariable.getProperty().getId(), TermId.HAS_PROPERTY);
Assert.assertNotNull(stdVariableId);
}
@Test
public void testDeleteTerm() {
// terms to be deleted should be from local db
String name = "Test Method " + new Random().nextInt(10000);
String definition = "Test Definition";
// add a method, should allow insert
CvId cvId = CvId.METHODS;
Term term = this.ontologyDataManager.addTerm(name, definition, cvId);
this.ontologyDataManager.deleteTerm(term.getId(), cvId);
// check if value does not exist anymore
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
name = "Test Scale " + new Random().nextInt(10000);
definition = "Test Definition";
cvId = CvId.SCALES;
term = this.ontologyDataManager.addTerm(name, definition, cvId);
this.ontologyDataManager.deleteTerm(term.getId(), cvId);
// check if value does not exist anymore
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
}
@Test
public void testDeleteTermAndRelationship() {
String name = "Test Property" + new Random().nextInt(10000);
String definition = "Property Definition";
final int isA = 1087;
Term term = this.ontologyDataManager.addProperty(name, definition, isA);
this.ontologyDataManager.deleteTermAndRelationship(term.getId(), CvId.PROPERTIES, TermId.IS_A.getId(), isA);
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
name = "Test Trait Class " + new Random().nextInt(10000);
definition = "Test Definition";
term = this.ontologyDataManager.addTraitClass(name, definition, TermId.ONTOLOGY_TRAIT_CLASS.getId()).getTerm();
this.ontologyDataManager.deleteTermAndRelationship(term.getId(), CvId.IBDB_TERMS, TermId.IS_A.getId(),
TermId.ONTOLOGY_TRAIT_CLASS.getId());
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
}
@Test(expected = MiddlewareQueryException.class)
public void testDeleteParentChildTerms() {
final String parentTermName = "Parent Test Trait Class" + new Random().nextInt(10000);
final String parentTermDef = parentTermName + " Definition";
final Term termParent =
this.ontologyDataManager.addTraitClass(parentTermName, parentTermDef, TermId.ONTOLOGY_TRAIT_CLASS.getId()).getTerm();
final String childTermName = "Child Test Trait Class" + new Random().nextInt(10000);
final String childTermDef = childTermName + " Definition";
this.ontologyDataManager.addTraitClass(childTermName, childTermDef, termParent.getId()).getTerm();
this.ontologyDataManager.deleteTermAndRelationship(termParent.getId(), CvId.IBDB_TERMS, TermId.IS_A.getId(),
TermId.ONTOLOGY_TRAIT_CLASS.getId());
}
@Test
public void testGetAllPropertiesWithTraitClass() {
final List<Property> properties = this.ontologyDataManager.getAllPropertiesWithTraitClass();
Assert.assertFalse(properties.isEmpty());
}
@Test
@Ignore(value = "This test is failing and it seems it's due to a bug in deleteStandardVariable. Skipping this test.")
public void testDeleteStandardVariable() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
this.ontologyDataManager.deleteStandardVariable(standardVariable.getId());
// Check that the variable got deleted
final Term term = this.ontologyDataManager.getTermById(standardVariable.getId());
Assert.assertNull("Expected the standard variable deleted but it is still there!", term);
}
@Test
public void testGetCVIdByName() throws MiddlewareQueryException {
final Integer cvId = this.ontologyDataManager.getCVIdByName("Variables");
Assert.assertEquals(1040, cvId.intValue());
}
private StandardVariable createStandardVariable(final String name) {
final CVTerm property = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.PROPERTIES);
final CVTerm scale = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.SCALES);
final CVTerm method = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.METHODS);
final CVTerm numericDataType = this.cvTermDao.getById(DataType.NUMERIC_VARIABLE.getId());
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName(name);
standardVariable.setProperty(new Term(property.getCvTermId(), property.getName(), property.getDefinition()));
standardVariable.setScale(new Term(scale.getCvTermId(), scale.getName(), scale.getDefinition()));
standardVariable.setMethod(new Term(method.getCvTermId(), method.getName(), method.getDefinition()));
standardVariable.setDataType(new Term(numericDataType.getCvTermId(), numericDataType.getName(), numericDataType.getDefinition()));
this.ontologyDataManager.addStandardVariable(standardVariable, PROGRAM_UUID);
return standardVariable;
}
}
| UTF-8 | Java | 38,732 | java | OntologyDataManagerImplIntegrationTest.java | Java | [
{
"context": "ublic void testAddTerm() {\n\t\tfinal String name = \"Test Method \" + new Random().nextInt(10000);\n\t\tfinal S",
"end": 23233,
"score": 0.61388099193573,
"start": 23229,
"tag": "NAME",
"value": "Test"
}
] | null | [] | /*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public License (http://bit.ly/8Ztv8M) and the provisions of Part F
* of the Generation Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.middleware.manager;
import org.apache.commons.lang3.RandomStringUtils;
import org.generationcp.middleware.ContextHolder;
import org.generationcp.middleware.IntegrationTestBase;
import org.generationcp.middleware.dao.oms.CVTermDao;
import org.generationcp.middleware.domain.dms.Enumeration;
import org.generationcp.middleware.domain.dms.PhenotypicType;
import org.generationcp.middleware.domain.dms.StandardVariable;
import org.generationcp.middleware.domain.dms.StandardVariableSummary;
import org.generationcp.middleware.domain.dms.VariableConstraints;
import org.generationcp.middleware.domain.oms.CvId;
import org.generationcp.middleware.domain.oms.Property;
import org.generationcp.middleware.domain.oms.Term;
import org.generationcp.middleware.domain.oms.TermId;
import org.generationcp.middleware.domain.oms.TermSummary;
import org.generationcp.middleware.domain.oms.TraitClassReference;
import org.generationcp.middleware.domain.ontology.DataType;
import org.generationcp.middleware.exceptions.MiddlewareQueryException;
import org.generationcp.middleware.pojos.oms.CVTerm;
import org.generationcp.middleware.utils.test.OntologyDataManagerImplTestConstants;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
public class OntologyDataManagerImplIntegrationTest extends IntegrationTestBase {
private static final String PROGRAM_UUID = UUID.randomUUID().toString();
@BeforeClass
public static void setUpOnce() {
// Variable caching relies on the context holder to determine current crop database in use
ContextHolder.setCurrentCrop("maize");
ContextHolder.setCurrentProgram(PROGRAM_UUID);
}
private OntologyDataManagerImpl ontologyDataManager;
private CVTermDao cvTermDao;
@Before
public void init() {
this.ontologyDataManager = new OntologyDataManagerImpl(this.sessionProvder);
this.cvTermDao = new CVTermDao();
this.cvTermDao.setSession(this.sessionProvder.getSession());
}
@Test
public void testGetCvTermById() {
final Term term = this.ontologyDataManager.getTermById(6040);
Assert.assertNotNull(term);
}
@Test
public void testGetStandardVariable() {
final StandardVariable standardVariable =
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
Assert.assertNotNull(standardVariable);
}
@Test
public void getStandVariableList() {
final StandardVariable standardVariable1 = this.createStandardVariable("StandardVariable1");
final StandardVariable standardVariable2 = this.createStandardVariable("StandardVariable2");
final List<Integer> ids = Arrays.asList(standardVariable1.getId(), standardVariable2.getId());
final List<StandardVariable> standardVariables = this.ontologyDataManager.getStandardVariables(ids, PROGRAM_UUID);
Assert.assertEquals(2, standardVariables.size());
Assert.assertEquals(standardVariable1.getId(), standardVariables.get(0).getId());
Assert.assertEquals(standardVariable2.getId(), standardVariables.get(1).getId());
}
@Test
public void testGetStandardVariableSummaries() {
final StandardVariable standardVariable1 = this.createStandardVariable("StandardVariable1");
final StandardVariable standardVariable2 = this.createStandardVariable("StandardVariable2");
final List<Integer> ids = Arrays.asList(standardVariable1.getId(), standardVariable2.getId());
final List<StandardVariableSummary> summaries = this.ontologyDataManager.getStandardVariableSummaries(ids);
Assert.assertNotNull(summaries);
Assert.assertEquals(ids.size(), summaries.size());
for (final StandardVariableSummary summary : summaries) {
Assert.assertTrue(ids.contains(summary.getId()));
}
}
@Test
public void testGetStandardVariableSummary() {
// First create a new Standardvariable
final StandardVariable testStandardVariable = this.createStandardVariable("TestVariable");
// Load summary from the view based method
final StandardVariableSummary summary = this.ontologyDataManager.getStandardVariableSummary(testStandardVariable.getId());
Assert.assertNotNull(summary);
// Make sure that the summary data loaded from view matches with details
// data loaded using the usual method.
this.assertVariableDataMatches(testStandardVariable, summary);
}
private void assertVariableDataMatches(final StandardVariable standardVariable, final StandardVariableSummary summary) {
Assert.assertEquals(new Integer(standardVariable.getId()), summary.getId());
Assert.assertEquals(standardVariable.getName(), summary.getName());
Assert.assertEquals(standardVariable.getDescription(), summary.getDescription());
this.assertTermDataMatches(standardVariable.getProperty(), summary.getProperty());
this.assertTermDataMatches(standardVariable.getMethod(), summary.getMethod());
this.assertTermDataMatches(standardVariable.getScale(), summary.getScale());
this.assertTermDataMatches(standardVariable.getDataType(), summary.getDataType());
Assert.assertEquals(standardVariable.getPhenotypicType(), summary.getPhenotypicType());
}
private void assertTermDataMatches(final Term termDetails, final TermSummary termSummary) {
Assert.assertEquals(new Integer(termDetails.getId()), termSummary.getId());
Assert.assertEquals(termDetails.getName(), termSummary.getName());
Assert.assertEquals(termDetails.getDefinition(), termSummary.getDefinition());
}
@Test
public void testCopyStandardVariable() {
final StandardVariable stdVar =
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
final StandardVariable stdVar2 = stdVar.copy();
Assert.assertNotSame(stdVar.getId(), stdVar2.getId());
Assert.assertSame(stdVar.getProperty(), stdVar2.getProperty());
Assert.assertSame(stdVar.getScale(), stdVar2.getScale());
Assert.assertSame(stdVar.getMethod(), stdVar2.getMethod());
Assert.assertSame(stdVar.getDataType(), stdVar2.getDataType());
Assert.assertSame(stdVar.getPhenotypicType(), stdVar2.getPhenotypicType());
Assert.assertSame(stdVar.getConstraints(), stdVar2.getConstraints());
if (stdVar.getName() != null) {
Assert.assertTrue(stdVar.getName().equals(stdVar2.getName()));
}
if (stdVar.getDescription() != null) {
Assert.assertTrue(stdVar.getDescription().equals(stdVar2.getDescription()));
}
Assert.assertSame(stdVar.getEnumerations(), stdVar2.getEnumerations());
}
@Test
public void testStandardVariableCache() {
// First call to getStandardVariable() will put the value to the cache
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
// Second (and subsequent) calls will retrieve the value from the cache
this.ontologyDataManager.getStandardVariable(OntologyDataManagerImplTestConstants.STD_VARIABLE_ID, PROGRAM_UUID);
}
@Test
public void testNameSynonyms() {
final StandardVariable sv = this.ontologyDataManager.getStandardVariable(8383, PROGRAM_UUID);
sv.print(IntegrationTestBase.INDENT);
}
@Test
public void testAddStandardVariable() {
// create new trait
final String propertyName = "property name " + new Random().nextInt(10000);
this.ontologyDataManager.addProperty(propertyName, "test property", 1087);
final StandardVariable stdVariable = new StandardVariable();
stdVariable.setName("variable name " + new Random().nextInt(10000));
stdVariable.setDescription("variable description");
// stdVariable.setProperty(new Term(2002, "User", "Database user"));
stdVariable.setProperty(this.ontologyDataManager.findTermByName(propertyName, CvId.PROPERTIES));
stdVariable.setMethod(new Term(4030, "Assigned", "Term, name or id assigned"));
stdVariable.setScale(new Term(6000, "DBCV", "Controlled vocabulary from a database"));
stdVariable.setDataType(new Term(1120, "Character variable", "variable with char values"));
stdVariable.setIsA(new Term(1050, "Study condition", "Study condition class"));
stdVariable.setEnumerations(new ArrayList<Enumeration>());
stdVariable.getEnumerations().add(new Enumeration(10000, "N", "Nursery", 1));
stdVariable.getEnumerations().add(new Enumeration(10001, "HB", "Hybridization Nursery", 2));
stdVariable.getEnumerations().add(new Enumeration(10002, "PN", "Pedigree Nursery", 3));
stdVariable.setConstraints(new VariableConstraints(100.0, 999.0));
stdVariable.setCropOntologyId("CROP-TEST");
try {
this.ontologyDataManager.addStandardVariable(stdVariable, PROGRAM_UUID);
} catch (final MiddlewareQueryException e) {
if (e.getMessage().contains("already exists")) {
// Ignore. The test run successfully before.
}
}
}
@Test(expected = MiddlewareQueryException.class)
public void testAddStandardVariableWithMissingScalePropertyMethod() {
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName("Test SPM" + new Random().nextInt(10000));
standardVariable.setDescription("Std variable with new scale, property, method");
final Term newProperty = new Term(2451, "Environment", "Environment");
Term property = this.ontologyDataManager.findTermByName(newProperty.getName(), CvId.PROPERTIES);
if (property == null) {
property = newProperty;
}
final Term newScale = new Term(6020, "Text", "Text");
Term scale = this.ontologyDataManager.findTermByName(newScale.getName(), CvId.SCALES);
if (scale == null) {
scale = newScale;
}
final Term newMethod = new Term(0, "Test Method", "Test Method");
Term method = this.ontologyDataManager.findTermByName(newMethod.getName(), CvId.METHODS);
if (method == null) {
method = newMethod;
}
standardVariable.setProperty(property);
standardVariable.setScale(scale);
standardVariable.setMethod(method);
this.ontologyDataManager.addStandardVariable(standardVariable, PROGRAM_UUID);
}
@Test
public void testAddStandardVariableEnumeration() {
final int standardVariableId = OntologyDataManagerImplTestConstants.CATEGORICAL_VARIABLE_TERM_ID;
final String name = "Name_" + new Random().nextInt(10000);
final String description = "Test Valid Value" + new Random().nextInt(10000);
StandardVariable standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
final Enumeration validValue = new Enumeration(null, name, description, 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
}
@Test
public void testUpdateStandardVariableEnumeration() {
// Case 1: NEW VALID VALUE
final int standardVariableId = OntologyDataManagerImplTestConstants.CATEGORICAL_VARIABLE_TERM_ID;
String name = "Name_" + new Random().nextInt(10000);
String description = "Test Valid Value" + new Random().nextInt(10000);
StandardVariable standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Enumeration validValue = new Enumeration(null, name, description, standardVariable.getEnumerations().size() + 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
final Integer validValueGeneratedId1 = standardVariable.getEnumerationByName(name).getId();
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
// Case 2: UPDATE CENTRAL VALID VALUE
final Integer validValueId = OntologyDataManagerImplTestConstants.CROP_SESCND_VALID_VALUE_FROM_CENTRAL;
name = "Name_" + new Random().nextInt(10000);
description = "Test Valid Value " + new Random().nextInt(10000); // Original
// value
// in
// central:
// "Moderately well exserted"
validValue = new Enumeration(validValueId, name, description, 1);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertNotNull(standardVariable.getEnumeration(validValue.getId()));
// Case 3: UPDATE LOCAL VALID VALUE
description = "Test Valid Value " + new Random().nextInt(10000);
validValue.setDescription(description);
this.ontologyDataManager.saveOrUpdateStandardVariableEnumeration(standardVariable, validValue);
standardVariable = this.ontologyDataManager.getStandardVariable(standardVariableId, PROGRAM_UUID);
Assert.assertTrue(standardVariable.getEnumeration(validValue.getId()).getDescription().equals(description));
// (*) clean up
this.ontologyDataManager.deleteStandardVariableEnumeration(standardVariableId, validValueGeneratedId1);
this.ontologyDataManager.deleteStandardVariableEnumeration(standardVariableId, validValue.getId());
}
@Test
public void testAddMethod() {
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
Term term = this.ontologyDataManager.addMethod(name, definition);
Assert.assertTrue(term.getId() > 0);
term = this.ontologyDataManager.getTermById(term.getId());
}
/**
* This tests an expected property of the ontology data manager to return a non empty map, even for entries that cannot be matched to a
* standard variable in the database
*
* @
*/
@Test
public void testGetStandardVariablesInProjectsNonNullEvenIfNotPresent() {
final String baseVariableName = "TEST_VARIABLE_NAME";
final Random random = new Random();
final int testItemCount = random.nextInt(10);
final List<String> headers = new ArrayList<>(testItemCount);
for (int i = 0; i < testItemCount; i++) {
headers.add(baseVariableName + i);
}
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
Assert.assertNotNull("Application is unable to return non empty output even on non present variables", results);
Assert
.assertEquals("Application is unable to return non empty output even on non present variables", testItemCount, results.size());
for (final String header : headers) {
Assert.assertTrue(
"Application is unable to return non empty output for each of the passed header parameters",
results.containsKey(header));
}
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> vars = entry.getValue();
Assert.assertNotNull(
"Application should give a non null list of standard variables for a given header name, even if not present", vars);
Assert.assertTrue("Application shouldn't be able to give values for dummy input", vars.isEmpty());
}
}
/**
* This tests the ability of the application to retrieve the standard variables associated with known headers
*
* @
*/
@Test
public void testGetStandardVariablesInProjectsKnownHeaders() {
final List<String> headers = Arrays.asList(OntologyDataManagerImplTestConstants.COMMON_HEADERS);
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> variableList = entry.getValue();
Assert.assertTrue(
"Application is unable to return a list of standard variables for known existing central headers ",
variableList.size() > 0);
}
}
/**
* This tests the ability of the application to retrieve standard variables for newly created items
*
* @
*/
@Test
public void testGetStandardVariablesForNewlyCreatedEntries() {
// set up and create a new standard variable for this test
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<String> headers = Arrays.asList(standardVariable.getName());
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
for (final Map.Entry<String, List<StandardVariable>> entry : results.entrySet()) {
final List<StandardVariable> variableList = entry.getValue();
Assert.assertTrue(
"Application is unable to return a proper sized list of standard variables for newly added standard variables",
variableList.size() == 1);
final StandardVariable retrieved = variableList.get(0);
Assert.assertEquals("Application is unable to retrieve the proper standard variable for newly created entries",
standardVariable.getName(), retrieved.getName());
}
}
protected StandardVariable constructDummyStandardVariable() {
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName("TestVariable" + new Random().nextLong());
standardVariable.setDescription("For unit testing purposes");
final Term propertyTerm = this.ontologyDataManager.findTermByName("Yield", CvId.PROPERTIES);
standardVariable.setProperty(propertyTerm);
final Term scaleTerm = this.ontologyDataManager.findTermByName("g", CvId.SCALES);
standardVariable.setScale(scaleTerm);
final Term methodTerm = this.ontologyDataManager.findTermByName("Counting", CvId.METHODS);
standardVariable.setMethod(methodTerm);
final Term dataType = this.ontologyDataManager.getTermById(TermId.NUMERIC_VARIABLE.getId());
standardVariable.setDataType(dataType);
standardVariable.setPhenotypicType(PhenotypicType.VARIATE);
return standardVariable;
}
@Test
public void testFindStandardVariablesByNameOrSynonym() {
Set<StandardVariable> standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING,
PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 0);
standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS, PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_SYNONYM,
PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testFindStandardVariablesByNameOrSynonymWithProperties() {
final Set<StandardVariable> standardVariables =
this.ontologyDataManager.findStandardVariablesByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS, PROGRAM_UUID);
Assert.assertSame(standardVariables.size(), 1);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
final Term term = this.ontologyDataManager.getTermById(stdVar.getId());
term.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testFindMethodById() {
// term doesn't exist
Term term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_NOT_EXISTING);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_NOT_METHOD);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findMethodById(OntologyDataManagerImplTestConstants.TERM_ID_IN_CENTRAL);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
// add a method to local
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
term = this.ontologyDataManager.addMethod(name, definition);
// term does exist in local
term = this.ontologyDataManager.findMethodById(term.getId());
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testFindMethodByName() {
// term doesn't exist
Term term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findMethodByName(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testFindStandardVariableByTraitScaleMethodNames() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final StandardVariable result =
this.ontologyDataManager.findStandardVariableByTraitScaleMethodNames(standardVariable.getProperty().getName(),
standardVariable.getScale().getName(), standardVariable.getMethod().getName(), PROGRAM_UUID);
Assert.assertNotNull(result);
}
@Test
public void testGetAllTermsByCvId() {
List<Term> terms = this.ontologyDataManager.getAllTermsByCvId(CvId.METHODS);
Assert.assertNotNull(terms);
terms = this.ontologyDataManager.getAllTermsByCvId(CvId.PROPERTIES);
Assert.assertNotNull(terms);
terms = this.ontologyDataManager.getAllTermsByCvId(CvId.SCALES);
Assert.assertNotNull(terms);
}
@Test
public void testCountTermsByCvId() {
long count = this.ontologyDataManager.countTermsByCvId(CvId.METHODS);
count = this.ontologyDataManager.countTermsByCvId(CvId.PROPERTIES);
Assert.assertTrue(count != 0);
count = this.ontologyDataManager.countTermsByCvId(CvId.SCALES);
Assert.assertTrue(count != 0);
}
@Test
public void testGetMethodsForTrait() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<Term> terms = this.ontologyDataManager.getMethodsForTrait(standardVariable.getProperty().getId());
Assert.assertFalse(terms.isEmpty());
}
@Test
public void testGetScalesForTrait() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final List<Term> terms = this.ontologyDataManager.getScalesForTrait(standardVariable.getProperty().getId());
Assert.assertFalse(terms.isEmpty());
}
@Test
public void testAddTerm() {
final String name = "Test Method " + new Random().nextInt(10000);
final String definition = "Test Definition";
// add a method, should allow insert
final CvId cvId = CvId.METHODS;
Term term = this.ontologyDataManager.addTerm(name, definition, cvId);
Assert.assertNotNull(term);
Assert.assertTrue(term.getId() > 0);
term = this.ontologyDataManager.getTermById(term.getId());
}
@Test
public void testFindTermByName() {
// term doesn't exist
Term term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING, CvId.METHODS);
Assert.assertNull(term);
// term exist but isn't a method
term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD, CvId.METHODS);
Assert.assertNull(term);
// term does exist in central
term = this.ontologyDataManager.findTermByName(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL, CvId.METHODS);
Assert.assertNotNull(term);
term.print(IntegrationTestBase.INDENT);
}
@Test
public void testGetDataTypes() {
final List<Term> terms = this.ontologyDataManager.getDataTypes();
Assert.assertNotNull(terms);
}
@Test
public void testGetStandardVariablesInProjects() {
final String entry = "ENTRY";
final String entryno = "ENTRYNO";
final String plot = "PLOT";
final List<String> headers =
Arrays.asList(entry, entryno, plot);
final Map<String, List<StandardVariable>> results = this.ontologyDataManager.getStandardVariablesInProjects(headers, PROGRAM_UUID);
Assert.assertTrue(results.get(entry).isEmpty());
Assert.assertFalse(results.get(entryno).isEmpty());
Assert.assertFalse(results.get(plot).isEmpty());
}
@Test
public void testFindTermsByNameOrSynonym() {
// term doesn't exist
List<Term> terms =
this.ontologyDataManager
.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_EXISTING, CvId.METHODS);
Assert.assertSame(terms.size(), 0);
// term exist but isn't a method
terms = this.ontologyDataManager.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_NOT_METHOD, CvId.METHODS);
Assert.assertSame(terms.size(), 0);
// term does exist in central
terms = this.ontologyDataManager.findTermsByNameOrSynonym(OntologyDataManagerImplTestConstants.TERM_NAME_IN_CENTRAL, CvId.METHODS);
Assert.assertNotNull(terms);
Assert.assertTrue(!terms.isEmpty());
terms.get(0).print(IntegrationTestBase.INDENT);
// name is in synonyms
terms =
this.ontologyDataManager.findTermsByNameOrSynonym(
OntologyDataManagerImplTestConstants.TERM_NAME_IS_IN_SYNONYMS,
CvId.VARIABLES);
Assert.assertNotNull(terms);
terms.get(0).print(IntegrationTestBase.INDENT);
// name is both in term and in synonyms
// need to modify the entry in cvterm where name = "Cooperator" to have
// cv_id = 1010
terms = this.ontologyDataManager.findTermsByNameOrSynonym("Cooperator", CvId.PROPERTIES);
Assert.assertNotNull(terms);
for (final Term term : terms) {
term.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testCountIsAOfProperties() {
final long asOf = this.ontologyDataManager.countIsAOfProperties();
Assert.assertTrue(asOf != 0);
}
@Test
public void testAddProperty() {
final int isA = 1087;
final Term term =
this.ontologyDataManager.addProperty(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10), isA);
Assert.assertNotNull(term);
}
@Test
public void testGetProperty() {
final int isA = 1087;
final Term term =
this.ontologyDataManager.addProperty(RandomStringUtils.randomAlphanumeric(10), RandomStringUtils.randomAlphanumeric(10), isA);
final Property property = this.ontologyDataManager.getProperty(term.getId());
Assert.assertNotNull(property);
}
@Test
public void testGetAllTraitGroupsHierarchy() {
final List<TraitClassReference> traitGroups = this.ontologyDataManager.getAllTraitGroupsHierarchy(true);
for (final TraitClassReference traitGroup : traitGroups) {
traitGroup.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testGetPropertyByName() {
final String name = "Season";
final Property property = this.ontologyDataManager.getProperty(name);
}
@Test
@Ignore(value = "Skipping this test. It takes minute+ to run and does not have any assertions anyway. Needs revising.")
public void testGetAllStandardVariable() {
final Set<StandardVariable> standardVariables = this.ontologyDataManager.getAllStandardVariables(PROGRAM_UUID);
for (final StandardVariable stdVar : standardVariables) {
stdVar.print(IntegrationTestBase.INDENT);
}
}
@Test
public void testGetStandardVariablesByTraitClass() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(OntologyDataManagerImplTestConstants.NONEXISTING_TERM_TRAIT_CLASS_ID, null,
null, null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(OntologyDataManagerImplTestConstants.EXPECTED_TERM_TRAIT_CLASS_ID, null,
null, null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByProperty() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, OntologyDataManagerImplTestConstants.NONEXISTING_TERM_PROPERTY_ID,
null, null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, OntologyDataManagerImplTestConstants.EXPECTED_TERM_PROPERTY_ID, null,
null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByMethod() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, null, OntologyDataManagerImplTestConstants.NONEXISTING_TERM_METHOD_ID,
null, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, null, OntologyDataManagerImplTestConstants.EXPECTED_TERM_METHOD_ID,
null, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testGetStandardVariablesByScale() throws MiddlewareQueryException {
List<StandardVariable> vars =
this.ontologyDataManager.getStandardVariables(null, null, null,
OntologyDataManagerImplTestConstants.NONEXISTING_TERM_SCALE_ID, PROGRAM_UUID);
Assert.assertTrue(vars.isEmpty());
vars =
this.ontologyDataManager.getStandardVariables(null, null, null,
OntologyDataManagerImplTestConstants.EXPECTED_TERM_SCALE_ID, PROGRAM_UUID);
Assert.assertFalse(vars.isEmpty());
}
@Test
public void testAddOrUpdateTermAndRelationship() {
final String name = "Study condition NEW";
final String definition = "Study condition NEW class " + (int) (Math.random() * 100);
final Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
final Term newTerm =
this.ontologyDataManager.addOrUpdateTermAndRelationship(name, definition, CvId.PROPERTIES, TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
if (origTerm != null) { // if the operation is update, the ids must be
// same
Assert.assertEquals(origTerm.getId(), newTerm.getId());
}
}
@Test
public void testUpdateTermAndRelationship() {
final String name = "Slope NEW";
final String definition = "Slope NEW class " + (int) (Math.random() * 100);
Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
if (origTerm == null) { // first run, add before update
origTerm =
this.ontologyDataManager.addOrUpdateTermAndRelationship(name, definition, CvId.PROPERTIES, TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
}
this.ontologyDataManager.updateTermAndRelationship(new Term(origTerm.getId(), name, definition), TermId.IS_A.getId(),
OntologyDataManagerImplTestConstants.OBJECT_ID);
final Term newTerm = this.ontologyDataManager.findTermByName(name, CvId.PROPERTIES);
if (newTerm != null) {
Assert.assertTrue(newTerm.getDefinition().equals(definition));
}
}
@Test
public void testAddOrUpdateTerm() {
final String name = "Real";
// add random number to see the update
final String definition = "Real Description NEW " + (int) (Math.random() * 100);
final Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
final Term newTerm = this.ontologyDataManager.addOrUpdateTerm(name, definition, CvId.SCALES);
if (origTerm != null) { // if the operation is update, the ids must be same
Assert.assertEquals(origTerm.getId(), newTerm.getId());
}
}
@Test
public void testUpdateTerm() {
final String name = "Integer2";
// add random number to see the update
final String definition = "Integer NEW " + (int) (Math.random() * 100);
Term origTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
if (origTerm == null) { // first run, add before update
origTerm = this.ontologyDataManager.addTerm(name, definition, CvId.SCALES);
}
this.ontologyDataManager.updateTerm(new Term(origTerm.getId(), name, definition));
final Term newTerm = this.ontologyDataManager.findTermByName(name, CvId.SCALES);
if (origTerm != null && newTerm != null) {
Assert.assertTrue(newTerm.getDefinition().equals(definition));
}
}
@Test
public void testUpdateTerms() {
final String termName1 = "Sample Term 1";
final String termName2 = "Sample Term 2";
final String termDescription1 = "Sample Term Description 1";
final String termDescription2 = "Sample Term Description 2";
final Term term1 = this.ontologyDataManager.addTerm(termName1, termDescription1, CvId.SCALES);
final Term term2 = this.ontologyDataManager.addTerm(termName2, termDescription2, CvId.SCALES);
// Update the added terms name with new names.
final List<Term> terms = new ArrayList<>();
term1.setName("New Term Name 1");
term2.setName("New Term Name 2");
terms.add(term1);
terms.add(term2);
this.ontologyDataManager.updateTerms(terms);
final Term newTerm1 = this.ontologyDataManager.getTermById(term1.getId());
final Term newTerm2 = this.ontologyDataManager.getTermById(term2.getId());
Assert.assertEquals("The term's name should be updated", "New Term Name 1", newTerm1.getName());
Assert.assertEquals("The term's name should be updated", "New Term Name 2", newTerm2.getName());
}
@Test
public void testGetStandardVariableIdByTermId() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
final Integer stdVariableId =
this.ontologyDataManager.getStandardVariableIdByTermId(standardVariable.getProperty().getId(), TermId.HAS_PROPERTY);
Assert.assertNotNull(stdVariableId);
}
@Test
public void testDeleteTerm() {
// terms to be deleted should be from local db
String name = "Test Method " + new Random().nextInt(10000);
String definition = "Test Definition";
// add a method, should allow insert
CvId cvId = CvId.METHODS;
Term term = this.ontologyDataManager.addTerm(name, definition, cvId);
this.ontologyDataManager.deleteTerm(term.getId(), cvId);
// check if value does not exist anymore
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
name = "Test Scale " + new Random().nextInt(10000);
definition = "Test Definition";
cvId = CvId.SCALES;
term = this.ontologyDataManager.addTerm(name, definition, cvId);
this.ontologyDataManager.deleteTerm(term.getId(), cvId);
// check if value does not exist anymore
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
}
@Test
public void testDeleteTermAndRelationship() {
String name = "Test Property" + new Random().nextInt(10000);
String definition = "Property Definition";
final int isA = 1087;
Term term = this.ontologyDataManager.addProperty(name, definition, isA);
this.ontologyDataManager.deleteTermAndRelationship(term.getId(), CvId.PROPERTIES, TermId.IS_A.getId(), isA);
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
name = "Test Trait Class " + new Random().nextInt(10000);
definition = "Test Definition";
term = this.ontologyDataManager.addTraitClass(name, definition, TermId.ONTOLOGY_TRAIT_CLASS.getId()).getTerm();
this.ontologyDataManager.deleteTermAndRelationship(term.getId(), CvId.IBDB_TERMS, TermId.IS_A.getId(),
TermId.ONTOLOGY_TRAIT_CLASS.getId());
term = this.ontologyDataManager.getTermById(term.getId());
Assert.assertNull(term);
}
@Test(expected = MiddlewareQueryException.class)
public void testDeleteParentChildTerms() {
final String parentTermName = "Parent Test Trait Class" + new Random().nextInt(10000);
final String parentTermDef = parentTermName + " Definition";
final Term termParent =
this.ontologyDataManager.addTraitClass(parentTermName, parentTermDef, TermId.ONTOLOGY_TRAIT_CLASS.getId()).getTerm();
final String childTermName = "Child Test Trait Class" + new Random().nextInt(10000);
final String childTermDef = childTermName + " Definition";
this.ontologyDataManager.addTraitClass(childTermName, childTermDef, termParent.getId()).getTerm();
this.ontologyDataManager.deleteTermAndRelationship(termParent.getId(), CvId.IBDB_TERMS, TermId.IS_A.getId(),
TermId.ONTOLOGY_TRAIT_CLASS.getId());
}
@Test
public void testGetAllPropertiesWithTraitClass() {
final List<Property> properties = this.ontologyDataManager.getAllPropertiesWithTraitClass();
Assert.assertFalse(properties.isEmpty());
}
@Test
@Ignore(value = "This test is failing and it seems it's due to a bug in deleteStandardVariable. Skipping this test.")
public void testDeleteStandardVariable() {
final StandardVariable standardVariable = this.createStandardVariable("testVariable");
this.ontologyDataManager.deleteStandardVariable(standardVariable.getId());
// Check that the variable got deleted
final Term term = this.ontologyDataManager.getTermById(standardVariable.getId());
Assert.assertNull("Expected the standard variable deleted but it is still there!", term);
}
@Test
public void testGetCVIdByName() throws MiddlewareQueryException {
final Integer cvId = this.ontologyDataManager.getCVIdByName("Variables");
Assert.assertEquals(1040, cvId.intValue());
}
private StandardVariable createStandardVariable(final String name) {
final CVTerm property = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.PROPERTIES);
final CVTerm scale = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.SCALES);
final CVTerm method = this.cvTermDao.save(RandomStringUtils.randomAlphanumeric(10), "", CvId.METHODS);
final CVTerm numericDataType = this.cvTermDao.getById(DataType.NUMERIC_VARIABLE.getId());
final StandardVariable standardVariable = new StandardVariable();
standardVariable.setName(name);
standardVariable.setProperty(new Term(property.getCvTermId(), property.getName(), property.getDefinition()));
standardVariable.setScale(new Term(scale.getCvTermId(), scale.getName(), scale.getDefinition()));
standardVariable.setMethod(new Term(method.getCvTermId(), method.getName(), method.getDefinition()));
standardVariable.setDataType(new Term(numericDataType.getCvTermId(), numericDataType.getName(), numericDataType.getDefinition()));
this.ontologyDataManager.addStandardVariable(standardVariable, PROGRAM_UUID);
return standardVariable;
}
}
| 38,732 | 0.774528 | 0.766782 | 963 | 39.220146 | 37.165977 | 138 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.140187 | false | false | 9 |
8617c68843e5007e8bb87652d004881ee07e1d8e | 1,108,101,619,228 | 72e89408e5ab586501fbbb0de9fe988d4eccc720 | /ole-app/olefs/src/main/java/org/kuali/ole/deliver/controller/LoanHistoryUpdateController.java | a9a637b6cc7e0144e01b740b7163c2b6116b15b2 | [] | no_license | rajeshgnanam/SOAS_2.1_Spr12_05052016 | https://github.com/rajeshgnanam/SOAS_2.1_Spr12_05052016 | 13fc3b3637a8326f5ef61e1ca417067019b68341 | 01e3d6d60957cea35fbfae3a243de70f6aafb350 | refs/heads/release-2.1 | 2017-05-05T09:03:00.425000 | 2017-03-09T10:42:44 | 2017-03-09T10:42:44 | 58,110,532 | 0 | 1 | null | false | 2017-03-09T09:23:50 | 2016-05-05T06:49:15 | 2016-05-06T07:33:54 | 2017-03-09T09:23:50 | 153,885 | 0 | 1 | 0 | Java | null | null | package org.kuali.ole.deliver.controller;
import org.apache.log4j.Logger;
import org.kuali.ole.deliver.form.LoanHistoryUpdateForm;
import org.kuali.ole.deliver.form.OleNoticeForm;
import org.kuali.ole.deliver.util.LoanHistoryUtil;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.web.controller.UifControllerBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by gopalp on 3/18/16.
*/
@Controller
@RequestMapping(value = "/loanHistoryUpdateController")
public class LoanHistoryUpdateController extends UifControllerBase {
private static final Logger LOG = Logger.getLogger(LoanHistoryUpdateController.class);
private LoanHistoryUtil loanHistoryUtil;
public LoanHistoryUtil getLoanHistoryUtil() {
if(loanHistoryUtil == null){
loanHistoryUtil = new LoanHistoryUtil();
}
return loanHistoryUtil;
}
@Override
protected LoanHistoryUpdateForm createInitialForm(HttpServletRequest request) {
return new LoanHistoryUpdateForm();
}
@Override
@RequestMapping(params = "methodToCall=start")
public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
return getUIFModelAndView(form);
}
@RequestMapping(params = "methodToCall=update")
public ModelAndView update(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
try{
getLoanHistoryUtil().populateCirculationHistoryTable();
}catch (Exception e){
LOG.info("Exception occured while running the job" + e.getMessage());
}
return getUIFModelAndView(form);
}
}
| UTF-8 | Java | 2,223 | java | LoanHistoryUpdateController.java | Java | [
{
"context": "rvlet.http.HttpServletResponse;\n\n/**\n * Created by gopalp on 3/18/16.\n */\n@Controller\n@RequestMapping(value",
"end": 801,
"score": 0.9996790885925293,
"start": 795,
"tag": "USERNAME",
"value": "gopalp"
}
] | null | [] | package org.kuali.ole.deliver.controller;
import org.apache.log4j.Logger;
import org.kuali.ole.deliver.form.LoanHistoryUpdateForm;
import org.kuali.ole.deliver.form.OleNoticeForm;
import org.kuali.ole.deliver.util.LoanHistoryUtil;
import org.kuali.rice.krad.service.BusinessObjectService;
import org.kuali.rice.krad.web.controller.UifControllerBase;
import org.kuali.rice.krad.web.form.UifFormBase;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by gopalp on 3/18/16.
*/
@Controller
@RequestMapping(value = "/loanHistoryUpdateController")
public class LoanHistoryUpdateController extends UifControllerBase {
private static final Logger LOG = Logger.getLogger(LoanHistoryUpdateController.class);
private LoanHistoryUtil loanHistoryUtil;
public LoanHistoryUtil getLoanHistoryUtil() {
if(loanHistoryUtil == null){
loanHistoryUtil = new LoanHistoryUtil();
}
return loanHistoryUtil;
}
@Override
protected LoanHistoryUpdateForm createInitialForm(HttpServletRequest request) {
return new LoanHistoryUpdateForm();
}
@Override
@RequestMapping(params = "methodToCall=start")
public ModelAndView start(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
return getUIFModelAndView(form);
}
@RequestMapping(params = "methodToCall=update")
public ModelAndView update(@ModelAttribute("KualiForm") UifFormBase form, BindingResult result,
HttpServletRequest request, HttpServletResponse response) {
try{
getLoanHistoryUtil().populateCirculationHistoryTable();
}catch (Exception e){
LOG.info("Exception occured while running the job" + e.getMessage());
}
return getUIFModelAndView(form);
}
}
| 2,223 | 0.747638 | 0.744939 | 56 | 38.69643 | 28.75321 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.535714 | false | false | 9 |
14ed6d628778978e75d02048e7eebfbae747069d | 16,569,983,848,212 | c3ce69173ac33a1d424e26d3824bf4f77f610345 | /restlet-jaxrs-spring-hibernate-example/src/main/java/com/example/service/util/ServiceMessage.java | 7242f19f5b1af92f1e9183f14897eb0ad23d62ad | [] | no_license | kalevish/restful-service | https://github.com/kalevish/restful-service | 3a18ee1f861fb1a0db081b862600d45df11b8929 | 495a469669c6c7c735d1dd26c9ca2d1e8056f575 | refs/heads/master | 2018-01-09T18:36:45.293000 | 2016-03-14T03:33:28 | 2016-03-14T03:33:28 | 53,823,124 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.service.util;
import java.util.ArrayList;
import java.util.List;
public class ServiceMessage {
private List<String> message;
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
public void addMessage(String message){
if (message == null )
this.message = new ArrayList<String> ();
this.message.add(message);
}
public boolean hasErrors(){
return (message != null && message.size() == 0);
}
}
| UTF-8 | Java | 516 | java | ServiceMessage.java | Java | [] | null | [] | package com.example.service.util;
import java.util.ArrayList;
import java.util.List;
public class ServiceMessage {
private List<String> message;
public List<String> getMessage() {
return message;
}
public void setMessage(List<String> message) {
this.message = message;
}
public void addMessage(String message){
if (message == null )
this.message = new ArrayList<String> ();
this.message.add(message);
}
public boolean hasErrors(){
return (message != null && message.size() == 0);
}
}
| 516 | 0.695736 | 0.693798 | 27 | 18.111111 | 16.888159 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.222222 | false | false | 9 |
507ec48792e9e02627f194a51ce15458a70d1672 | 4,432,406,280,330 | 68cd958da794fb6f0c891bbbc05cb7c3aac67e31 | /src/main/java/kodlamaio/hrms/entities/dtos/LanguageDto.java | f2f651160d68557fd6f57234e6b7d9b6d4fbe36f | [] | no_license | m19yurttutar/HrmsBackend | https://github.com/m19yurttutar/HrmsBackend | c3320dba5f54c1c051e8195fc544b7f9eb33d9c8 | fd99320b0bd8141a55718000409033d35912757d | refs/heads/master | 2023-06-04T06:24:23.620000 | 2021-06-24T18:29:20 | 2021-06-24T18:29:20 | 366,025,274 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kodlamaio.hrms.entities.dtos;
import kodlamaio.hrms.core.entities.abstracts.Dto;
import lombok.Data;
@Data
public class LanguageDto implements Dto {
private String language;
private int languageLevel;
}
| UTF-8 | Java | 221 | java | LanguageDto.java | Java | [] | null | [] | package kodlamaio.hrms.entities.dtos;
import kodlamaio.hrms.core.entities.abstracts.Dto;
import lombok.Data;
@Data
public class LanguageDto implements Dto {
private String language;
private int languageLevel;
}
| 221 | 0.78733 | 0.78733 | 10 | 21.1 | 17.801405 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
165186f84f3e4120710523241b12d1c52d14e9de | 32,916,629,376,873 | 506b2bf8db1e7c72bfc7d88b88a0ad8e608c14c9 | /ArrayExercise_InsertingElements.java | 9e41c03995393e5d976682ccecc4ba083115507e | [] | no_license | sebastienrevis/ExercisesFundamentalsWeek | https://github.com/sebastienrevis/ExercisesFundamentalsWeek | 8db0f1d3b7403230f8a0acc139fc64a895e6254b | b53054e60d640ea791a760d77a08a29c7b2072d1 | refs/heads/master | 2022-11-10T01:54:44.124000 | 2020-07-03T12:01:26 | 2020-07-03T12:01:26 | 276,889,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package be.vdab.Arrays;
import java.util.Arrays;
public class ArrayExercise_InsertingElements {
public static void main(String args[]) {
// Define an array and assign a variable that calculates the length of the array
int[] arrayOriginal = {1, 2, 3, 4, 5, 6, 7, 8};
int l = arrayOriginal.length;
// Define a new element with value 'newValue' at the 'Index_position' of the array
int newValue = 9;
int indexNewValue = 3;
// Print out the original array (this must be done before the insertion loop)
System.out.println("Original Array : "+Arrays.toString(arrayOriginal));
// Select all the elements above the new index value using a decreasing for loop that
// runs from the last index value until but excluding the index value of the new element
for(int i=l-1; i > indexNewValue; i--){
arrayOriginal[i] = arrayOriginal[i-1];
}
// Insert the new element with its defined value and position in the array
arrayOriginal[indexNewValue] = newValue;
// Print out the new array (this must be done after the insertion loop)
System.out.println("New Array: "+Arrays.toString(arrayOriginal));
}
}
| UTF-8 | Java | 1,345 | java | ArrayExercise_InsertingElements.java | Java | [] | null | [] | package be.vdab.Arrays;
import java.util.Arrays;
public class ArrayExercise_InsertingElements {
public static void main(String args[]) {
// Define an array and assign a variable that calculates the length of the array
int[] arrayOriginal = {1, 2, 3, 4, 5, 6, 7, 8};
int l = arrayOriginal.length;
// Define a new element with value 'newValue' at the 'Index_position' of the array
int newValue = 9;
int indexNewValue = 3;
// Print out the original array (this must be done before the insertion loop)
System.out.println("Original Array : "+Arrays.toString(arrayOriginal));
// Select all the elements above the new index value using a decreasing for loop that
// runs from the last index value until but excluding the index value of the new element
for(int i=l-1; i > indexNewValue; i--){
arrayOriginal[i] = arrayOriginal[i-1];
}
// Insert the new element with its defined value and position in the array
arrayOriginal[indexNewValue] = newValue;
// Print out the new array (this must be done after the insertion loop)
System.out.println("New Array: "+Arrays.toString(arrayOriginal));
}
}
| 1,345 | 0.607435 | 0.598513 | 31 | 41.387096 | 36.066853 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 9 |
c799dd13b171dedaf5d7c0de1a4e3335004e9502 | 32,238,024,568,700 | 32f38cd53372ba374c6dab6cc27af78f0a1b0190 | /app/src/main/java/com/alipay/mobile/tinyappcommon/a/c.java | f1047e27b1252c9c02c10aaa2236ddcc2bc6b598 | [] | no_license | shuixi2013/AmapCode | https://github.com/shuixi2013/AmapCode | 9ea7aefb42e0413f348f238f0721c93245f4eac6 | 1a3a8d4dddfcc5439df8df570000cca12b15186a | refs/heads/master | 2023-06-06T23:08:57.391000 | 2019-08-29T04:36:02 | 2019-08-29T04:36:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.alipay.mobile.tinyappcommon.a;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import com.alipay.mobile.liteprocess.LiteProcess;
import com.alipay.mobile.liteprocess.LiteProcessApi;
import com.alipay.mobile.liteprocess.ipc.IpcMsgClient;
import com.alipay.mobile.liteprocess.ipc.IpcMsgServer;
import com.alipay.mobile.nebula.util.H5Log;
import java.util.List;
/* compiled from: IPCUtils */
public class c {
private static final String a = c.class.getSimpleName();
public static void a(int what, String appId, Bundle data) {
try {
if (!data.isEmpty() && !TextUtils.isEmpty(appId)) {
Bundle bundle = new Bundle(data);
long time = System.currentTimeMillis();
H5Log.d(a, "sendDataToLiteProcess...appId " + appId + ", what=" + what + ",logTag=" + time);
List liteProcessList = LiteProcessApi.getAllAliveProcess();
if (liteProcessList == null || liteProcessList.isEmpty()) {
H5Log.d(a, "sendDataToLiteProcess...all alive process is empty, appId " + appId);
return;
}
bundle.putLong("logTag", time);
for (LiteProcess liteProcess : liteProcessList) {
if (appId.equals(liteProcess.getAppId())) {
a(liteProcess, what, bundle);
}
}
}
} catch (Throwable throwable) {
H5Log.e(a, "sendDataToLiteProcess...e=" + throwable);
}
}
public static void a(String appId, String key, String value) {
if (!TextUtils.isEmpty(key)) {
Bundle data = new Bundle();
data.putString(key, value);
a(1, appId, data);
}
}
public static void a(Bundle data) {
if (data != null) {
List<LiteProcess> allLiteProcessList = LiteProcessApi.getAllAliveProcess();
if (allLiteProcessList != null) {
long time = System.currentTimeMillis();
H5Log.d(a, "sendDataToAllLiteProcess..." + allLiteProcessList.size() + ",logTag=" + time);
Bundle bundle = new Bundle(data);
bundle.putLong("logTag", time);
for (LiteProcess a2 : allLiteProcessList) {
a(a2, 1, bundle);
}
}
}
}
private static void a(LiteProcess liteProcess, int what, Bundle data) {
if (liteProcess != null) {
Message message = Message.obtain();
message.what = what;
message.setData(data);
IpcMsgServer.reply(liteProcess.getReplyTo(), "TINY_APP_BIZ", message);
}
}
public static void a(int what, Bundle bundle) {
Bundle data;
if (bundle == null) {
data = new Bundle();
} else {
data = new Bundle(bundle);
}
long time = System.currentTimeMillis();
data.putLong("logTag", time);
H5Log.d(a, "sendDataToMainProcess...logTag:" + time);
Message message = Message.obtain();
message.what = what;
message.setData(data);
IpcMsgClient.send("TINY_APP_BIZ", message);
}
public static void a(Messenger replyTo, int what, Bundle data) {
Bundle bundle;
if (replyTo != null) {
if (data == null) {
bundle = new Bundle();
} else {
bundle = new Bundle(data);
}
long time = System.currentTimeMillis();
bundle.putLong("logTag", time);
H5Log.d(a, "replyDataToLiteProcess...logTag:" + time);
Message message = Message.obtain();
message.what = what;
message.setData(bundle);
IpcMsgServer.reply(replyTo, "TINY_APP_BIZ", message);
}
}
}
| UTF-8 | Java | 3,934 | java | c.java | Java | [] | null | [] | package com.alipay.mobile.tinyappcommon.a;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import com.alipay.mobile.liteprocess.LiteProcess;
import com.alipay.mobile.liteprocess.LiteProcessApi;
import com.alipay.mobile.liteprocess.ipc.IpcMsgClient;
import com.alipay.mobile.liteprocess.ipc.IpcMsgServer;
import com.alipay.mobile.nebula.util.H5Log;
import java.util.List;
/* compiled from: IPCUtils */
public class c {
private static final String a = c.class.getSimpleName();
public static void a(int what, String appId, Bundle data) {
try {
if (!data.isEmpty() && !TextUtils.isEmpty(appId)) {
Bundle bundle = new Bundle(data);
long time = System.currentTimeMillis();
H5Log.d(a, "sendDataToLiteProcess...appId " + appId + ", what=" + what + ",logTag=" + time);
List liteProcessList = LiteProcessApi.getAllAliveProcess();
if (liteProcessList == null || liteProcessList.isEmpty()) {
H5Log.d(a, "sendDataToLiteProcess...all alive process is empty, appId " + appId);
return;
}
bundle.putLong("logTag", time);
for (LiteProcess liteProcess : liteProcessList) {
if (appId.equals(liteProcess.getAppId())) {
a(liteProcess, what, bundle);
}
}
}
} catch (Throwable throwable) {
H5Log.e(a, "sendDataToLiteProcess...e=" + throwable);
}
}
public static void a(String appId, String key, String value) {
if (!TextUtils.isEmpty(key)) {
Bundle data = new Bundle();
data.putString(key, value);
a(1, appId, data);
}
}
public static void a(Bundle data) {
if (data != null) {
List<LiteProcess> allLiteProcessList = LiteProcessApi.getAllAliveProcess();
if (allLiteProcessList != null) {
long time = System.currentTimeMillis();
H5Log.d(a, "sendDataToAllLiteProcess..." + allLiteProcessList.size() + ",logTag=" + time);
Bundle bundle = new Bundle(data);
bundle.putLong("logTag", time);
for (LiteProcess a2 : allLiteProcessList) {
a(a2, 1, bundle);
}
}
}
}
private static void a(LiteProcess liteProcess, int what, Bundle data) {
if (liteProcess != null) {
Message message = Message.obtain();
message.what = what;
message.setData(data);
IpcMsgServer.reply(liteProcess.getReplyTo(), "TINY_APP_BIZ", message);
}
}
public static void a(int what, Bundle bundle) {
Bundle data;
if (bundle == null) {
data = new Bundle();
} else {
data = new Bundle(bundle);
}
long time = System.currentTimeMillis();
data.putLong("logTag", time);
H5Log.d(a, "sendDataToMainProcess...logTag:" + time);
Message message = Message.obtain();
message.what = what;
message.setData(data);
IpcMsgClient.send("TINY_APP_BIZ", message);
}
public static void a(Messenger replyTo, int what, Bundle data) {
Bundle bundle;
if (replyTo != null) {
if (data == null) {
bundle = new Bundle();
} else {
bundle = new Bundle(data);
}
long time = System.currentTimeMillis();
bundle.putLong("logTag", time);
H5Log.d(a, "replyDataToLiteProcess...logTag:" + time);
Message message = Message.obtain();
message.what = what;
message.setData(bundle);
IpcMsgServer.reply(replyTo, "TINY_APP_BIZ", message);
}
}
}
| 3,934 | 0.556939 | 0.554143 | 106 | 36.113209 | 24.686457 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.858491 | false | false | 9 |
3bf3307eda7ba2ebbbc7d34614aa92aa8fc785e4 | 33,672,543,640,158 | cb2cd360f524e6fbaeff5a3d6a89fb5933200967 | /src/InputAndExecution.java | 1376337e95a8d20982609cd957eb7306b9f94c10 | [] | no_license | green-fox-academy/karczubm-todo-app | https://github.com/green-fox-academy/karczubm-todo-app | 01cf0328d84d4e50221dee103f715ebae8d3448b | 2364523312b8030de7a23b5eab3f00450a82c2a1 | refs/heads/master | 2022-02-28T13:11:20.834000 | 2019-10-03T15:33:56 | 2019-10-03T15:33:56 | 212,535,391 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
public class InputAndExecution {
ToDo toDoObject;
Scanner sc = new Scanner(System.in);
private Path myPath;
private List<String> myFile;
public InputAndExecution(String fileName) {
myPath = Paths.get(fileName);
try {
myFile = Files.readAllLines(myPath);
} catch (IOException e) {
System.out.println("File not found!");
}
toDoObject = new ToDo(myFile);
toDoObject.usageInformation();
}
public String inputFromUser() {
return sc.nextLine();
}
public void nextCommand() {
System.out.println("Next command:");
}
public void saveTasksToFile() {
myFile.clear();
for (Thing thing : toDoObject.thingsToDo) {
if (thing.isReady()) {
myFile.add("1" + thing.getTaskDescription());
} else {
myFile.add("0" + thing.getTaskDescription());
}
}
try {
Files.write(myPath, myFile);
} catch (IOException e) {
System.out.println("Unable to write in file!");
}
}
public void todo(String inputFromUser) {
String argument = inputFromUser.substring(0, 2);
if (inputFromUser.length() == 2 || inputFromUser.charAt(2) == ' ') {
switch (argument) {
case "-l":
toDoObject.listTasks();
break;
case "-u":
toDoObject.listOfUndoneTasks();
break;
case "-a":
try {
toDoObject.addNewTask(inputFromUser.trim().substring(3));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Unable to add: no task provided!");
break;
}
case "-r":
try {
toDoObject.removeTask(Integer.parseInt(inputFromUser.trim().substring(3)));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("No index provided!");
break;
} catch (IndexOutOfBoundsException e) {
System.out.println("Index is out of bound!");
break;
} catch (NumberFormatException e) {
System.out.println("Index is not a number!");
break;
}
case "-c":
try {
toDoObject.completeTask(Integer.parseInt(inputFromUser.trim().substring(3)));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("No index provided!");
break;
} catch (IndexOutOfBoundsException e) {
System.out.println("Index is out of bound!");
break;
} catch (NumberFormatException e) {
System.out.println("Index is not a number!");
break;
}
default:
System.out.println("Unsupported argument!");
toDoObject.usageInformation();
}
} else {
System.out.println("Invalid command!");
}
saveTasksToFile();
}
}
| UTF-8 | Java | 3,708 | java | InputAndExecution.java | Java | [] | null | [] | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
public class InputAndExecution {
ToDo toDoObject;
Scanner sc = new Scanner(System.in);
private Path myPath;
private List<String> myFile;
public InputAndExecution(String fileName) {
myPath = Paths.get(fileName);
try {
myFile = Files.readAllLines(myPath);
} catch (IOException e) {
System.out.println("File not found!");
}
toDoObject = new ToDo(myFile);
toDoObject.usageInformation();
}
public String inputFromUser() {
return sc.nextLine();
}
public void nextCommand() {
System.out.println("Next command:");
}
public void saveTasksToFile() {
myFile.clear();
for (Thing thing : toDoObject.thingsToDo) {
if (thing.isReady()) {
myFile.add("1" + thing.getTaskDescription());
} else {
myFile.add("0" + thing.getTaskDescription());
}
}
try {
Files.write(myPath, myFile);
} catch (IOException e) {
System.out.println("Unable to write in file!");
}
}
public void todo(String inputFromUser) {
String argument = inputFromUser.substring(0, 2);
if (inputFromUser.length() == 2 || inputFromUser.charAt(2) == ' ') {
switch (argument) {
case "-l":
toDoObject.listTasks();
break;
case "-u":
toDoObject.listOfUndoneTasks();
break;
case "-a":
try {
toDoObject.addNewTask(inputFromUser.trim().substring(3));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Unable to add: no task provided!");
break;
}
case "-r":
try {
toDoObject.removeTask(Integer.parseInt(inputFromUser.trim().substring(3)));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("No index provided!");
break;
} catch (IndexOutOfBoundsException e) {
System.out.println("Index is out of bound!");
break;
} catch (NumberFormatException e) {
System.out.println("Index is not a number!");
break;
}
case "-c":
try {
toDoObject.completeTask(Integer.parseInt(inputFromUser.trim().substring(3)));
break;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("No index provided!");
break;
} catch (IndexOutOfBoundsException e) {
System.out.println("Index is out of bound!");
break;
} catch (NumberFormatException e) {
System.out.println("Index is not a number!");
break;
}
default:
System.out.println("Unsupported argument!");
toDoObject.usageInformation();
}
} else {
System.out.println("Invalid command!");
}
saveTasksToFile();
}
}
| 3,708 | 0.47438 | 0.471953 | 104 | 34.653847 | 22.264481 | 101 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528846 | false | false | 9 |
65a7d36c465959d6e295f8d9ab6d245ad3855473 | 29,042,568,889,801 | 2f75c5da4855431281d8df9d7be33dbb52c0bee9 | /RED_ShoppingMall/src/main/java/com/itwill/red/service/impl/WishListServiceImpl.java | 5a659c1cb8253c0d3e9ab7dbcd730f1fe1944785 | [] | no_license | 0chun/1511_itwill_3rd | https://github.com/0chun/1511_itwill_3rd | 91646169b7ac60cee3a5af0b7310a0d9c790f6f7 | 13b6be6dc3e9aa57c438f64fbdc2b35180b5c3cb | refs/heads/master | 2021-01-21T21:47:52.624000 | 2015-12-29T09:01:16 | 2015-12-29T09:01:16 | 48,176,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itwill.red.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.itwill.red.dao.WishListDao;
import com.itwill.red.dto.Product;
import com.itwill.red.dto.WishList;
import com.itwill.red.service.ProductService;
import com.itwill.red.service.WishListService;
public class WishListServiceImpl implements WishListService {
WishListDao wishListDao;
ProductService productService;
public void setProductService(ProductService productService) {
this.productService = productService;
}
public void setWishListDao(WishListDao wishListDao) {
this.wishListDao = wishListDao;
}
@Override
public WishList selectByMemberId(String w_m_id) throws Exception {
return wishListDao.selectByMemberId(w_m_id);
}
@Override
public List<WishList> selectAll() throws Exception {
return wishListDao.selectAll();
}
@Override
public int selectCount(String w_m_id) {
return wishListDao.selectCount(w_m_id);
}
@Override
public int insertWish(HashMap<String, Object> insertMap) throws Exception {
return wishListDao.insertWish(insertMap);
}
@Override
public int insertWishDetail(HashMap<String, Object> insertMap) {
return wishListDao.insertWishDetail(insertMap);
}
@Override
public List<Product> findProductList(String w_m_id){ // 아이디로 위시리스트에 상품가져오기
WishList wishList = null;
List<Product> productList = new ArrayList<Product>();
int p_no = 0;
try {
wishList = wishListDao.selectByMemberId(w_m_id); // 아이디로 wishlist + wishlist_detail 찾기
for (int i = 0; i < wishList.getWishList_Detail().size(); i++) {
p_no = wishList.getWishList_Detail().get(i).getWd_p_no(); // 아이디가 가진 상품번호 찾기
productList.add(productService.findByNo(p_no));
}
} catch (Exception e) {
e.printStackTrace();
}
return productList;
}
@Override
public int removeProduct(HashMap<String, Object> insertMap) {
return wishListDao.removeProduct(insertMap);
}
@Override
public int selectWnoByMemberId(String w_m_id) {
return wishListDao.selectWnoByMemberId(w_m_id);
}
}
| UTF-8 | Java | 2,125 | java | WishListServiceImpl.java | Java | [] | null | [] | package com.itwill.red.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.itwill.red.dao.WishListDao;
import com.itwill.red.dto.Product;
import com.itwill.red.dto.WishList;
import com.itwill.red.service.ProductService;
import com.itwill.red.service.WishListService;
public class WishListServiceImpl implements WishListService {
WishListDao wishListDao;
ProductService productService;
public void setProductService(ProductService productService) {
this.productService = productService;
}
public void setWishListDao(WishListDao wishListDao) {
this.wishListDao = wishListDao;
}
@Override
public WishList selectByMemberId(String w_m_id) throws Exception {
return wishListDao.selectByMemberId(w_m_id);
}
@Override
public List<WishList> selectAll() throws Exception {
return wishListDao.selectAll();
}
@Override
public int selectCount(String w_m_id) {
return wishListDao.selectCount(w_m_id);
}
@Override
public int insertWish(HashMap<String, Object> insertMap) throws Exception {
return wishListDao.insertWish(insertMap);
}
@Override
public int insertWishDetail(HashMap<String, Object> insertMap) {
return wishListDao.insertWishDetail(insertMap);
}
@Override
public List<Product> findProductList(String w_m_id){ // 아이디로 위시리스트에 상품가져오기
WishList wishList = null;
List<Product> productList = new ArrayList<Product>();
int p_no = 0;
try {
wishList = wishListDao.selectByMemberId(w_m_id); // 아이디로 wishlist + wishlist_detail 찾기
for (int i = 0; i < wishList.getWishList_Detail().size(); i++) {
p_no = wishList.getWishList_Detail().get(i).getWd_p_no(); // 아이디가 가진 상품번호 찾기
productList.add(productService.findByNo(p_no));
}
} catch (Exception e) {
e.printStackTrace();
}
return productList;
}
@Override
public int removeProduct(HashMap<String, Object> insertMap) {
return wishListDao.removeProduct(insertMap);
}
@Override
public int selectWnoByMemberId(String w_m_id) {
return wishListDao.selectWnoByMemberId(w_m_id);
}
}
| 2,125 | 0.750608 | 0.749635 | 78 | 25.371796 | 24.832314 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.551282 | false | false | 9 |
4fa9b8ac75da8ac6d776089c2381b09a2c57101c | 5,815,385,734,895 | 4212172829d805b39fde0fd987d018db10e2b225 | /TicTacToe/Start.java | 5b01466d86a6f675640b475503e9f3c8477984a8 | [] | no_license | fanfreak247/Beginner-Projects | https://github.com/fanfreak247/Beginner-Projects | 8a4e5773dd71d19960d71d1acf8457c15f35be70 | c75d073c385264f7668eff0cff4e9ce62253cc16 | refs/heads/master | 2021-05-07T17:39:48.774000 | 2017-11-10T04:33:58 | 2017-11-10T04:33:58 | 108,699,421 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
Copyright © FanFreak247 All rights reserved.
Permission granted to reproduce for personal and educational use only. Commercial copying, hiring, lending is prohibited.
May be used free of charge. Selling without prior written consent prohibited. Obtain permission before redistributing. In all cases this notice must remain intact.
*/
import java.util.Scanner;
public class Start
{
public static void main(String[] args)
{
TicTacToe game = new TicTacToe();
System.out.println("Welcome to Tic Tac Toe");
while (true)
{
game.printBoard();
game.position(true);
if (game.checkWin()>0 || game.checkTie()) break;
game.printBoard();
game.position(false);
if (game.checkWin() > 0 || game.checkTie()) break;
}
game.printBoard();
if (game.checkWin() > 0) System.out.println("Player " + game.checkWin() + " is the winner. Congrats :D");
else System.out.println("The game ended in a tie. Too bad.");
}
} | UTF-8 | Java | 1,077 | java | Start.java | Java | [
{
"context": "/*\r\n Copyright © FanFreak247 All rights reserved.\r\n Permission granted to re",
"end": 29,
"score": 0.9995194673538208,
"start": 18,
"tag": "USERNAME",
"value": "FanFreak247"
}
] | null | [] | /*
Copyright © FanFreak247 All rights reserved.
Permission granted to reproduce for personal and educational use only. Commercial copying, hiring, lending is prohibited.
May be used free of charge. Selling without prior written consent prohibited. Obtain permission before redistributing. In all cases this notice must remain intact.
*/
import java.util.Scanner;
public class Start
{
public static void main(String[] args)
{
TicTacToe game = new TicTacToe();
System.out.println("Welcome to Tic Tac Toe");
while (true)
{
game.printBoard();
game.position(true);
if (game.checkWin()>0 || game.checkTie()) break;
game.printBoard();
game.position(false);
if (game.checkWin() > 0 || game.checkTie()) break;
}
game.printBoard();
if (game.checkWin() > 0) System.out.println("Player " + game.checkWin() + " is the winner. Congrats :D");
else System.out.println("The game ended in a tie. Too bad.");
}
} | 1,077 | 0.615242 | 0.609665 | 27 | 37.925926 | 39.962875 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
4916373386281d8d57150b6d3eac8ebafe294763 | 18,159,121,749,168 | 81524d3d65baa71c976d9990d72965eb558d3e57 | /njams-sdk/src/main/java/com/im/njams/sdk/argos/ArgosMultiCollector.java | c243f53abd9cda8b667b99dbb1322f3c20692bb0 | [
"JSON"
] | permissive | IntegrationMatters/njams-sdk | https://github.com/IntegrationMatters/njams-sdk | 89916141d56e32c73cd508f0c20e1f326c0dacd4 | a0eefe1360d841819f0ee0eed447c1f44f14cf4b | refs/heads/master | 2023-07-05T09:45:43.849000 | 2023-06-28T12:15:05 | 2023-06-28T12:15:05 | 139,853,884 | 7 | 3 | NOASSERTION | false | 2022-05-19T08:25:53 | 2018-07-05T13:30:47 | 2022-02-24T11:02:23 | 2022-05-19T08:25:52 | 14,051 | 7 | 2 | 0 | Java | false | false | /*
* Copyright (c) 2019 Faiz & Siegeln Software GmbH
*
* 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 shall be used for Good, not Evil.
*
* 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.im.njams.sdk.argos;
import java.util.Collection;
/**
* Abstract base class for an ArgosCollector that collects several metrics of the same type.
* <p>
* Extend this class, implement the collect method and register it in {@link ArgosSender}
*
* @param <T> The type of the metric that this collector creates.
* @see ArgosCollector
*/
public abstract class ArgosMultiCollector<T extends ArgosMetric> {
private ArgosComponent argosComponent;
/**
* Sets the given ArgosComponent.
*
* @param argosComponent the argosComponent to set.
*/
public ArgosMultiCollector(ArgosComponent argosComponent) {
this.argosComponent = argosComponent;
}
/**
* Returns the ArgosComponent for this collector.
*
* @return the argosComponent for this collector.
*/
public ArgosComponent getArgosComponent() {
return argosComponent;
}
/**
* Overwrite this method in your implementation of this class.
* <p>
* Create a collection of {@link ArgosMetric} and return it.
*
* @return the created {@link ArgosMetric}s
*/
protected abstract Collection<T> createAll();
/**
* This gets called by {@link ArgosSender} in periodic manner.
* <p>
* It will collect {@link ArgosMetric}s from this implementation
* and send it to the configured agent.
*
* @return the collected {@link ArgosMetric}s
*/
public Collection<T> collectAll() {
return createAll();
}
}
| UTF-8 | Java | 2,702 | java | ArgosMultiCollector.java | Java | [] | null | [] | /*
* Copyright (c) 2019 Faiz & Siegeln Software GmbH
*
* 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 shall be used for Good, not Evil.
*
* 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.im.njams.sdk.argos;
import java.util.Collection;
/**
* Abstract base class for an ArgosCollector that collects several metrics of the same type.
* <p>
* Extend this class, implement the collect method and register it in {@link ArgosSender}
*
* @param <T> The type of the metric that this collector creates.
* @see ArgosCollector
*/
public abstract class ArgosMultiCollector<T extends ArgosMetric> {
private ArgosComponent argosComponent;
/**
* Sets the given ArgosComponent.
*
* @param argosComponent the argosComponent to set.
*/
public ArgosMultiCollector(ArgosComponent argosComponent) {
this.argosComponent = argosComponent;
}
/**
* Returns the ArgosComponent for this collector.
*
* @return the argosComponent for this collector.
*/
public ArgosComponent getArgosComponent() {
return argosComponent;
}
/**
* Overwrite this method in your implementation of this class.
* <p>
* Create a collection of {@link ArgosMetric} and return it.
*
* @return the created {@link ArgosMetric}s
*/
protected abstract Collection<T> createAll();
/**
* This gets called by {@link ArgosSender} in periodic manner.
* <p>
* It will collect {@link ArgosMetric}s from this implementation
* and send it to the configured agent.
*
* @return the collected {@link ArgosMetric}s
*/
public Collection<T> collectAll() {
return createAll();
}
}
| 2,702 | 0.706144 | 0.704663 | 75 | 35.026669 | 37.410862 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.413333 | false | false | 9 |
fff8d93eb5798b3bb5430cdb77c244400409ecc4 | 33,277,406,622,455 | 0a1bd64051f2ba3d23742bfdbbf260f932ea39bb | /app/src/main/java/com/lidchanin/crudindiploma/activity/AddingShoppingListActivity.java | 74c78f81b763312ae935e0b8ef0fb6bee31fc6fe | [] | no_license | Lidchanin/CRUDinDiploma | https://github.com/Lidchanin/CRUDinDiploma | 0f3bf35e71faab250d9a61f83bf2c7044703832f | a6c8e167d5cadbeb2080daa33e8d64073e658d08 | refs/heads/master | 2021-01-19T02:51:54.005000 | 2017-05-16T18:06:49 | 2017-05-16T18:06:49 | 87,299,544 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lidchanin.crudindiploma.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.lidchanin.crudindiploma.R;
import com.lidchanin.crudindiploma.data.dao.ShoppingListDAO;
import com.lidchanin.crudindiploma.data.model.ShoppingList;
/**
* Class <code>AddingShoppingListActivity</code> is a activity and extends
* {@link AppCompatActivity}. Here you can create a new shopping list.
*
* @author Lidchanin
* @see android.app.Activity
*/
public class AddingShoppingListActivity extends AppCompatActivity {
private EditText editTextEnterNameShoppingList;
private ShoppingListDAO shoppingListDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_shopping_list);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
shoppingListDAO = new ShoppingListDAO(this);
initializeButtons();
}
@Override
protected void onResume() {
super.onResume();
shoppingListDAO.open();
}
@Override
protected void onPause() {
super.onPause();
shoppingListDAO.close();
}
/**
* Method <code>initializeViewsAndButtons</code> initialize views and buttons and add them an
* actions or other properties.
*/
public void initializeButtons() {
editTextEnterNameShoppingList = (EditText)
findViewById(R.id.adding_shopping_list_edit_text_enter_shopping_list_name);
Button buttonAddShoppingList = (Button)
findViewById(R.id.adding_shopping_list_button_add_shopping_list);
buttonAddShoppingList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editTextEnterNameShoppingList.getText().length() >= 3) {
long shoppingListId = shoppingListDAO.add(
new ShoppingList(editTextEnterNameShoppingList.getText().toString()));
Intent intent = new Intent(AddingShoppingListActivity.this,
InsideShoppingListActivity.class);
intent.putExtra("shoppingListId", shoppingListId);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Uncorrected name!", Toast.LENGTH_SHORT)
.show();
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(AddingShoppingListActivity.this, MainScreenActivity.class);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| UTF-8 | Java | 3,086 | java | AddingShoppingListActivity.java | Java | [
{
"context": " you can create a new shopping list.\n *\n * @author Lidchanin\n * @see android.app.Activity\n */\npublic class Add",
"end": 634,
"score": 0.9809242486953735,
"start": 625,
"tag": "NAME",
"value": "Lidchanin"
}
] | null | [] | package com.lidchanin.crudindiploma.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.lidchanin.crudindiploma.R;
import com.lidchanin.crudindiploma.data.dao.ShoppingListDAO;
import com.lidchanin.crudindiploma.data.model.ShoppingList;
/**
* Class <code>AddingShoppingListActivity</code> is a activity and extends
* {@link AppCompatActivity}. Here you can create a new shopping list.
*
* @author Lidchanin
* @see android.app.Activity
*/
public class AddingShoppingListActivity extends AppCompatActivity {
private EditText editTextEnterNameShoppingList;
private ShoppingListDAO shoppingListDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_adding_shopping_list);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
shoppingListDAO = new ShoppingListDAO(this);
initializeButtons();
}
@Override
protected void onResume() {
super.onResume();
shoppingListDAO.open();
}
@Override
protected void onPause() {
super.onPause();
shoppingListDAO.close();
}
/**
* Method <code>initializeViewsAndButtons</code> initialize views and buttons and add them an
* actions or other properties.
*/
public void initializeButtons() {
editTextEnterNameShoppingList = (EditText)
findViewById(R.id.adding_shopping_list_edit_text_enter_shopping_list_name);
Button buttonAddShoppingList = (Button)
findViewById(R.id.adding_shopping_list_button_add_shopping_list);
buttonAddShoppingList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (editTextEnterNameShoppingList.getText().length() >= 3) {
long shoppingListId = shoppingListDAO.add(
new ShoppingList(editTextEnterNameShoppingList.getText().toString()));
Intent intent = new Intent(AddingShoppingListActivity.this,
InsideShoppingListActivity.class);
intent.putExtra("shoppingListId", shoppingListId);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Uncorrected name!", Toast.LENGTH_SHORT)
.show();
}
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent(AddingShoppingListActivity.this, MainScreenActivity.class);
startActivity(intent);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| 3,086 | 0.651005 | 0.650356 | 92 | 32.54348 | 27.772528 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.456522 | false | false | 9 |
4b88b1e17f69ec3f16538235f431c30fefa03e4b | 1,529,008,389,029 | c1415dd817008866d0c77e89d345131bb35b0ae1 | /algorithms/src/main/java/algorithms/basics/FindMaxMultuplierPair.java | 656f2442a04dac95612de03dfb7ded366749982c | [] | no_license | keyurmahajan4u/Algorithm | https://github.com/keyurmahajan4u/Algorithm | 4648d63e279f2ae46c5fa51737f4fcc8894d53ca | dc0b6c56f839bf1a099b5bf1e9853a3c1723876d | refs/heads/master | 2021-01-01T04:30:33.996000 | 2020-11-07T17:14:17 | 2020-11-07T17:14:17 | 59,196,139 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algorithms.basics;
/**
* Find max pair multiplier from given int array.
*
* @author keyur.mahajan
*
*/
public class FindMaxMultuplierPair {
private static int[] numbers = { 0, 11, 55, 99, 66, 50, 99, -50, 56 };
public static void main(String[] args) {
int maxNumber = findMaxNumber(numbers);
System.out.println("Max Multiplier from the array = " + maxNumber);
}
private static int findMaxNumber(int[] array) {
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max1 || array[i] > max2) {
max1 = Integer.max(max1, max2);
max2 = array[i];
}
}
return max1 * max2;
}
}
| UTF-8 | Java | 708 | java | FindMaxMultuplierPair.java | Java | [
{
"context": " multiplier from given int array.\r\n * \r\n * @author keyur.mahajan\r\n *\r\n */\r\npublic class FindMaxMultuplierPair {\r\n\t",
"end": 115,
"score": 0.892662525177002,
"start": 102,
"tag": "NAME",
"value": "keyur.mahajan"
}
] | null | [] | package algorithms.basics;
/**
* Find max pair multiplier from given int array.
*
* @author keyur.mahajan
*
*/
public class FindMaxMultuplierPair {
private static int[] numbers = { 0, 11, 55, 99, 66, 50, 99, -50, 56 };
public static void main(String[] args) {
int maxNumber = findMaxNumber(numbers);
System.out.println("Max Multiplier from the array = " + maxNumber);
}
private static int findMaxNumber(int[] array) {
int max1 = Integer.MIN_VALUE;
int max2 = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max1 || array[i] > max2) {
max1 = Integer.max(max1, max2);
max2 = array[i];
}
}
return max1 * max2;
}
}
| 708 | 0.611582 | 0.572034 | 28 | 23.285715 | 21.537106 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.964286 | false | false | 9 |
b9d65d91ab11805354c4bed0dbebb1ded18dccc6 | 4,277,787,434,982 | af47e6e0c34b1361fbdb3aa9529197484711401f | /src/net/lakkie/rubs/storage/UnitGroup.java | 479668241e9f930c3947c2152b4389d80eb38b43 | [] | no_license | LakkieNet/Risk-Universalis-Battle-Simulator | https://github.com/LakkieNet/Risk-Universalis-Battle-Simulator | 193eea159276e42fe2704565ac0e11eb476d0d3e | 53e5ef912d1cdb51b279dcb97d0bf8b9a6ff9ec0 | refs/heads/master | 2020-03-16T23:44:14.730000 | 2018-05-25T04:51:27 | 2018-05-25T04:51:27 | 133,089,516 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.lakkie.rubs.storage;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import net.lakkie.rubs.ai.AIArmyOrder;
import net.lakkie.rubs.ai.RUBSBattleAI;
public class UnitGroup implements Serializable {
private static final long serialVersionUID = 9071012123543856152L;
private final List<PositionedUnit> units = new CopyOnWriteArrayList<PositionedUnit>();
public transient AIArmyOrder order = AIArmyOrder.GENERAL_ADVANCE;
public transient RUBSBattleAI ai;
public void addUnit(PositionedUnit unit) {
this.units.add(unit);
}
public void removeUnit(PositionedUnit unit) {
this.units.remove(unit);
}
public List<PositionedUnit> getUnits() {
return units;
}
public int getTotalTroops() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.getSize();
}
return total;
}
public int getTotalInfantry() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.infantry;
}
return total;
}
public int getTotalCavalry() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.cavalry;
}
return total;
}
public int getTotalArmor() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.armor;
}
return total;
}
public UnitGroup copy() {
UnitGroup result = new UnitGroup();
for (PositionedUnit unit : this.units) {
result.units.add(unit.copy());
}
return result;
}
public String toString() {
return String.format("[units=%s]", this.units);
}
}
| UTF-8 | Java | 1,638 | java | UnitGroup.java | Java | [] | null | [] | package net.lakkie.rubs.storage;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import net.lakkie.rubs.ai.AIArmyOrder;
import net.lakkie.rubs.ai.RUBSBattleAI;
public class UnitGroup implements Serializable {
private static final long serialVersionUID = 9071012123543856152L;
private final List<PositionedUnit> units = new CopyOnWriteArrayList<PositionedUnit>();
public transient AIArmyOrder order = AIArmyOrder.GENERAL_ADVANCE;
public transient RUBSBattleAI ai;
public void addUnit(PositionedUnit unit) {
this.units.add(unit);
}
public void removeUnit(PositionedUnit unit) {
this.units.remove(unit);
}
public List<PositionedUnit> getUnits() {
return units;
}
public int getTotalTroops() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.getSize();
}
return total;
}
public int getTotalInfantry() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.infantry;
}
return total;
}
public int getTotalCavalry() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.cavalry;
}
return total;
}
public int getTotalArmor() {
int total = 0;
for (PositionedUnit unit : this.units) {
total += unit.armor;
}
return total;
}
public UnitGroup copy() {
UnitGroup result = new UnitGroup();
for (PositionedUnit unit : this.units) {
result.units.add(unit.copy());
}
return result;
}
public String toString() {
return String.format("[units=%s]", this.units);
}
}
| 1,638 | 0.675214 | 0.661172 | 73 | 20.438356 | 19.498497 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.69863 | false | false | 9 |
536fced993b012333482fa01c7279f383f3c8a47 | 6,674,379,184,304 | 8466e11135173dc921251cfc35531700f16021f7 | /src/akansha_Jain/Assignment_12/TestCase4.java | 8c424b4f9b2c321e63ea1856ba0dc079ab0b3b1b | [] | no_license | KrishnaKTechnocredits/SeleniumTechnoJuly2021 | https://github.com/KrishnaKTechnocredits/SeleniumTechnoJuly2021 | 7fef38aa843eae2e138736adb4fed9f071fb3c5f | db9c50bb18ec69ccf09834ffa206d198a46dcd65 | refs/heads/master | 2023-09-04T21:12:26.296000 | 2021-11-17T15:59:16 | 2021-11-17T15:59:16 | 418,002,755 | 3 | 0 | null | false | 2021-11-25T08:27:29 | 2021-10-17T02:50:23 | 2021-11-17T15:59:19 | 2021-11-25T08:27:29 | 58,600 | 1 | 0 | 3 | Java | false | false | /* Assignment - 12: 24th Oct'2021
https://datatables.net/extensions/autofill/examples/initialisation/focus.html
Program 4 : sorting works on employee name or not. */
package akansha_Jain.Assignment_12;
import java.util.ArrayList;
import java.util.Collections;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestCase4 {
WebDriver driver;
@BeforeClass
void launchBrowser() {
driver = PredefinedActions.start();
}
ArrayList<String> getEmpNameList() {
ArrayList<String> empNameList = new ArrayList<>();
int totalPages = driver.findElements(By.xpath("//div[@id='example_paginate']/span/a")).size();
for(int index=1; index<=totalPages; index++) {
int totalRows = driver.findElements(By.xpath("//table[@class='display nowrap dataTable']/tbody/tr")).size();
for(int innerIndex=1; innerIndex<=totalRows; innerIndex++) {
String empName = driver.findElement(By.xpath("//table[@class='display nowrap dataTable']/tbody/tr["+innerIndex+"]/td[1]")).getText();
empNameList.add(empName);
}
driver.findElement(By.xpath("//a[@id='example_next']")).click();
}
if(totalPages>0)
driver.findElement(By.xpath("//div[@id='example_paginate']/span/a[1]")).click();
return empNameList;
}
@Test
void testCase4() {
driver.findElement(By.xpath("//table[@class='display nowrap dataTable']/thead/tr/th[1]")).click();
ArrayList<String> actualEmpNameList = getEmpNameList();
System.out.println("STEP- Actual sorted list of employee names- " + actualEmpNameList);
ArrayList<String> expectedEmpNameList = getEmpNameList();
Collections.sort(expectedEmpNameList, Collections.reverseOrder());
System.out.println("STEP- Expected sorted list of employee names- " + expectedEmpNameList);
Assert.assertEquals(actualEmpNameList, expectedEmpNameList);
}
@AfterClass
void closeBrowser() {
driver.close();
}
} | UTF-8 | Java | 2,020 | java | TestCase4.java | Java | [] | null | [] | /* Assignment - 12: 24th Oct'2021
https://datatables.net/extensions/autofill/examples/initialisation/focus.html
Program 4 : sorting works on employee name or not. */
package akansha_Jain.Assignment_12;
import java.util.ArrayList;
import java.util.Collections;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class TestCase4 {
WebDriver driver;
@BeforeClass
void launchBrowser() {
driver = PredefinedActions.start();
}
ArrayList<String> getEmpNameList() {
ArrayList<String> empNameList = new ArrayList<>();
int totalPages = driver.findElements(By.xpath("//div[@id='example_paginate']/span/a")).size();
for(int index=1; index<=totalPages; index++) {
int totalRows = driver.findElements(By.xpath("//table[@class='display nowrap dataTable']/tbody/tr")).size();
for(int innerIndex=1; innerIndex<=totalRows; innerIndex++) {
String empName = driver.findElement(By.xpath("//table[@class='display nowrap dataTable']/tbody/tr["+innerIndex+"]/td[1]")).getText();
empNameList.add(empName);
}
driver.findElement(By.xpath("//a[@id='example_next']")).click();
}
if(totalPages>0)
driver.findElement(By.xpath("//div[@id='example_paginate']/span/a[1]")).click();
return empNameList;
}
@Test
void testCase4() {
driver.findElement(By.xpath("//table[@class='display nowrap dataTable']/thead/tr/th[1]")).click();
ArrayList<String> actualEmpNameList = getEmpNameList();
System.out.println("STEP- Actual sorted list of employee names- " + actualEmpNameList);
ArrayList<String> expectedEmpNameList = getEmpNameList();
Collections.sort(expectedEmpNameList, Collections.reverseOrder());
System.out.println("STEP- Expected sorted list of employee names- " + expectedEmpNameList);
Assert.assertEquals(actualEmpNameList, expectedEmpNameList);
}
@AfterClass
void closeBrowser() {
driver.close();
}
} | 2,020 | 0.735644 | 0.726238 | 55 | 35.745453 | 32.940285 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.854545 | false | false | 9 |
5944dd01af469196a886ee8dcedacb70114d6b19 | 6,803,228,203,343 | ed43b5276330c7ec2554ce47fa00c01e7deee6e9 | /src/main/java/org/esupportail/nfctag/service/api/impl/TagIdCheckSql.java | 6da8706fafcca5916533ef4a912bdf6c62d3e919 | [
"LGPL-2.0-or-later",
"CC-BY-4.0",
"W3C",
"EPL-1.0",
"CC-BY-SA-3.0",
"Classpath-exception-2.0",
"MPL-1.1",
"CDDL-1.0",
"CPL-1.0",
"LGPL-2.1-only",
"BSD-3-Clause",
"MIT",
"SAX-PD",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | EsupPortail/esup-nfc-tag-server | https://github.com/EsupPortail/esup-nfc-tag-server | 99fb10a0ecc3ddc24a74d94b16eb24a0c760b3b7 | 41004309914f5418339f2a642e3044a2df61e0c5 | refs/heads/master | 2023-04-27T07:09:40.827000 | 2022-05-06T12:46:52 | 2022-05-06T12:46:52 | 63,779,649 | 11 | 15 | Apache-2.0 | false | 2023-04-17T17:39:56 | 2016-07-20T12:30:01 | 2022-06-27T13:47:04 | 2023-04-17T17:39:52 | 15,971 | 11 | 13 | 7 | Java | false | false | /**
* Licensed to ESUP-Portail under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* ESUP-Portail licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.esupportail.nfctag.service.api.impl;
import org.esupportail.nfctag.domain.TagLog;
import org.esupportail.nfctag.service.api.TagIdCheckApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class TagIdCheckSql implements TagIdCheckApi {
private final Logger log = LoggerFactory.getLogger(getClass());
protected JdbcTemplate jdbcTemplate;
protected String csnAuthSql;
protected String desfireAuthSql;
protected String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDataSource(DataSource datesource) {
this.jdbcTemplate = new JdbcTemplate(datesource);
}
public void setCsnAuthSql(String csnAuthSql) {
this.csnAuthSql = csnAuthSql;
}
public void setDesfireAuthSql(String desfireAuthSql) {
this.desfireAuthSql = desfireAuthSql;
}
@Override
public TagLog getTagLogFromTagId(TagType tagType, String tagId, String appName){
String authSql = "";
switch (tagType) {
case CSN :
authSql = csnAuthSql;
break;
case DESFIRE :
authSql = desfireAuthSql;
break;
default:
throw new RuntimeException(tagType + " is not supported");
}
TagLog tagLog = null;
try {
tagLog = (TagLog) jdbcTemplate.queryForObject(authSql, new TagLogRowMapper(), tagId);
log.info("tagId " + tagId + " identifié !");
} catch (EmptyResultDataAccessException ex) {
log.info("Pas de résultat pour le tagId : " + tagId);
}
return tagLog;
}
}
| UTF-8 | Java | 2,477 | java | TagIdCheckSql.java | Java | [] | null | [] | /**
* Licensed to ESUP-Portail under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* ESUP-Portail licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.esupportail.nfctag.service.api.impl;
import org.esupportail.nfctag.domain.TagLog;
import org.esupportail.nfctag.service.api.TagIdCheckApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class TagIdCheckSql implements TagIdCheckApi {
private final Logger log = LoggerFactory.getLogger(getClass());
protected JdbcTemplate jdbcTemplate;
protected String csnAuthSql;
protected String desfireAuthSql;
protected String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDataSource(DataSource datesource) {
this.jdbcTemplate = new JdbcTemplate(datesource);
}
public void setCsnAuthSql(String csnAuthSql) {
this.csnAuthSql = csnAuthSql;
}
public void setDesfireAuthSql(String desfireAuthSql) {
this.desfireAuthSql = desfireAuthSql;
}
@Override
public TagLog getTagLogFromTagId(TagType tagType, String tagId, String appName){
String authSql = "";
switch (tagType) {
case CSN :
authSql = csnAuthSql;
break;
case DESFIRE :
authSql = desfireAuthSql;
break;
default:
throw new RuntimeException(tagType + " is not supported");
}
TagLog tagLog = null;
try {
tagLog = (TagLog) jdbcTemplate.queryForObject(authSql, new TagLogRowMapper(), tagId);
log.info("tagId " + tagId + " identifié !");
} catch (EmptyResultDataAccessException ex) {
log.info("Pas de résultat pour le tagId : " + tagId);
}
return tagLog;
}
}
| 2,477 | 0.750707 | 0.748283 | 87 | 27.448277 | 25.898457 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.505747 | false | false | 9 |
6d4df8ef5b18f20c8735ee6f135b19323d9598ce | 18,494,129,183,340 | 1967d57598af37844cf5925b86f2be5bdf767fe8 | /project-mugo/src/main/java/com/saike/ebiz/delivery/dao/impl/DealerDAOImpl.java | 3e41a61becd32cc3bbf86e99accbc189696d7ab3 | [] | no_license | liubao19860416/project-mugo | https://github.com/liubao19860416/project-mugo | dea178dff4590d43b8a0705d89966a59d86d01c0 | 5f8c450d27561c3f7a8b9567a59f60bda53a8566 | refs/heads/master | 2018-03-21T17:17:18.978000 | 2016-10-27T15:14:38 | 2016-10-27T15:14:38 | 44,898,554 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.saike.ebiz.delivery.dao.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import com.saike.ebiz.delivery.dao.DealerDAO;
import com.saike.ebiz.delivery.dao.entity.Dealer;
import com.saike.ebiz.mugo.dao.base.GenericDAOBatisImpl;
import com.saike.ebiz.mugo.utils.DatetimeUtils;
/**
* 经销商DAO实现类
*
* @author zeng wei
* @version 2.0
*
* @see {@link com.saike.grape.dao20.api.dealer.DealerDAO}
*
*/
@Repository
public class DealerDAOImpl extends GenericDAOBatisImpl<Dealer, DealerDAOImpl>
implements DealerDAO {
public boolean insertDealerVehicles( String dealerCode,
List<String> vehicleCodes ) {
if( vehicleCodes != null && vehicleCodes.size() > 0 ) {
Map<String, Object> params = new HashMap<>();
params.put( "currentDatetime", DatetimeUtils.currentTimestamp() );
params.put( "dealerCode", dealerCode );
params.put( "vehicleCodes", vehicleCodes );
return super.insert( "insertDealerVehicles", params ) > 0;
}
return true;
}
@Override
public int getDealerListCount(String dealerCode, String dealerName) {
Map<String, Object> params = new HashMap<>();
params.put("dealerCode", dealerCode);
params.put("dealerName", dealerName);
long selectCount = super.selectCount("getDealerListCount", params);
return Integer.parseInt(selectCount+"");
}
@Override
public List<Map> getDealerList(String dealerCode, String dealerName,
int pageIndex, int pageSize ) {
Map<String, Object> params = new HashMap<>();
params.put("dealerCode", dealerCode);
params.put("dealerName", dealerName);
return super.selectMapList("getDealerListPage", params, pageIndex, pageSize);
}
@Override
public List<Dealer> getDealersByArea( String cityCode, String areaCode,
String vehicleCode,
List<String> dealerCodesInclude ) {
if( StringUtils.isEmpty( vehicleCode )
|| ( dealerCodesInclude != null && dealerCodesInclude.isEmpty() ) ) {
return new ArrayList<>();
}
return selectList( "selectDealersByArea",
newParams().put( "cityCode", cityCode )
.put( "areaCode", areaCode )
.put( "vehicleCode", vehicleCode )
.put( "dealerCodesInclude", dealerCodesInclude ) );
}
@Override
public List<Dealer> getDealersVisitedByUser( String userCode ) {
if( StringUtils.isEmpty( userCode ) ) {
return new ArrayList<>();
}
return selectList( "getDealersVisitedByUser",
newParams().put( "userCode", userCode ) );
}
@Override
public boolean setServiceTime(String dealerCode, String businessStartTime,
String businessEndTime) {
Map<String,String> param = new HashMap<>();
param.put("dealerCode", dealerCode);
param.put("businessStartTime", businessStartTime);
param.put("businessEndTime", businessEndTime);
int i = this.update("setServiceTime", param);
return i==1;
}
@Override
public boolean setBasicDiscount(String dealerCode, String basicDiscount) {
Map<String,String> param = new HashMap<>();
param.put("dealerCode", dealerCode);
param.put("basicDiscount", basicDiscount);
int i = this.update("setBasicDiscount", param);
return i==1;
}
/**
* 根据车型,城市编码,区域编码来查询没有工位数的经销商Id
*
* @param vehicleCode
* 车型编码
* @param cityCode
* 城市编码
* @param areaCode
* 区域列表
* @return
*/
public List<String> getDealerCodesAvailable(String vehicleCode,
String cityCode, String areaCode) {
List<String> result = new ArrayList<>();
Map<String, String> param = new HashMap<>();
param.put("vehicleCode", vehicleCode);
param.put("cityCode", cityCode);
param.put("areaCode", areaCode);
List<Map> list = this.selectMapList("getDealerCodesWithoutWorkstation",
param);
for (Map map : list) {
for (Object key : map.keySet()) {
String value = String.valueOf(map.get(key));
result.add(value);
}
}
return result;
}
/**
* 经销商数据增删查改
* add wangtao
* @return
*/
@Override
public List<Map> getAllDealerList(){
return selectMapList( "getAllDealerList", null );
}
@Override
public List<Dealer> getPageByDealerName(String dealerName, int pageIndex, int pageSize){
return selectList( "getPageByDealerName", dealerName, pageIndex, pageSize );
}
@Override
public Dealer getDealerByCode(String dealerCode){
return selectOne( "getDealerByCode", dealerCode );
}
@Override
public boolean updateDealerByCode(Dealer dealer){
int result = update( "updateDealerByCode", dealer );
return result==1;
}
@Override
public List<Map> getAreaCodeByDealerCode( List<String> dealerCodesInclude ) {
return selectMapList( "getAreaCodeByDealerCode",
newParams().put( "dealerCodesInclude", dealerCodesInclude ) );
}
@Override
public List<Dealer> getCxbDealerByCityCode(String cityCode){
return selectList( "getCxbDealerByCityCode", cityCode );
}
}
| UTF-8 | Java | 6,082 | java | DealerDAOImpl.java | Java | [
{
"context": "timeUtils;\r\n\r\n\r\n/**\r\n * 经销商DAO实现类\r\n * \r\n * @author zeng wei\r\n * @version 2.0\r\n * \r\n * @see {@link com.saike.g",
"end": 502,
"score": 0.9995985627174377,
"start": 494,
"tag": "NAME",
"value": "zeng wei"
},
{
"context": "t;\r\n }\r\n\r\n /**\r\n ... | null | [] | package com.saike.ebiz.delivery.dao.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import com.saike.ebiz.delivery.dao.DealerDAO;
import com.saike.ebiz.delivery.dao.entity.Dealer;
import com.saike.ebiz.mugo.dao.base.GenericDAOBatisImpl;
import com.saike.ebiz.mugo.utils.DatetimeUtils;
/**
* 经销商DAO实现类
*
* @author <NAME>
* @version 2.0
*
* @see {@link com.saike.grape.dao20.api.dealer.DealerDAO}
*
*/
@Repository
public class DealerDAOImpl extends GenericDAOBatisImpl<Dealer, DealerDAOImpl>
implements DealerDAO {
public boolean insertDealerVehicles( String dealerCode,
List<String> vehicleCodes ) {
if( vehicleCodes != null && vehicleCodes.size() > 0 ) {
Map<String, Object> params = new HashMap<>();
params.put( "currentDatetime", DatetimeUtils.currentTimestamp() );
params.put( "dealerCode", dealerCode );
params.put( "vehicleCodes", vehicleCodes );
return super.insert( "insertDealerVehicles", params ) > 0;
}
return true;
}
@Override
public int getDealerListCount(String dealerCode, String dealerName) {
Map<String, Object> params = new HashMap<>();
params.put("dealerCode", dealerCode);
params.put("dealerName", dealerName);
long selectCount = super.selectCount("getDealerListCount", params);
return Integer.parseInt(selectCount+"");
}
@Override
public List<Map> getDealerList(String dealerCode, String dealerName,
int pageIndex, int pageSize ) {
Map<String, Object> params = new HashMap<>();
params.put("dealerCode", dealerCode);
params.put("dealerName", dealerName);
return super.selectMapList("getDealerListPage", params, pageIndex, pageSize);
}
@Override
public List<Dealer> getDealersByArea( String cityCode, String areaCode,
String vehicleCode,
List<String> dealerCodesInclude ) {
if( StringUtils.isEmpty( vehicleCode )
|| ( dealerCodesInclude != null && dealerCodesInclude.isEmpty() ) ) {
return new ArrayList<>();
}
return selectList( "selectDealersByArea",
newParams().put( "cityCode", cityCode )
.put( "areaCode", areaCode )
.put( "vehicleCode", vehicleCode )
.put( "dealerCodesInclude", dealerCodesInclude ) );
}
@Override
public List<Dealer> getDealersVisitedByUser( String userCode ) {
if( StringUtils.isEmpty( userCode ) ) {
return new ArrayList<>();
}
return selectList( "getDealersVisitedByUser",
newParams().put( "userCode", userCode ) );
}
@Override
public boolean setServiceTime(String dealerCode, String businessStartTime,
String businessEndTime) {
Map<String,String> param = new HashMap<>();
param.put("dealerCode", dealerCode);
param.put("businessStartTime", businessStartTime);
param.put("businessEndTime", businessEndTime);
int i = this.update("setServiceTime", param);
return i==1;
}
@Override
public boolean setBasicDiscount(String dealerCode, String basicDiscount) {
Map<String,String> param = new HashMap<>();
param.put("dealerCode", dealerCode);
param.put("basicDiscount", basicDiscount);
int i = this.update("setBasicDiscount", param);
return i==1;
}
/**
* 根据车型,城市编码,区域编码来查询没有工位数的经销商Id
*
* @param vehicleCode
* 车型编码
* @param cityCode
* 城市编码
* @param areaCode
* 区域列表
* @return
*/
public List<String> getDealerCodesAvailable(String vehicleCode,
String cityCode, String areaCode) {
List<String> result = new ArrayList<>();
Map<String, String> param = new HashMap<>();
param.put("vehicleCode", vehicleCode);
param.put("cityCode", cityCode);
param.put("areaCode", areaCode);
List<Map> list = this.selectMapList("getDealerCodesWithoutWorkstation",
param);
for (Map map : list) {
for (Object key : map.keySet()) {
String value = String.valueOf(map.get(key));
result.add(value);
}
}
return result;
}
/**
* 经销商数据增删查改
* add wangtao
* @return
*/
@Override
public List<Map> getAllDealerList(){
return selectMapList( "getAllDealerList", null );
}
@Override
public List<Dealer> getPageByDealerName(String dealerName, int pageIndex, int pageSize){
return selectList( "getPageByDealerName", dealerName, pageIndex, pageSize );
}
@Override
public Dealer getDealerByCode(String dealerCode){
return selectOne( "getDealerByCode", dealerCode );
}
@Override
public boolean updateDealerByCode(Dealer dealer){
int result = update( "updateDealerByCode", dealer );
return result==1;
}
@Override
public List<Map> getAreaCodeByDealerCode( List<String> dealerCodesInclude ) {
return selectMapList( "getAreaCodeByDealerCode",
newParams().put( "dealerCodesInclude", dealerCodesInclude ) );
}
@Override
public List<Dealer> getCxbDealerByCityCode(String cityCode){
return selectList( "getCxbDealerByCityCode", cityCode );
}
}
| 6,080 | 0.586513 | 0.585007 | 179 | 31.385475 | 26.100193 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.670391 | false | false | 9 |
2ebe8b09cb9a00ea8c416ea18f78a571966f0761 | 29,712,583,759,201 | fdcfaf6992b391082263f4e7ea3663eb623deba2 | /src/patternrecognition2020/pkg1/MemoriasMain.java | 61013881c94edc225054b500e73ac0e5cb38238d | [] | no_license | zamudio1243/ReconocimientoPatrones | https://github.com/zamudio1243/ReconocimientoPatrones | 817db38b9d22b3bd21676c1d01b20902a06c114f | c164adf08ef95b0741314d26713157da2d41013c | refs/heads/master | 2021-12-02T00:10:44.267000 | 2021-11-30T19:58:39 | 2021-11-30T19:58:39 | 217,984,619 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package patternrecognition2020.pkg1;
/*
Hector noviembre 2019
*/
import herramientasclasificadores.Patron;
import memorias.CAP;
import memorias.Lernmatrix;
import java.util.ArrayList;
public class MemoriasMain {
public static void lernmatrix(){
int[][] x = new int[5][6];
int[][] y = new int[3][3];
x[0]= new int[]{1,0,1,0,1,0};
x[1]= new int[]{1,1,0,0,1,1};
x[2]= new int[]{1,0,1,1,0,2};
x[3]= new int[]{0,1,0,1,1,0};
x[4]= new int[]{0,0,1,0,1,2};
y[0]= new int[]{1,0,0};
y[1]= new int[]{0,1,0};
y[2]= new int[]{0,0,1};
Lernmatrix lm = new Lernmatrix(x,y,1);
lm.aprendizaje();
lm.mostrarM();
System.out.println("Efectividad: "+lm.recuperacion(x));
}
public static void cap(){
ArrayList<Patron> conjFundamental = new ArrayList<>();
/*
// Prueba 1
conjFundamental.add(new Patron(new double[]{2.1,3.8},"uno"));
conjFundamental.add(new Patron(new double[]{6.3,3.8},"dos"));
*/
// Prueba 2
conjFundamental.add(new Patron(new double[]{2.0,3.0,6.0},"uno"));
conjFundamental.add(new Patron(new double[]{6.0,8.0,10.0},"dos"));
conjFundamental.add(new Patron(new double[]{1.9,3.8,5.5},"uno"));
conjFundamental.add(new Patron(new double[]{6.4,7.2,9.7},"dos"));
CAP cap = new CAP(conjFundamental);
cap.aprendizaje();
cap.mostrarMemoria();
System.out.println();
cap.recuperacion(conjFundamental);
}
public static void main(String[] args) {
MemoriasMain.cap();
}
}
| UTF-8 | Java | 1,623 | java | MemoriasMain.java | Java | [
{
"context": "package patternrecognition2020.pkg1;\n/*\nHector noviembre 2019 \n*/\n\nimport herramientasclasificadores.Patro",
"end": 56,
"score": 0.997194766998291,
"start": 40,
"tag": "NAME",
"value": "Hector noviembre"
}
] | null | [] | package patternrecognition2020.pkg1;
/*
<NAME> 2019
*/
import herramientasclasificadores.Patron;
import memorias.CAP;
import memorias.Lernmatrix;
import java.util.ArrayList;
public class MemoriasMain {
public static void lernmatrix(){
int[][] x = new int[5][6];
int[][] y = new int[3][3];
x[0]= new int[]{1,0,1,0,1,0};
x[1]= new int[]{1,1,0,0,1,1};
x[2]= new int[]{1,0,1,1,0,2};
x[3]= new int[]{0,1,0,1,1,0};
x[4]= new int[]{0,0,1,0,1,2};
y[0]= new int[]{1,0,0};
y[1]= new int[]{0,1,0};
y[2]= new int[]{0,0,1};
Lernmatrix lm = new Lernmatrix(x,y,1);
lm.aprendizaje();
lm.mostrarM();
System.out.println("Efectividad: "+lm.recuperacion(x));
}
public static void cap(){
ArrayList<Patron> conjFundamental = new ArrayList<>();
/*
// Prueba 1
conjFundamental.add(new Patron(new double[]{2.1,3.8},"uno"));
conjFundamental.add(new Patron(new double[]{6.3,3.8},"dos"));
*/
// Prueba 2
conjFundamental.add(new Patron(new double[]{2.0,3.0,6.0},"uno"));
conjFundamental.add(new Patron(new double[]{6.0,8.0,10.0},"dos"));
conjFundamental.add(new Patron(new double[]{1.9,3.8,5.5},"uno"));
conjFundamental.add(new Patron(new double[]{6.4,7.2,9.7},"dos"));
CAP cap = new CAP(conjFundamental);
cap.aprendizaje();
cap.mostrarMemoria();
System.out.println();
cap.recuperacion(conjFundamental);
}
public static void main(String[] args) {
MemoriasMain.cap();
}
}
| 1,613 | 0.563155 | 0.504005 | 61 | 25.606558 | 22.785009 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.327869 | false | false | 9 |
0a65a0df931b2fb446157ce9f7f1bec37bbec483 | 11,218,454,586,812 | 1687523f51857d4f79883761519fe64c966fe23f | /Presentation/org.egovframe.rte.ptl.mvc/src/main/java/org/egovframe/rte/ptl/mvc/bind/CommandMapArgumentResolver.java | 1cc3c91cf4feadf1b0acc6ec7beb08960bb32641 | [
"Apache-2.0"
] | permissive | eGovFramework/egovframe-runtime | https://github.com/eGovFramework/egovframe-runtime | 46c3910a060f0dccd79c71f2fcc977998a9f6c84 | 3d012cdd0227e686c8cdcecf998d383f14b966e2 | refs/heads/contribution | 2023-07-06T07:54:26.496000 | 2023-06-29T06:41:08 | 2023-06-29T06:41:08 | 240,443,569 | 31 | 62 | Apache-2.0 | false | 2023-09-11T05:31:43 | 2020-02-14T06:32:50 | 2023-08-22T09:00:40 | 2023-09-11T05:31:42 | 7,983 | 32 | 48 | 10 | Java | false | false | /*
* Copyright 2008-2014 MOSPA(Ministry of Security and Public Administration).
*
* 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.egovframe.rte.ptl.mvc.bind;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* CommandMapArgumentResolver.java
* <p/><b>NOTE:</b> <pre> Controller에서 화면(JSP) 입력값을 받기 위해서 일반적으로 Command(Form Class) 객체를 사용하지만, Map 객체를 사용하는걸 선호할 수 있다.
* Sping MVC는 Controller의 argument를 분석하여 argument값을 customizing 할 수 있는 WebArgumentResolver라는 interface를 제공한다.
* CommandMapArgumentResolver는 WebArgumentResolver의 구현 클래스이다.
* CommandMapArgumentResolver는 Controller 메소드의 argument중에 commandMap이라는 Map 객체가 있다면
* HTTP request 객체에 있는 파라미터이름과 값을 commandMap에 담는다.
* </pre>
* @author 실행환경 개발팀 함철
* @since 2009.06.01
* @version 1.0
* <pre>
* 개정이력(Modification Information)
*
* 수정일 수정자 수정내용
* ----------------------------------------------
* 2009.05.30 함철 최초 생성
* 2014.04.23 이영지 deprecated
* </pre>
* @deprecated This class has been deprecated.
*/
@Deprecated
public class CommandMapArgumentResolver implements WebArgumentResolver {
/**
* Controller의 메소드 argument에 commandMap이라는 Map 객체가 있다면
* HTTP request 객체에 있는 파라미터이름과 값을 commandMap에 담아 returng한다.
* 배열인 파라미터 값은 배열로 Map에 저장한다.
*
* @param methodParameter - 메소드 파라미터의 타입,인덱스등의 정보
* @param webRequest - web request 객체
* @return argument에 commandMap(java.util.Map)이 있으면 commandMap, 없으면<code>UNRESOLVED</code>.
* @exception Exception
*/
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
Class<?> clazz = methodParameter.getParameterType();
String paramName = methodParameter.getParameterName();
if (clazz.equals(Map.class) && paramName.equals("commandMap")) {
Map<String, Object> commandMap = new HashMap<String, Object>();
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
Enumeration<?> enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String[] values = request.getParameterValues(key);
if (values != null) {
commandMap.put(key, (values.length > 1) ? values : values[0]);
}
}
return commandMap;
}
return UNRESOLVED;
}
}
| UTF-8 | Java | 3,457 | java | CommandMapArgumentResolver.java | Java | [
{
"context": " 값을 commandMap에 담는다.\n * </pre>\n * @author 실행환경 개발팀 함철\n * @since 2009.06.01\n * @version 1.0\n * <pre>\n * ",
"end": 1489,
"score": 0.9789183139801025,
"start": 1487,
"tag": "NAME",
"value": "함철"
}
] | null | [] | /*
* Copyright 2008-2014 MOSPA(Ministry of Security and Public Administration).
*
* 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.egovframe.rte.ptl.mvc.bind;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* CommandMapArgumentResolver.java
* <p/><b>NOTE:</b> <pre> Controller에서 화면(JSP) 입력값을 받기 위해서 일반적으로 Command(Form Class) 객체를 사용하지만, Map 객체를 사용하는걸 선호할 수 있다.
* Sping MVC는 Controller의 argument를 분석하여 argument값을 customizing 할 수 있는 WebArgumentResolver라는 interface를 제공한다.
* CommandMapArgumentResolver는 WebArgumentResolver의 구현 클래스이다.
* CommandMapArgumentResolver는 Controller 메소드의 argument중에 commandMap이라는 Map 객체가 있다면
* HTTP request 객체에 있는 파라미터이름과 값을 commandMap에 담는다.
* </pre>
* @author 실행환경 개발팀 함철
* @since 2009.06.01
* @version 1.0
* <pre>
* 개정이력(Modification Information)
*
* 수정일 수정자 수정내용
* ----------------------------------------------
* 2009.05.30 함철 최초 생성
* 2014.04.23 이영지 deprecated
* </pre>
* @deprecated This class has been deprecated.
*/
@Deprecated
public class CommandMapArgumentResolver implements WebArgumentResolver {
/**
* Controller의 메소드 argument에 commandMap이라는 Map 객체가 있다면
* HTTP request 객체에 있는 파라미터이름과 값을 commandMap에 담아 returng한다.
* 배열인 파라미터 값은 배열로 Map에 저장한다.
*
* @param methodParameter - 메소드 파라미터의 타입,인덱스등의 정보
* @param webRequest - web request 객체
* @return argument에 commandMap(java.util.Map)이 있으면 commandMap, 없으면<code>UNRESOLVED</code>.
* @exception Exception
*/
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
Class<?> clazz = methodParameter.getParameterType();
String paramName = methodParameter.getParameterName();
if (clazz.equals(Map.class) && paramName.equals("commandMap")) {
Map<String, Object> commandMap = new HashMap<String, Object>();
HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
Enumeration<?> enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String[] values = request.getParameterValues(key);
if (values != null) {
commandMap.put(key, (values.length > 1) ? values : values[0]);
}
}
return commandMap;
}
return UNRESOLVED;
}
}
| 3,457 | 0.733267 | 0.720079 | 81 | 36.444443 | 30.393713 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.320988 | false | false | 9 |
e52be288d133055f7bef50c6e5b5b0945bee327f | 14,525,579,408,832 | e3db9f4570e05bf93af029ce325e6db0cce172bb | /sigma-dal/src/main/java/com/tqmall/sigma/dao/PayOrderInfoMapper.java | d7f553c1ce5a528a95b9d415badf16c495a533d9 | [] | no_license | xie-summer/sigma | https://github.com/xie-summer/sigma | 974a5e69bb722eb4fa51ce2a8540826dcebb4b43 | 4a4e409d7ed9388ff90f48454937e48213d23579 | refs/heads/master | 2021-06-16T12:46:01.962000 | 2017-05-18T07:43:47 | 2017-05-18T07:43:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tqmall.sigma.dao;
import com.tqmall.sigma.entity.PayOrderInfoDO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*
* PayOrderInfoMapper数据库操作接口类
*
**/
public interface PayOrderInfoMapper{
/**
*
* 删除(根据主键ID删除)
*
**/
Integer deleteByPrimaryKey ( @Param("id") Integer id );
/**
*
* 添加 (匹配有值的字段)
*
**/
Integer insertSelective( PayOrderInfoDO record );
/**
*
* 查询(根据主键ID查询)
*
**/
PayOrderInfoDO selectByPrimaryKey ( @Param("id") Integer id );
/**
*
* 修改 (匹配有值的字段)
*
**/
Integer updateByPrimaryKeySelective( PayOrderInfoDO record );
/**
*
* 批量添加
*
**/
Integer batchInsert ( @Param("payOrderInfoDOList") List<PayOrderInfoDO> payOrderInfoDOList );
/**
*
* 动态条件查询总数目
*
**/
Integer countByBaseCondition ( Map<String,Object> map );
/**
*
* 动态条件查询(支持分页)
*
**/
List<PayOrderInfoDO> selectByBaseConditionPageable ( Map<String,Object> map );
/**
*
* 批量更新
*
**/
Integer batchUpdateById ( @Param("payOrderInfoDOList") List<PayOrderInfoDO> payOrderInfoDOList );
} | UTF-8 | Java | 1,275 | java | PayOrderInfoMapper.java | Java | [] | null | [] | package com.tqmall.sigma.dao;
import com.tqmall.sigma.entity.PayOrderInfoDO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*
* PayOrderInfoMapper数据库操作接口类
*
**/
public interface PayOrderInfoMapper{
/**
*
* 删除(根据主键ID删除)
*
**/
Integer deleteByPrimaryKey ( @Param("id") Integer id );
/**
*
* 添加 (匹配有值的字段)
*
**/
Integer insertSelective( PayOrderInfoDO record );
/**
*
* 查询(根据主键ID查询)
*
**/
PayOrderInfoDO selectByPrimaryKey ( @Param("id") Integer id );
/**
*
* 修改 (匹配有值的字段)
*
**/
Integer updateByPrimaryKeySelective( PayOrderInfoDO record );
/**
*
* 批量添加
*
**/
Integer batchInsert ( @Param("payOrderInfoDOList") List<PayOrderInfoDO> payOrderInfoDOList );
/**
*
* 动态条件查询总数目
*
**/
Integer countByBaseCondition ( Map<String,Object> map );
/**
*
* 动态条件查询(支持分页)
*
**/
List<PayOrderInfoDO> selectByBaseConditionPageable ( Map<String,Object> map );
/**
*
* 批量更新
*
**/
Integer batchUpdateById ( @Param("payOrderInfoDOList") List<PayOrderInfoDO> payOrderInfoDOList );
} | 1,275 | 0.638317 | 0.638317 | 73 | 14.315068 | 22.397331 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.863014 | false | false | 9 |
beb4eeb16a092fc23323badb98b175a614725384 | 16,690,242,925,379 | d851f4f34a87afa3d19133245136b7a08e9b1d88 | /app/src/main/java/com/chip/parkpro1/BeaconActivityService.java | 3e7fb0f91c052ee8fc47d8d88da53bd2f40c28ed | [] | no_license | emilioea1/yaahla_chip5 | https://github.com/emilioea1/yaahla_chip5 | 05b66c3e7069689a5093eaff844ff66b96cf09dc | 3ea546f918677e93198ced393b25ef6b9074beca | refs/heads/master | 2022-11-12T14:51:40.386000 | 2020-07-09T18:00:31 | 2020-07-09T18:00:31 | 278,435,365 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chip.parkpro1;
import android.content.Intent;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import mobi.inthepocket.android.beacons.ibeaconscanner.Beacon;
import mobi.inthepocket.android.beacons.ibeaconscanner.BluetoothScanBroadcastReceiver;
public class BeaconActivityService extends JobIntentService {
@Override
protected void onHandleWork(@NonNull Intent intent) {
// This is the beacon object containing UUID, major and minor info
final Beacon beacon = intent.getParcelableExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_DETECTION);
// This flag will be true if it is an enter event that triggered this service
final boolean enteredBeacon = intent.getBooleanExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_ENTERED, false);
// This flag will be true if it is an exit event that triggered this service
final boolean exitedBeacon = intent.getBooleanExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_EXITED, false);
//do shit when the beacon triggers
if (enteredBeacon)
Toast.makeText(this, "ENTRY", Toast.LENGTH_SHORT).show();
if (exitedBeacon)
Toast.makeText(this, "EXIT", Toast.LENGTH_SHORT).show();
}
} | UTF-8 | Java | 1,321 | java | BeaconActivityService.java | Java | [] | null | [] | package com.chip.parkpro1;
import android.content.Intent;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import mobi.inthepocket.android.beacons.ibeaconscanner.Beacon;
import mobi.inthepocket.android.beacons.ibeaconscanner.BluetoothScanBroadcastReceiver;
public class BeaconActivityService extends JobIntentService {
@Override
protected void onHandleWork(@NonNull Intent intent) {
// This is the beacon object containing UUID, major and minor info
final Beacon beacon = intent.getParcelableExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_DETECTION);
// This flag will be true if it is an enter event that triggered this service
final boolean enteredBeacon = intent.getBooleanExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_ENTERED, false);
// This flag will be true if it is an exit event that triggered this service
final boolean exitedBeacon = intent.getBooleanExtra(BluetoothScanBroadcastReceiver.IBEACON_SCAN_BEACON_EXITED, false);
//do shit when the beacon triggers
if (enteredBeacon)
Toast.makeText(this, "ENTRY", Toast.LENGTH_SHORT).show();
if (exitedBeacon)
Toast.makeText(this, "EXIT", Toast.LENGTH_SHORT).show();
}
} | 1,321 | 0.753974 | 0.753217 | 31 | 41.645161 | 39.505451 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 9 |
a7862152cf500a5beb4833d44401205404658014 | 17,609,365,926,187 | f88fe997e6ac2959ec8174c03018450544cbf125 | /IM/src/de/vbl/im/model/InKomponente.java | 3a870a7bcf13849e59aa67b129bb92724580ea14 | [] | no_license | Zschumme/IM | https://github.com/Zschumme/IM | 58c6cc4a2ee1ee64c3bea622897a341ea5f2cdd9 | 7383f096fe32f3372a26819bd53193ae055b65e3 | refs/heads/master | 2020-01-18T19:36:21.549000 | 2014-12-29T21:08:56 | 2014-12-29T21:08:56 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package de.vbl.im.model;
import static javax.persistence.GenerationType.IDENTITY;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import de.vbl.im.model.Ansprechpartner;
import java.util.Collection;
import javax.persistence.ManyToMany;
@Entity
public class InKomponente {
private long id;
private StringProperty name;
private String beschreibung;
private InSystem inSystem;
private Collection<Ansprechpartner> ansprechpartner;
private StringProperty fullname; // transient
public InKomponente() {
name = new SimpleStringProperty();
fullname = new SimpleStringProperty();
}
public InKomponente(String name, InSystem system) {
this();
setName(name);
setInSystem(system);
if (system.getInKomponente() != null)
system.getInKomponente().add(this);
}
// ------------------------------------------------------------------------
@Id
@GeneratedValue(strategy = IDENTITY)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
// ------------------------------------------------------------------------
public StringProperty nameProperty() {
return name;
}
public String getName() {
return name.getValueSafe();
}
public void setName(String param) {
name.set(param);
}
// ------------------------------------------------------------------------
public String getBeschreibung() {
return beschreibung;
}
public void setBeschreibung(String param) {
beschreibung = param;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --
@ManyToOne
public InSystem getInSystem() {
return inSystem;
}
public void setInSystem(InSystem param) {
if (inSystem != null) {
fullname.unbind();
}
this.inSystem = param;
fullname.bind(Bindings.concat(inSystem.fullnameProperty(), trennung(),name));
}
private String trennung() {
return " – "; // halbgeviertstrich Alt+0150
// return " — ";
}
// private String ASCIItoStr(int a) {
// byte[] b = { (byte) a };
// String ret = new String(b);
// return " " + ret + " ";
// }
// * * * * * * * * * * * * * * * * * * *
public StringProperty fullnameProperty() {
return fullname;
}
public String getFullname() {
return fullname.get();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --
@ManyToMany
public Collection<Ansprechpartner> getAnsprechpartner() {
return ansprechpartner;
}
public void setAnsprechpartner(Collection<Ansprechpartner> param) {
this.ansprechpartner = param;
}
}
| WINDOWS-1252 | Java | 2,884 | java | InKomponente.java | Java | [] | null | [] |
package de.vbl.im.model;
import static javax.persistence.GenerationType.IDENTITY;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import de.vbl.im.model.Ansprechpartner;
import java.util.Collection;
import javax.persistence.ManyToMany;
@Entity
public class InKomponente {
private long id;
private StringProperty name;
private String beschreibung;
private InSystem inSystem;
private Collection<Ansprechpartner> ansprechpartner;
private StringProperty fullname; // transient
public InKomponente() {
name = new SimpleStringProperty();
fullname = new SimpleStringProperty();
}
public InKomponente(String name, InSystem system) {
this();
setName(name);
setInSystem(system);
if (system.getInKomponente() != null)
system.getInKomponente().add(this);
}
// ------------------------------------------------------------------------
@Id
@GeneratedValue(strategy = IDENTITY)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
// ------------------------------------------------------------------------
public StringProperty nameProperty() {
return name;
}
public String getName() {
return name.getValueSafe();
}
public void setName(String param) {
name.set(param);
}
// ------------------------------------------------------------------------
public String getBeschreibung() {
return beschreibung;
}
public void setBeschreibung(String param) {
beschreibung = param;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --
@ManyToOne
public InSystem getInSystem() {
return inSystem;
}
public void setInSystem(InSystem param) {
if (inSystem != null) {
fullname.unbind();
}
this.inSystem = param;
fullname.bind(Bindings.concat(inSystem.fullnameProperty(), trennung(),name));
}
private String trennung() {
return " – "; // halbgeviertstrich Alt+0150
// return " — ";
}
// private String ASCIItoStr(int a) {
// byte[] b = { (byte) a };
// String ret = new String(b);
// return " " + ret + " ";
// }
// * * * * * * * * * * * * * * * * * * *
public StringProperty fullnameProperty() {
return fullname;
}
public String getFullname() {
return fullname.get();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --
@ManyToMany
public Collection<Ansprechpartner> getAnsprechpartner() {
return ansprechpartner;
}
public void setAnsprechpartner(Collection<Ansprechpartner> param) {
this.ansprechpartner = param;
}
}
| 2,884 | 0.578472 | 0.577083 | 116 | 22.810345 | 21.73822 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.353448 | false | false | 9 |
838d3173c005f7d18af3a8512f5ef352390166c9 | 9,534,827,408,936 | 0af7c9bd75772bba20e3916e9aa3fb92b1163402 | /src/dao/TipoOcorrenciaPolicialDAO.java | 0a02e5e81de5fd6c73e045540a59094ba9e9fa80 | [] | no_license | renanroeder99/TCCWeb | https://github.com/renanroeder99/TCCWeb | d4d8f8cbe91d4776a7e4b4a354d78a17eac3d2e5 | b853479f9818fc1929c7f42c0358a75224fbb5c0 | refs/heads/master | 2021-01-23T21:21:39.964000 | 2017-10-02T19:06:44 | 2017-10-02T19:06:44 | 102,893,658 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package dao;
import database.Conexao;
import model.BaseOcorrencia;
import model.BaseTipoOcorrencia;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author Wanderson Ferreira 30/08/2017.
*/
public class TipoOcorrenciaPolicialDAO {
public static int inserir(BaseTipoOcorrencia baseTipoOcorrencia) {
String sql = "INSERT INTO tipo_ocorrencias_policiais (tipo) VALUES (?);";
Conexao conexao = new Conexao();
try {
PreparedStatement ps = conexao.conectar().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, baseTipoOcorrencia.getTipo());
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
int codigo = rs.getInt(1);
return codigo;
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return -1;
}
public static int alterar(BaseTipoOcorrencia baseTipoOcorrencia) {
Conexao conexao = new Conexao();
try {
String sql = "UPDATE tipo_ocorrencias_policiais SET tipo = ?,"
+ "WHERE id = ?";
PreparedStatement ps = conexao.conectar().prepareStatement(sql);
ps.setString(1, baseTipoOcorrencia.getTipo());
ps.setInt(3, baseTipoOcorrencia.getId());
int resultado = ps.executeUpdate();
return resultado;
} catch (SQLException ex) {
ex.printStackTrace();
return 0;
} finally {
conexao.conectar();
}
}
public static int retornarQuantidadeRegistros() {
String sql = "SELECT COUNT (id) AS quantidade FROM tipo_ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
PreparedStatement stt = conexao.conectar().prepareCall(sql);
stt.execute(sql);
ResultSet resultado = stt.getResultSet();
if (resultado.next()) {
return resultado.getInt("quantidade");
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return -1;
}
public static BaseTipoOcorrencia buscarOPPorID(int id) {
BaseTipoOcorrencia tipoOcorrenciaPolicial = null;
String sql = "SELECT tipo FROM tipo_ocorrencias_policiais WHERE id = ?";
Conexao conexao = new Conexao();
try {
PreparedStatement ps = conexao.conectar().prepareCall(sql);
ps.setInt(1, id);
ps.execute();
ResultSet rs = ps.getResultSet();
while (rs.next()) {
tipoOcorrenciaPolicial = new BaseTipoOcorrencia();
tipoOcorrenciaPolicial.setId(id);
tipoOcorrenciaPolicial.setTipo(rs.getString("tipo"));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return tipoOcorrenciaPolicial;
}
public static ArrayList<BaseTipoOcorrencia> buscarOcorrenciaPolicial() {
ArrayList<BaseTipoOcorrencia> ocorrenciasPoliciais = new ArrayList<>();
String sql = "SELECT id, tipo FROM tipo_ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
Statement ps = conexao.conectar().createStatement();
ps.execute(sql);
ResultSet rs = ps.getResultSet();
while (rs.next()) {
BaseTipoOcorrencia ocorrenciaPolicial = new BaseTipoOcorrencia();
ocorrenciaPolicial.setId(rs.getInt("id"));
ocorrenciaPolicial.setTipo(rs.getString("tipo"));
ocorrenciasPoliciais.add(ocorrenciaPolicial);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return ocorrenciasPoliciais;
}
public static ArrayList<BaseOcorrencia> retornarOcorrenciaBombeiro(){
ArrayList<BaseOcorrencia> tabelaOcorrenciaPolicial = new ArrayList<>();
String sql = "SELECT id, id_tipo_ocorrencias_bombeiros, id_emissor, cep, rua, numero_residencia FROM ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
Statement stt = conexao.conectar().createStatement();
stt.execute(sql);
ResultSet rs = stt.getResultSet();
while (rs.next()){
BaseOcorrencia ocorrenciaPolicial = new BaseOcorrencia();
ocorrenciaPolicial.setId(rs.getInt("id"));
ocorrenciaPolicial.setBaseTipoOcorrencia(TipoOcorrenciaPolicialDAO.buscarOPPorID(rs.getInt("id_tipo_ocorrencias_policiais")));
//Tipo de ocorrencia
ocorrenciaPolicial.setEmissor(EmissorDAO.buscarEmissorPorID(rs.getInt("id_emissor")));
ocorrenciaPolicial.setCep(rs.getString("cep"));
ocorrenciaPolicial.setRua(rs.getString("rua"));
ocorrenciaPolicial.setNumeroResidencia(rs.getInt("numero_residencia"));
tabelaOcorrenciaPolicial.add(ocorrenciaPolicial);
}
}catch(SQLException ex){
ex.printStackTrace();
}finally {
conexao.desconectar();
}
return tabelaOcorrenciaPolicial;
}
} | UTF-8 | Java | 5,547 | java | TipoOcorrenciaPolicialDAO.java | Java | [
{
"context": "nt;\nimport java.util.ArrayList;\n\n/**\n *\n * @author Wanderson Ferreira 30/08/2017.\n */\npublic class TipoOcorrenciaPolici",
"end": 286,
"score": 0.9998884201049805,
"start": 268,
"tag": "NAME",
"value": "Wanderson Ferreira"
}
] | null | [] | package dao;
import database.Conexao;
import model.BaseOcorrencia;
import model.BaseTipoOcorrencia;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
/**
*
* @author <NAME> 30/08/2017.
*/
public class TipoOcorrenciaPolicialDAO {
public static int inserir(BaseTipoOcorrencia baseTipoOcorrencia) {
String sql = "INSERT INTO tipo_ocorrencias_policiais (tipo) VALUES (?);";
Conexao conexao = new Conexao();
try {
PreparedStatement ps = conexao.conectar().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, baseTipoOcorrencia.getTipo());
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
while (rs.next()) {
int codigo = rs.getInt(1);
return codigo;
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return -1;
}
public static int alterar(BaseTipoOcorrencia baseTipoOcorrencia) {
Conexao conexao = new Conexao();
try {
String sql = "UPDATE tipo_ocorrencias_policiais SET tipo = ?,"
+ "WHERE id = ?";
PreparedStatement ps = conexao.conectar().prepareStatement(sql);
ps.setString(1, baseTipoOcorrencia.getTipo());
ps.setInt(3, baseTipoOcorrencia.getId());
int resultado = ps.executeUpdate();
return resultado;
} catch (SQLException ex) {
ex.printStackTrace();
return 0;
} finally {
conexao.conectar();
}
}
public static int retornarQuantidadeRegistros() {
String sql = "SELECT COUNT (id) AS quantidade FROM tipo_ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
PreparedStatement stt = conexao.conectar().prepareCall(sql);
stt.execute(sql);
ResultSet resultado = stt.getResultSet();
if (resultado.next()) {
return resultado.getInt("quantidade");
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return -1;
}
public static BaseTipoOcorrencia buscarOPPorID(int id) {
BaseTipoOcorrencia tipoOcorrenciaPolicial = null;
String sql = "SELECT tipo FROM tipo_ocorrencias_policiais WHERE id = ?";
Conexao conexao = new Conexao();
try {
PreparedStatement ps = conexao.conectar().prepareCall(sql);
ps.setInt(1, id);
ps.execute();
ResultSet rs = ps.getResultSet();
while (rs.next()) {
tipoOcorrenciaPolicial = new BaseTipoOcorrencia();
tipoOcorrenciaPolicial.setId(id);
tipoOcorrenciaPolicial.setTipo(rs.getString("tipo"));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return tipoOcorrenciaPolicial;
}
public static ArrayList<BaseTipoOcorrencia> buscarOcorrenciaPolicial() {
ArrayList<BaseTipoOcorrencia> ocorrenciasPoliciais = new ArrayList<>();
String sql = "SELECT id, tipo FROM tipo_ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
Statement ps = conexao.conectar().createStatement();
ps.execute(sql);
ResultSet rs = ps.getResultSet();
while (rs.next()) {
BaseTipoOcorrencia ocorrenciaPolicial = new BaseTipoOcorrencia();
ocorrenciaPolicial.setId(rs.getInt("id"));
ocorrenciaPolicial.setTipo(rs.getString("tipo"));
ocorrenciasPoliciais.add(ocorrenciaPolicial);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
conexao.desconectar();
}
return ocorrenciasPoliciais;
}
public static ArrayList<BaseOcorrencia> retornarOcorrenciaBombeiro(){
ArrayList<BaseOcorrencia> tabelaOcorrenciaPolicial = new ArrayList<>();
String sql = "SELECT id, id_tipo_ocorrencias_bombeiros, id_emissor, cep, rua, numero_residencia FROM ocorrencias_policiais";
Conexao conexao = new Conexao();
try {
Statement stt = conexao.conectar().createStatement();
stt.execute(sql);
ResultSet rs = stt.getResultSet();
while (rs.next()){
BaseOcorrencia ocorrenciaPolicial = new BaseOcorrencia();
ocorrenciaPolicial.setId(rs.getInt("id"));
ocorrenciaPolicial.setBaseTipoOcorrencia(TipoOcorrenciaPolicialDAO.buscarOPPorID(rs.getInt("id_tipo_ocorrencias_policiais")));
//Tipo de ocorrencia
ocorrenciaPolicial.setEmissor(EmissorDAO.buscarEmissorPorID(rs.getInt("id_emissor")));
ocorrenciaPolicial.setCep(rs.getString("cep"));
ocorrenciaPolicial.setRua(rs.getString("rua"));
ocorrenciaPolicial.setNumeroResidencia(rs.getInt("numero_residencia"));
tabelaOcorrenciaPolicial.add(ocorrenciaPolicial);
}
}catch(SQLException ex){
ex.printStackTrace();
}finally {
conexao.desconectar();
}
return tabelaOcorrenciaPolicial;
}
} | 5,535 | 0.595457 | 0.592573 | 157 | 34.337578 | 27.961201 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.605096 | false | false | 9 |
a720b45e0944e39e449a1413faf5c27df1cc2406 | 9,689,446,232,205 | cdb977f3001cf243d8a4153d49a6f24c636b1981 | /hxf-test/src/main/java/com/hxf/test/web/util/ResponseObject.java | 92688dbbec2286207dd16d0d81a130256e8e6197 | [] | no_license | hxf044/demos | https://github.com/hxf044/demos | 9828928952a23ae37ef99cb6fc0d8e0d318c482a | 349361084be9320c0f8c71da12226b30797bc193 | refs/heads/master | 2020-04-27T15:34:35.579000 | 2019-03-08T02:14:14 | 2019-03-08T02:14:14 | 174,451,386 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hxf.test.web.util;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
/**
* @author peanut angerpeanut@gmail.com
* @since 1.0
*/
public class ResponseObject implements Serializable{
private static final long serialVersionUID = 2732127907851832345L;
private int status;
private String msg;
private Object data;
public ResponseObject(ResponseStatus status, Object data) {
this.data = data;
this.status = status.status();
this.msg = status.msg();
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
public static ResponseObject ok() {
return new ResponseObject(ResponseStatus.OK, null);
}
public static ResponseObject ok(Object data) {
return new ResponseObject(ResponseStatus.OK, data);
}
public static ResponseObject list(List list) {
return new ResponseObject(ResponseStatus.OK, new ResponseInnerListObject(list));
}
public static ResponseObject failure(ResponseStatus status) {
return new ResponseObject(status, null);
}
public static ResponseObject failure(ResponseStatus status, Object data) {
return new ResponseObject(status, data);
}
public static <X> ResponseObject wrapOrNotFound(Optional<X> data) {
return data.map(response -> ResponseObject.ok(response))
.orElse(ResponseObject.failure(ResponseStatus.NOT_FOUND));
}
public static <X> ResponseObject wrapOrNull(Optional<X> data,ResponseStatus status) {
return data.map(response -> ResponseObject.ok(response))
.orElse(ResponseObject.failure(status));
}
}
| UTF-8 | Java | 1,802 | java | ResponseObject.java | Java | [
{
"context": "l.List;\nimport java.util.Optional;\n\n/**\n * @author peanut angerpeanut@gmail.com\n * @since 1.0\n */\npublic ",
"end": 135,
"score": 0.9995646476745605,
"start": 129,
"tag": "USERNAME",
"value": "peanut"
},
{
"context": "mport java.util.Optional;\n\n/**\n * @author... | null | [] | package com.hxf.test.web.util;
import java.io.Serializable;
import java.util.List;
import java.util.Optional;
/**
* @author peanut <EMAIL>
* @since 1.0
*/
public class ResponseObject implements Serializable{
private static final long serialVersionUID = 2732127907851832345L;
private int status;
private String msg;
private Object data;
public ResponseObject(ResponseStatus status, Object data) {
this.data = data;
this.status = status.status();
this.msg = status.msg();
}
public int getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public Object getData() {
return data;
}
public static ResponseObject ok() {
return new ResponseObject(ResponseStatus.OK, null);
}
public static ResponseObject ok(Object data) {
return new ResponseObject(ResponseStatus.OK, data);
}
public static ResponseObject list(List list) {
return new ResponseObject(ResponseStatus.OK, new ResponseInnerListObject(list));
}
public static ResponseObject failure(ResponseStatus status) {
return new ResponseObject(status, null);
}
public static ResponseObject failure(ResponseStatus status, Object data) {
return new ResponseObject(status, data);
}
public static <X> ResponseObject wrapOrNotFound(Optional<X> data) {
return data.map(response -> ResponseObject.ok(response))
.orElse(ResponseObject.failure(ResponseStatus.NOT_FOUND));
}
public static <X> ResponseObject wrapOrNull(Optional<X> data,ResponseStatus status) {
return data.map(response -> ResponseObject.ok(response))
.orElse(ResponseObject.failure(status));
}
}
| 1,788 | 0.667592 | 0.655938 | 79 | 21.810127 | 25.970322 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367089 | false | false | 9 |
b5e024371b9b659c081af2a025a5790930c841ee | 13,322,988,565,149 | 3211d33c3563f13e631823f89f79b975a1397966 | /engine/src/main/java/org/terasology/engine/rendering/assets/mesh/resource/AllocationType.java | 7d2fe140812bd7375533caf50efc58db9b73a865 | [
"Apache-2.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | MovingBlocks/Terasology | https://github.com/MovingBlocks/Terasology | 16de3854efe0896ae7a9e1a6d5036078bd4d4941 | 36591e16a4b5f120be8460013d69300ffbb48ec1 | refs/heads/develop | 2023-08-24T03:00:17.723000 | 2023-08-13T18:00:30 | 2023-08-13T18:00:30 | 1,438,007 | 3,344 | 1,871 | Apache-2.0 | false | 2023-09-10T19:16:22 | 2011-03-04T03:49:19 | 2023-09-08T16:28:43 | 2023-09-10T19:16:21 | 300,495 | 3,549 | 1,331 | 478 | Java | false | false | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.rendering.assets.mesh.resource;
import org.lwjgl.opengl.GL33;
public enum AllocationType {
STATIC(GL33.GL_STATIC_DRAW),
DYNAMIC(GL33.GL_DYNAMIC_DRAW),
STREAM(GL33.GL_STREAM_DRAW);
public final int glCall;
AllocationType(int gl) {
this.glCall = gl;
}
}
| UTF-8 | Java | 402 | java | AllocationType.java | Java | [] | null | [] | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.engine.rendering.assets.mesh.resource;
import org.lwjgl.opengl.GL33;
public enum AllocationType {
STATIC(GL33.GL_STATIC_DRAW),
DYNAMIC(GL33.GL_DYNAMIC_DRAW),
STREAM(GL33.GL_STREAM_DRAW);
public final int glCall;
AllocationType(int gl) {
this.glCall = gl;
}
}
| 402 | 0.708955 | 0.674129 | 18 | 21.333334 | 18.058546 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 9 |
18017be653fdee0f36ae2b044fb5437efedf52ad | 10,024,453,678,719 | 987c697617bff0c9d9473920d428cdb18db4069d | /dch-util/src/main/java/com/dch/util/ReadExcelToDb.java | 7761c06ddd39c2ded1347b13aa225cc6e3e05789 | [] | no_license | bellmit/dch-health | https://github.com/bellmit/dch-health | f78060ecc8cede64941f0bd0c66d834015762655 | 63eade430f17c3973d647a783908680f5fe12495 | refs/heads/master | 2022-04-14T20:11:06.821000 | 2019-03-21T09:50:09 | 2019-03-21T09:56:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dch.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.*;
/**
* Created by sunkqa on 2018/4/8.
*/
public class ReadExcelToDb {
//private static String excelDir = "F:\\skqRare\\excel";
public static List<Map> readDirExcel(String excelDir) {
List<Map> list = new ArrayList<>();
try {
File file = new File(excelDir);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list.addAll(readExcelFile(f,null));
}
}else{
list = readExcelFile(file,null);
}
}catch (Exception e){
e.printStackTrace();
}
return list;
}
public static List<Map> readExcelFile(File f,Map titleMap) throws Exception{
List<Map> list = new ArrayList<>();
LinkedHashMap colMap = new LinkedHashMap();
if(f.getName().indexOf("xls")>0||f.getName().indexOf("xlsx")>0){
// jxl提供的Workbook类
Workbook wb = readExcel(f.getAbsolutePath());
Sheet sheet=wb.getSheetAt(0);
for(int i=0;i<sheet.getPhysicalNumberOfRows();i++){
LinkedHashMap map = new LinkedHashMap();
Row row = sheet.getRow(i);
if(i<1 && !titleMap.isEmpty()){
for(int j=0;j<row.getPhysicalNumberOfCells();j++){
colMap.put("col_"+j,titleMap.get(getCellFormatValue(row.getCell(j))));
}
}else{
for(int j=0;j<row.getPhysicalNumberOfCells();j++){
Object value = getCellFormatValue(row.getCell(j));
if(value instanceof String){
value = value.toString().replace(" ","");
}
map.put(colMap.get("col_"+j),value);
}
list.add(map);
}
}
}
return list;
}
//读取excel
public static Workbook readExcel(String filePath){
Workbook wb = null;
if(filePath==null){
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
try {
is = new FileInputStream(filePath);
if(".xls".equals(extString)){
return wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(extString)){
return wb = new XSSFWorkbook(is);
}else{
return wb = null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return wb;
}
public static Object getCellFormatValue(Cell cell){
Object cellValue = null;
if(cell!=null){
//判断cell类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:{
cellValue = String.valueOf(cell.getNumericCellValue());
cellValue = Double.valueOf(cellValue.toString());
break;
}
case Cell.CELL_TYPE_FORMULA:{
//判断cell是否为日期格式
if(DateUtil.isCellDateFormatted(cell)){
//转换为日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue();
}else{
//数字
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING:{
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
}else{
cellValue = "";
}
return cellValue;
}
}
| UTF-8 | Java | 4,178 | java | ReadExcelToDb.java | Java | [
{
"context": " java.io.*;\nimport java.util.*;\n\n/**\n * Created by sunkqa on 2018/4/8.\n */\npublic class ReadExcelToDb {\n ",
"end": 228,
"score": 0.9995692372322083,
"start": 222,
"tag": "USERNAME",
"value": "sunkqa"
}
] | null | [] | package com.dch.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.*;
/**
* Created by sunkqa on 2018/4/8.
*/
public class ReadExcelToDb {
//private static String excelDir = "F:\\skqRare\\excel";
public static List<Map> readDirExcel(String excelDir) {
List<Map> list = new ArrayList<>();
try {
File file = new File(excelDir);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
list.addAll(readExcelFile(f,null));
}
}else{
list = readExcelFile(file,null);
}
}catch (Exception e){
e.printStackTrace();
}
return list;
}
public static List<Map> readExcelFile(File f,Map titleMap) throws Exception{
List<Map> list = new ArrayList<>();
LinkedHashMap colMap = new LinkedHashMap();
if(f.getName().indexOf("xls")>0||f.getName().indexOf("xlsx")>0){
// jxl提供的Workbook类
Workbook wb = readExcel(f.getAbsolutePath());
Sheet sheet=wb.getSheetAt(0);
for(int i=0;i<sheet.getPhysicalNumberOfRows();i++){
LinkedHashMap map = new LinkedHashMap();
Row row = sheet.getRow(i);
if(i<1 && !titleMap.isEmpty()){
for(int j=0;j<row.getPhysicalNumberOfCells();j++){
colMap.put("col_"+j,titleMap.get(getCellFormatValue(row.getCell(j))));
}
}else{
for(int j=0;j<row.getPhysicalNumberOfCells();j++){
Object value = getCellFormatValue(row.getCell(j));
if(value instanceof String){
value = value.toString().replace(" ","");
}
map.put(colMap.get("col_"+j),value);
}
list.add(map);
}
}
}
return list;
}
//读取excel
public static Workbook readExcel(String filePath){
Workbook wb = null;
if(filePath==null){
return null;
}
String extString = filePath.substring(filePath.lastIndexOf("."));
InputStream is = null;
try {
is = new FileInputStream(filePath);
if(".xls".equals(extString)){
return wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(extString)){
return wb = new XSSFWorkbook(is);
}else{
return wb = null;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return wb;
}
public static Object getCellFormatValue(Cell cell){
Object cellValue = null;
if(cell!=null){
//判断cell类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:{
cellValue = String.valueOf(cell.getNumericCellValue());
cellValue = Double.valueOf(cellValue.toString());
break;
}
case Cell.CELL_TYPE_FORMULA:{
//判断cell是否为日期格式
if(DateUtil.isCellDateFormatted(cell)){
//转换为日期格式YYYY-mm-dd
cellValue = cell.getDateCellValue();
}else{
//数字
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING:{
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
}
}else{
cellValue = "";
}
return cellValue;
}
}
| 4,178 | 0.478894 | 0.47574 | 120 | 33.349998 | 21.506453 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 9 |
49b7d9a85418721fae618f57beef38ed1f574d6f | 12,060,268,168,443 | 505c97e18a00365b952cecc652279dc41f622e6b | /demo-zk/src/main/java/com/zk/lock/DistributedLock.java | 6f7f3d995c88fda3a39b9166075ed69f8bb48392 | [] | no_license | halbert918/demo-test | https://github.com/halbert918/demo-test | acfdb2dec51a85e9dd1e057c28302831ecd79356 | 248b4936cb235d814a9f03910fd5946cb5898984 | refs/heads/master | 2021-01-10T11:00:49.159000 | 2017-04-28T07:55:49 | 2017-04-28T07:55:49 | 51,733,087 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zk.lock;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 基于zookeeper实现的分布式锁
* @Vesrion 1.0
* @Author heyinbo
* @Date 2016/1/6
* @Description
*/
public class DistributedLock implements Lock {
private static final Logger logger = LoggerFactory.getLogger(DistributedLock.class);
private ZooKeeper zooKeeper = null;
/**
* 锁根节点目录
*/
private final String LOCK_ROOT = "/locks";
/**
* 当前节点
*/
private String currentNode;
/**
* 获取需要监控的前一个节点
*/
private String prevNode;
/**
* 当前已获得锁节点
*/
private String lockedBy;
/**
* 节点名称
*/
private String nodeName;
/**
* 线程阻塞,直到计数器减为0
*/
private CountDownLatch latch;
public DistributedLock() {
this("/lock");
}
public DistributedLock(String nodeName) {
this("192.168.52.128:2181", 60000, nodeName);
}
public DistributedLock(String connectString, int sessionTimeout, String nodeName) {
this.nodeName = nodeName;
initZooKeeper(connectString, sessionTimeout);
latch = new CountDownLatch(1);
}
/**
* 初始化zookeeper
* @param connectString
* @param sessionTimeout
*/
public void initZooKeeper(String connectString, int sessionTimeout) {
try {
//创建zookeeper实例,Watcher:监控节点变化的事件
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new ZKWatcher());
//判断锁对应的根节点是否存在
Stat stat = zooKeeper.exists(LOCK_ROOT, false);
if(null == stat) {
zooKeeper.create(LOCK_ROOT, LOCK_ROOT.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
@Override
public void lock() {
//尝试获取锁
if(!tryLock()) {
//阻塞
await();
}
logger.info("线程{}获取锁{}", Thread.currentThread().getName(), currentNode);
}
/**
* 阻塞线程,直到latch计数countDown=0
*/
private void await() {
try {
Stat stat = zooKeeper.exists(prevNode, true);
if(null != stat) {
logger.info("线程{}被阻塞,当前锁{}", Thread.currentThread().getName(), lockedBy);
latch.await();
}
//前一个节点不存在,则当前节点可获取锁
lockedBy = currentNode;
} catch (InterruptedException e) {
logger.error("thread is interrupted{}", e);
} catch (KeeperException e) {
logger.error("KeeperException{}", e);
e.printStackTrace();
}
}
@Override
public boolean tryLock() {
if(hasLocked()) {
return true;
}
try {
if (null == currentNode) {
currentNode = zooKeeper.create(LOCK_ROOT + nodeName, Thread.currentThread().getName().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
logger.info("线程{}创建节点{}完成", Thread.currentThread().getName(), currentNode);
}
//如果当前最小的节点与当前创建的节点相同,则获取到锁
if(isLockNode(currentNode)) {
return true;
}
} catch (InterruptedException e) {
logger.error("create zooKeeper node failed...", e);
e.printStackTrace();
} catch (KeeperException e) {
logger.error("create zooKeeper node failed...", e);
e.printStackTrace();
}
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
/**
* 判断当前节点是否是需要枷锁的节点(最小的节点)
* @param currentNode
* @return
*/
private boolean isLockNode(String currentNode) {
List<String> nodes = getChildren();
Collections.sort(nodes, new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
lockedBy = LOCK_ROOT + "/" + nodes.get(0);
if(currentNode.equals(lockedBy)) {
return true;
}
//获取当前节点的前一个节点数据(监控前一个节点数据的变化)
String nodeName = currentNode.substring(LOCK_ROOT.length() + 1);
for(int i = 1; i < nodes.size(); i++) {
if(nodeName.equals(nodes.get(i))) {
prevNode = LOCK_ROOT + "/" + nodes.get(i - 1);
break;
}
}
return false;
}
/**
* 获取所有节点
* @return
*/
private List<String> getChildren() {
try {
return zooKeeper.getChildren(LOCK_ROOT, false);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
/**
* 判断当前是否已经获取到锁
* @return
*/
private boolean hasLocked() {
return null != currentNode && null != lockedBy && currentNode.equals(lockedBy);
}
@Override
public void unlock() {
try {
Stat stat = zooKeeper.exists(currentNode, true);
if(null != stat) {
logger.info("线程{}释放锁{}", Thread.currentThread().getName(), currentNode);
zooKeeper.delete(currentNode, stat.getVersion());
}
} catch (KeeperException e) {
e.printStackTrace();
logger.info("线程{}释放锁{}失败", Thread.currentThread().getName(), currentNode);
} catch (InterruptedException e) {
e.printStackTrace();
logger.info("线程{}释放锁{}失败", Thread.currentThread().getName(), currentNode);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public Condition newCondition() {
return null;
}
/**
* 监控节点变化
*/
private class ZKWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
//判断是否是删除节点事件,并且判断删除的节点是否是当前节点的前一个节点
if(event.getType() == Event.EventType.NodeDeleted) {
//阻塞线程计数器减1
latch.countDown();
}
}
}
}
| UTF-8 | Java | 7,284 | java | DistributedLock.java | Java | [
{
"context": "*\n * 基于zookeeper实现的分布式锁\n * @Vesrion 1.0\n * @Author heyinbo\n * @Date 2016/1/6\n * @Description\n */\npublic clas",
"end": 488,
"score": 0.9995977878570557,
"start": 481,
"tag": "USERNAME",
"value": "heyinbo"
},
{
"context": " DistributedLock(String nodeName) {\n ... | null | [] | package com.zk.lock;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* 基于zookeeper实现的分布式锁
* @Vesrion 1.0
* @Author heyinbo
* @Date 2016/1/6
* @Description
*/
public class DistributedLock implements Lock {
private static final Logger logger = LoggerFactory.getLogger(DistributedLock.class);
private ZooKeeper zooKeeper = null;
/**
* 锁根节点目录
*/
private final String LOCK_ROOT = "/locks";
/**
* 当前节点
*/
private String currentNode;
/**
* 获取需要监控的前一个节点
*/
private String prevNode;
/**
* 当前已获得锁节点
*/
private String lockedBy;
/**
* 节点名称
*/
private String nodeName;
/**
* 线程阻塞,直到计数器减为0
*/
private CountDownLatch latch;
public DistributedLock() {
this("/lock");
}
public DistributedLock(String nodeName) {
this("192.168.52.128:2181", 60000, nodeName);
}
public DistributedLock(String connectString, int sessionTimeout, String nodeName) {
this.nodeName = nodeName;
initZooKeeper(connectString, sessionTimeout);
latch = new CountDownLatch(1);
}
/**
* 初始化zookeeper
* @param connectString
* @param sessionTimeout
*/
public void initZooKeeper(String connectString, int sessionTimeout) {
try {
//创建zookeeper实例,Watcher:监控节点变化的事件
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new ZKWatcher());
//判断锁对应的根节点是否存在
Stat stat = zooKeeper.exists(LOCK_ROOT, false);
if(null == stat) {
zooKeeper.create(LOCK_ROOT, LOCK_ROOT.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
@Override
public void lock() {
//尝试获取锁
if(!tryLock()) {
//阻塞
await();
}
logger.info("线程{}获取锁{}", Thread.currentThread().getName(), currentNode);
}
/**
* 阻塞线程,直到latch计数countDown=0
*/
private void await() {
try {
Stat stat = zooKeeper.exists(prevNode, true);
if(null != stat) {
logger.info("线程{}被阻塞,当前锁{}", Thread.currentThread().getName(), lockedBy);
latch.await();
}
//前一个节点不存在,则当前节点可获取锁
lockedBy = currentNode;
} catch (InterruptedException e) {
logger.error("thread is interrupted{}", e);
} catch (KeeperException e) {
logger.error("KeeperException{}", e);
e.printStackTrace();
}
}
@Override
public boolean tryLock() {
if(hasLocked()) {
return true;
}
try {
if (null == currentNode) {
currentNode = zooKeeper.create(LOCK_ROOT + nodeName, Thread.currentThread().getName().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
logger.info("线程{}创建节点{}完成", Thread.currentThread().getName(), currentNode);
}
//如果当前最小的节点与当前创建的节点相同,则获取到锁
if(isLockNode(currentNode)) {
return true;
}
} catch (InterruptedException e) {
logger.error("create zooKeeper node failed...", e);
e.printStackTrace();
} catch (KeeperException e) {
logger.error("create zooKeeper node failed...", e);
e.printStackTrace();
}
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
/**
* 判断当前节点是否是需要枷锁的节点(最小的节点)
* @param currentNode
* @return
*/
private boolean isLockNode(String currentNode) {
List<String> nodes = getChildren();
Collections.sort(nodes, new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
});
lockedBy = LOCK_ROOT + "/" + nodes.get(0);
if(currentNode.equals(lockedBy)) {
return true;
}
//获取当前节点的前一个节点数据(监控前一个节点数据的变化)
String nodeName = currentNode.substring(LOCK_ROOT.length() + 1);
for(int i = 1; i < nodes.size(); i++) {
if(nodeName.equals(nodes.get(i))) {
prevNode = LOCK_ROOT + "/" + nodes.get(i - 1);
break;
}
}
return false;
}
/**
* 获取所有节点
* @return
*/
private List<String> getChildren() {
try {
return zooKeeper.getChildren(LOCK_ROOT, false);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
/**
* 判断当前是否已经获取到锁
* @return
*/
private boolean hasLocked() {
return null != currentNode && null != lockedBy && currentNode.equals(lockedBy);
}
@Override
public void unlock() {
try {
Stat stat = zooKeeper.exists(currentNode, true);
if(null != stat) {
logger.info("线程{}释放锁{}", Thread.currentThread().getName(), currentNode);
zooKeeper.delete(currentNode, stat.getVersion());
}
} catch (KeeperException e) {
e.printStackTrace();
logger.info("线程{}释放锁{}失败", Thread.currentThread().getName(), currentNode);
} catch (InterruptedException e) {
e.printStackTrace();
logger.info("线程{}释放锁{}失败", Thread.currentThread().getName(), currentNode);
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public Condition newCondition() {
return null;
}
/**
* 监控节点变化
*/
private class ZKWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
//判断是否是删除节点事件,并且判断删除的节点是否是当前节点的前一个节点
if(event.getType() == Event.EventType.NodeDeleted) {
//阻塞线程计数器减1
latch.countDown();
}
}
}
}
| 7,284 | 0.559748 | 0.553459 | 246 | 26.146341 | 24.550655 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.463415 | false | false | 9 |
0afa514f08bd1606859a2f9f7e8c3ff3bf2db806 | 8,134,668,068,231 | fe6902aa141019ea17a7f1fe3bac093d9b5a7213 | /tweetservice/src/main/java/ademsalih/softwarearch/tweetservice/service/NewTweetService.java | a67919685affa9063817e80bed053155f687e8ec | [] | no_license | ademsalih/twitterclone | https://github.com/ademsalih/twitterclone | a8122998a54852e25cc1b13060580728f7dcecfb | defa5596ff4ac4e0af0fff4ff24a986ad1fa9b8b | refs/heads/master | 2021-06-10T01:20:39.825000 | 2019-10-02T07:37:55 | 2019-10-02T07:37:55 | 177,738,358 | 1 | 0 | null | false | 2021-06-07T16:53:47 | 2019-03-26T07:43:27 | 2020-01-15T23:40:03 | 2021-06-07T16:53:46 | 85,079 | 1 | 0 | 1 | Java | false | false | package ademsalih.softwarearch.tweetservice.service;
import ademsalih.softwarearch.tweetservice.model.NewTweet;
import ademsalih.softwarearch.tweetservice.model.Tweet;
import java.util.List;
public interface NewTweetService {
List<NewTweet> getAllNewTweets();
List<NewTweet> getNewTweetsForUser(long id);
NewTweet getNewTweet(long id);
NewTweet saveNewTweet(NewTweet newTweet);
void deleteNewTweet(long id);
List<NewTweet> getTweetForSearch(String query);
void deleteAllTweetsForUser(long id);
}
| UTF-8 | Java | 534 | java | NewTweetService.java | Java | [] | null | [] | package ademsalih.softwarearch.tweetservice.service;
import ademsalih.softwarearch.tweetservice.model.NewTweet;
import ademsalih.softwarearch.tweetservice.model.Tweet;
import java.util.List;
public interface NewTweetService {
List<NewTweet> getAllNewTweets();
List<NewTweet> getNewTweetsForUser(long id);
NewTweet getNewTweet(long id);
NewTweet saveNewTweet(NewTweet newTweet);
void deleteNewTweet(long id);
List<NewTweet> getTweetForSearch(String query);
void deleteAllTweetsForUser(long id);
}
| 534 | 0.780899 | 0.780899 | 23 | 22.217392 | 22.463413 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 9 |
a9f8d55e51fa99743ae7fb079262ef3af96154b8 | 37,941,741,101,217 | 12ce2231d0a4f68ce3ee59270531824895a63752 | /SalesClient/src/main/java/com/xiaoxing/salesclient/di/component/ZhanTingDetailComponent.java | 88b797fe01f494fdc2efc684d4e22b1a5322f475 | [] | no_license | lqqhd/paimai | https://github.com/lqqhd/paimai | 96333f6974a1eb6a9917bb7b671abcc12ccbbc33 | 675006bec0f8a92ca44b0881d58ffd2741caee52 | refs/heads/master | 2021-04-19T14:04:35.644000 | 2018-08-17T02:21:07 | 2018-08-17T02:21:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xiaoxing.salesclient.di.component;
import dagger.Component;
import com.jess.arms.di.component.AppComponent;
import com.xiaoxing.salesclient.di.module.ZhanTingDetailModule;
import com.jess.arms.di.scope.ActivityScope;
import com.xiaoxing.salesclient.mvp.ui.activity.ZhanTingDetailActivity;
@ActivityScope
@Component(modules = ZhanTingDetailModule.class, dependencies = AppComponent.class)
public interface ZhanTingDetailComponent {
void inject(ZhanTingDetailActivity activity);
} | UTF-8 | Java | 499 | java | ZhanTingDetailComponent.java | Java | [] | null | [] | package com.xiaoxing.salesclient.di.component;
import dagger.Component;
import com.jess.arms.di.component.AppComponent;
import com.xiaoxing.salesclient.di.module.ZhanTingDetailModule;
import com.jess.arms.di.scope.ActivityScope;
import com.xiaoxing.salesclient.mvp.ui.activity.ZhanTingDetailActivity;
@ActivityScope
@Component(modules = ZhanTingDetailModule.class, dependencies = AppComponent.class)
public interface ZhanTingDetailComponent {
void inject(ZhanTingDetailActivity activity);
} | 499 | 0.837675 | 0.837675 | 16 | 30.25 | 27.902733 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
d6e581fe01a1dd166cc03c394a596dbb5b972b5d | 35,794,257,477,134 | d3e03a0b1d9df542f813772935f0a0ed0ecbe087 | /ojcms-sqlbuilder/src/main/java/de/adito/ojcms/sqlbuilder/OJSQLBuilderForTableImpl.java | 007b9f31b6d92c0124843371d03dae999058013b | [
"MIT"
] | permissive | aditosoftware/beans | https://github.com/aditosoftware/beans | dedef20500b876174b4634281e93553ec3c11176 | 56c522501ac8ac27afd50889a4553e318728980a | refs/heads/master | 2021-05-08T07:42:39.785000 | 2020-06-13T14:00:00 | 2020-06-13T14:00:00 | 106,793,886 | 3 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.adito.ojcms.sqlbuilder;
import de.adito.ojcms.sqlbuilder.definition.IColumnIdentification;
import de.adito.ojcms.sqlbuilder.definition.column.IColumnDefinition;
import de.adito.ojcms.sqlbuilder.platform.IDatabasePlatform;
import de.adito.ojcms.sqlbuilder.platform.connection.IDatabaseConnectionSupplier;
import de.adito.ojcms.sqlbuilder.serialization.IValueSerializer;
import de.adito.ojcms.sqlbuilder.statements.types.Create;
import de.adito.ojcms.utils.StringUtility;
import java.util.Set;
import java.util.function.Consumer;
/**
* Implementation of the SQL builder for single tables.
*
* @author Simon Danner, 15.05.2018
*/
final class OJSQLBuilderForTableImpl extends AbstractSQLBuilder implements OJSQLBuilderForTable
{
private final String tableName;
/**
* Creates a new builder.
*
* @param pPlatform the database platform to use for this builder
* @param pConnectionSupplier the database platform based connection supplier
* @param pCloseAfterStatement <tt>true</tt>, if the connection should be closed after executing one statement
* @param pSerializer the value serializer
* @param pTableName the name of the table to use for this builder
* @param pIdColumnName a global id column name for this builder instance
*/
OJSQLBuilderForTableImpl(IDatabasePlatform pPlatform, IDatabaseConnectionSupplier pConnectionSupplier, boolean pCloseAfterStatement,
IValueSerializer pSerializer, String pTableName, String pIdColumnName)
{
super(pPlatform, pConnectionSupplier, pCloseAfterStatement, pSerializer, pIdColumnName);
tableName = StringUtility.requireNotEmpty(pTableName, "table name");
}
@Override
public void dropTable()
{
boolean result = super.dropTable(tableName);
if (!result)
throw new IllegalStateException("The table " + tableName + " is not existing anymore!");
}
@Override
public void addColumn(IColumnDefinition pColumnDefinition)
{
super.addColumn(tableName, pColumnDefinition);
}
@Override
public void removeColumn(IColumnIdentification<?> pColumn)
{
super.removeColumn(tableName, pColumn);
}
@Override
public boolean hasTable()
{
return super.hasTable(tableName);
}
@Override
public void ifTableNotExistingCreate(Consumer<Create> pCreateStatement)
{
super.ifTableNotExistingCreate(tableName, pCreateStatement);
}
@Override
public int getColumnCount()
{
return super.getColumnCount(tableName);
}
@Override
public boolean hasColumn(String pColumnName)
{
return super.hasColumn(tableName, pColumnName);
}
@Override
public Set<String> getAllColumnNames()
{
return super.getAllColumnNames(tableName);
}
@Override
protected <RESULT, STATEMENT extends AbstractSQLStatement<RESULT, STATEMENT>> STATEMENT configureStatementBeforeExecution(
STATEMENT pStatement)
{
pStatement.setTableName(tableName);
return pStatement;
}
}
| UTF-8 | Java | 2,996 | java | OJSQLBuilderForTableImpl.java | Java | [
{
"context": "f the SQL builder for single tables.\n *\n * @author Simon Danner, 15.05.2018\n */\nfinal class OJSQLBuilderForTableI",
"end": 628,
"score": 0.9996678233146667,
"start": 616,
"tag": "NAME",
"value": "Simon Danner"
}
] | null | [] | package de.adito.ojcms.sqlbuilder;
import de.adito.ojcms.sqlbuilder.definition.IColumnIdentification;
import de.adito.ojcms.sqlbuilder.definition.column.IColumnDefinition;
import de.adito.ojcms.sqlbuilder.platform.IDatabasePlatform;
import de.adito.ojcms.sqlbuilder.platform.connection.IDatabaseConnectionSupplier;
import de.adito.ojcms.sqlbuilder.serialization.IValueSerializer;
import de.adito.ojcms.sqlbuilder.statements.types.Create;
import de.adito.ojcms.utils.StringUtility;
import java.util.Set;
import java.util.function.Consumer;
/**
* Implementation of the SQL builder for single tables.
*
* @author <NAME>, 15.05.2018
*/
final class OJSQLBuilderForTableImpl extends AbstractSQLBuilder implements OJSQLBuilderForTable
{
private final String tableName;
/**
* Creates a new builder.
*
* @param pPlatform the database platform to use for this builder
* @param pConnectionSupplier the database platform based connection supplier
* @param pCloseAfterStatement <tt>true</tt>, if the connection should be closed after executing one statement
* @param pSerializer the value serializer
* @param pTableName the name of the table to use for this builder
* @param pIdColumnName a global id column name for this builder instance
*/
OJSQLBuilderForTableImpl(IDatabasePlatform pPlatform, IDatabaseConnectionSupplier pConnectionSupplier, boolean pCloseAfterStatement,
IValueSerializer pSerializer, String pTableName, String pIdColumnName)
{
super(pPlatform, pConnectionSupplier, pCloseAfterStatement, pSerializer, pIdColumnName);
tableName = StringUtility.requireNotEmpty(pTableName, "table name");
}
@Override
public void dropTable()
{
boolean result = super.dropTable(tableName);
if (!result)
throw new IllegalStateException("The table " + tableName + " is not existing anymore!");
}
@Override
public void addColumn(IColumnDefinition pColumnDefinition)
{
super.addColumn(tableName, pColumnDefinition);
}
@Override
public void removeColumn(IColumnIdentification<?> pColumn)
{
super.removeColumn(tableName, pColumn);
}
@Override
public boolean hasTable()
{
return super.hasTable(tableName);
}
@Override
public void ifTableNotExistingCreate(Consumer<Create> pCreateStatement)
{
super.ifTableNotExistingCreate(tableName, pCreateStatement);
}
@Override
public int getColumnCount()
{
return super.getColumnCount(tableName);
}
@Override
public boolean hasColumn(String pColumnName)
{
return super.hasColumn(tableName, pColumnName);
}
@Override
public Set<String> getAllColumnNames()
{
return super.getAllColumnNames(tableName);
}
@Override
protected <RESULT, STATEMENT extends AbstractSQLStatement<RESULT, STATEMENT>> STATEMENT configureStatementBeforeExecution(
STATEMENT pStatement)
{
pStatement.setTableName(tableName);
return pStatement;
}
}
| 2,990 | 0.753672 | 0.751001 | 97 | 29.886599 | 33.213425 | 134 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43299 | false | false | 9 |
df3daabe47d1d984f132bbb5903335c6e7a0696d | 35,794,257,477,296 | e19a80f671e79fee5f8a00a4e6b5e2bc1ec2c580 | /ursful-mina-core/src/main/java/com/ursful/framework/mina/client/mina/packet/PacketWriter.java | 021dfc47e651482dcb75e7d0c34adde9b53f9380 | [] | no_license | ynicing/urs-database | https://github.com/ynicing/urs-database | e1a0286842ca94753ae5fb13da275a6ad036d42c | 2fce01dec5e25726c37898992567929900e0576e | refs/heads/master | 2021-01-23T14:16:49.835000 | 2020-12-24T02:02:41 | 2020-12-24T02:02:41 | 93,249,747 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ursful.framework.mina.client.mina.packet;
import com.ursful.framework.mina.common.packet.Packet;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class PacketWriter {
private static Logger log = LoggerFactory.getLogger(PacketWriter.class.getName());
private Thread writerThread;
private IoSession session;
private final BlockingQueue<Packet> queue;
volatile boolean done = false;
public IoSession getSession() {
return session;
}
public PacketWriter(IoSession session) {
this.session = session;
this.queue = new ArrayBlockingQueue<Packet>(500, true);
init();
}
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
protected void init() {
done = false;
writerThread = new Thread() {
public void run() {
writePackets(this);
}
};
writerThread.setName("Message Packet Writer");
writerThread.setDaemon(true);
}
/**
* Sends the specified packet to the server.
*
* @param packet the packet to send.
*/
public void sendPacket(Packet packet) {
try {
queue.put(packet);
}
catch (InterruptedException ie) {
return;
}
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Starts the packet writer thread and opens a connection to the server. The
* packet writer will continue writing packets until {@link #shutdown} or an
* error occurs.
*/
public void startup() {
writerThread.start();
}
/**
* Shuts down the packet writer. Once this method has been called, no further
* packets will be written to the server.
*/
public void shutdown() {
done = true;
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Returns the next available packet from the queue for writing.
*
* @return the next packet for writing.
*/
private Packet nextPacket() {
Packet packet = null;
// Wait until there's a packet or we're done.
while ((packet = queue.poll()) == null) {
try {
synchronized (queue) {
queue.wait();
}
}
catch (InterruptedException ie) {
// Do nothing
}
}
return packet;
}
private void writePackets(Thread thisThread) {
// Open the stream.
// Write out packets from the queue.
while ( (writerThread == thisThread)) {
Packet packet = nextPacket();
if (packet != null) {
session.write(packet);
}
// if (queue.isEmpty()) {
// writer.flush();
// }
// }
}
// Flush out the rest of the queue. If the queue is extremely large, it's possible
// we won't have time to entirely flush it before the socket is forced closed
// by the shutdown process.
try {
while (!queue.isEmpty()) {
Packet packet = queue.remove();
session.write(packet);
}
// writer.flush();
}
catch (Exception e) {
log.warn("Error flushing queue during shutdown, ignore and continue");
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
}
}
| UTF-8 | Java | 3,883 | java | PacketWriter.java | Java | [] | null | [] | package com.ursful.framework.mina.client.mina.packet;
import com.ursful.framework.mina.common.packet.Packet;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class PacketWriter {
private static Logger log = LoggerFactory.getLogger(PacketWriter.class.getName());
private Thread writerThread;
private IoSession session;
private final BlockingQueue<Packet> queue;
volatile boolean done = false;
public IoSession getSession() {
return session;
}
public PacketWriter(IoSession session) {
this.session = session;
this.queue = new ArrayBlockingQueue<Packet>(500, true);
init();
}
/**
* Initializes the writer in order to be used. It is called at the first connection and also
* is invoked if the connection is disconnected by an error.
*/
protected void init() {
done = false;
writerThread = new Thread() {
public void run() {
writePackets(this);
}
};
writerThread.setName("Message Packet Writer");
writerThread.setDaemon(true);
}
/**
* Sends the specified packet to the server.
*
* @param packet the packet to send.
*/
public void sendPacket(Packet packet) {
try {
queue.put(packet);
}
catch (InterruptedException ie) {
return;
}
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Starts the packet writer thread and opens a connection to the server. The
* packet writer will continue writing packets until {@link #shutdown} or an
* error occurs.
*/
public void startup() {
writerThread.start();
}
/**
* Shuts down the packet writer. Once this method has been called, no further
* packets will be written to the server.
*/
public void shutdown() {
done = true;
synchronized (queue) {
queue.notifyAll();
}
}
/**
* Returns the next available packet from the queue for writing.
*
* @return the next packet for writing.
*/
private Packet nextPacket() {
Packet packet = null;
// Wait until there's a packet or we're done.
while ((packet = queue.poll()) == null) {
try {
synchronized (queue) {
queue.wait();
}
}
catch (InterruptedException ie) {
// Do nothing
}
}
return packet;
}
private void writePackets(Thread thisThread) {
// Open the stream.
// Write out packets from the queue.
while ( (writerThread == thisThread)) {
Packet packet = nextPacket();
if (packet != null) {
session.write(packet);
}
// if (queue.isEmpty()) {
// writer.flush();
// }
// }
}
// Flush out the rest of the queue. If the queue is extremely large, it's possible
// we won't have time to entirely flush it before the socket is forced closed
// by the shutdown process.
try {
while (!queue.isEmpty()) {
Packet packet = queue.remove();
session.write(packet);
}
// writer.flush();
}
catch (Exception e) {
log.warn("Error flushing queue during shutdown, ignore and continue");
}
// Delete the queue contents (hopefully nothing is left).
queue.clear();
}
}
| 3,883 | 0.543137 | 0.541849 | 136 | 27.55147 | 23.035721 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.308824 | false | false | 9 |
fabc28cf419a7df36e54ca16e19af68b6d5311df | 34,677,565,982,707 | 586968cb48c5f00ce8765ed2efa9cc883ad55f1d | /src/test/java/B2B_PageLoadTime/TestSuiteBase.java | 2495c7f0702402966e82f581be2b6a045cdf8779 | [] | no_license | mrsachin24/B2B | https://github.com/mrsachin24/B2B | f76fc24eef299f5012c5166fad24d7dd8b713849 | 7504386477c55e6d6cab8da2de45101f6d0749fc | refs/heads/master | 2021-01-19T05:30:26.743000 | 2016-07-05T11:16:52 | 2016-07-05T11:16:52 | 62,558,104 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package B2B_PageLoadTime;
import org.testng.SkipException;
import org.testng.annotations.BeforeSuite;
import util.Utility;
public class TestSuiteBase {
@BeforeSuite
public void checkSuitRun(){
System.out.println("checking checkSuitRun ="+Utility.isSuiteRunnable("B2B_PageLoadTime") );
Utility.creatingXlsReportFolder("B2B_PageLoadTime");
if(!Utility.isSuiteRunnable("B2B_PageLoadTime")){
System.out.println("Inside checkSuitRun");
Utility.isSuiteRunnableReport("B2B_PageLoadTime");
throw new SkipException("Skipping the testsuite as runmmode is set to ");
}
else{
System.out.println("Running the testCase");
}
}
}
| UTF-8 | Java | 650 | java | TestSuiteBase.java | Java | [] | null | [] | package B2B_PageLoadTime;
import org.testng.SkipException;
import org.testng.annotations.BeforeSuite;
import util.Utility;
public class TestSuiteBase {
@BeforeSuite
public void checkSuitRun(){
System.out.println("checking checkSuitRun ="+Utility.isSuiteRunnable("B2B_PageLoadTime") );
Utility.creatingXlsReportFolder("B2B_PageLoadTime");
if(!Utility.isSuiteRunnable("B2B_PageLoadTime")){
System.out.println("Inside checkSuitRun");
Utility.isSuiteRunnableReport("B2B_PageLoadTime");
throw new SkipException("Skipping the testsuite as runmmode is set to ");
}
else{
System.out.println("Running the testCase");
}
}
}
| 650 | 0.755385 | 0.747692 | 23 | 27.26087 | 26.173697 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.521739 | false | false | 9 |
f71d65e2371b1e0772ab3ca31f857cd3b1d674ab | 34,411,277,999,783 | 5be877771eec456ec1a7bd25944a650e0d0f32b4 | /src/main/java/fr/an/mem4j/datatypesystem/reflect/AllocArrayDataType.java | eecbccb8e4ddd6116c5a87186cf715b5eb43e943 | [] | no_license | d4rkang3l/mem4j | https://github.com/d4rkang3l/mem4j | 165376cf153c8a4a947d2d8ec2ccae42f0540fbe | 4043597d1d1fe7418161e222befe827df76a1634 | refs/heads/master | 2021-01-21T10:04:37.577000 | 2016-04-03T22:15:51 | 2016-04-03T22:15:51 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.an.mem4j.datatypesystem.reflect;
import fr.an.mem4j.datatypesystem.DataTypeSystem;
/**
*
*/
public class AllocArrayDataType extends TemplateInstanceDataType {
private final int allocArrayLen;
// ------------------------------------------------------------------------
public AllocArrayDataType(DataTypeSystem owner, ParametricLenArrayDataType templateArrayDataType, int allocArrayLen) {
super(owner, templateArrayDataType);
this.allocArrayLen = allocArrayLen;
}
// ------------------------------------------------------------------------
public ParametricLenArrayDataType getTemplateArrayDataType() {
return (ParametricLenArrayDataType) super.templateDataType;
}
public FixedLenDataType getElementDataType() {
return getTemplateArrayDataType().getElementType();
}
public int getAllocArrayLen() {
return allocArrayLen;
}
// ------------------------------------------------------------------------
@Override
public int hashCode() {
final int prime = 31;
int result = allocArrayLen * prime + templateDataType.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AllocArrayDataType other = (AllocArrayDataType) obj;
if (templateDataType != other.templateDataType)
return false;
if (allocArrayLen != other.allocArrayLen)
return false;
return true;
}
@Override
public String toString() {
return "alloc(" + allocArrayLen + "*" + getElementDataType().getName() + ")";
}
}
| UTF-8 | Java | 1,815 | java | AllocArrayDataType.java | Java | [] | null | [] | package fr.an.mem4j.datatypesystem.reflect;
import fr.an.mem4j.datatypesystem.DataTypeSystem;
/**
*
*/
public class AllocArrayDataType extends TemplateInstanceDataType {
private final int allocArrayLen;
// ------------------------------------------------------------------------
public AllocArrayDataType(DataTypeSystem owner, ParametricLenArrayDataType templateArrayDataType, int allocArrayLen) {
super(owner, templateArrayDataType);
this.allocArrayLen = allocArrayLen;
}
// ------------------------------------------------------------------------
public ParametricLenArrayDataType getTemplateArrayDataType() {
return (ParametricLenArrayDataType) super.templateDataType;
}
public FixedLenDataType getElementDataType() {
return getTemplateArrayDataType().getElementType();
}
public int getAllocArrayLen() {
return allocArrayLen;
}
// ------------------------------------------------------------------------
@Override
public int hashCode() {
final int prime = 31;
int result = allocArrayLen * prime + templateDataType.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AllocArrayDataType other = (AllocArrayDataType) obj;
if (templateDataType != other.templateDataType)
return false;
if (allocArrayLen != other.allocArrayLen)
return false;
return true;
}
@Override
public String toString() {
return "alloc(" + allocArrayLen + "*" + getElementDataType().getName() + ")";
}
}
| 1,815 | 0.554821 | 0.552617 | 63 | 27.809525 | 27.779665 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.349206 | false | false | 9 |
2b9de122c60a71932cf102d53c35f2c364a1d3d4 | 31,456,340,539,551 | 13e5310caa1859039ee8ab5a562d4e725b8b67e9 | /app/src/main/java/air/net/deflexion/mobile/LucidEggApp/presentation/di/modules/RepositoryModule.java | 002542779a71a9ea06d34bba764381576c0d0eb1 | [] | no_license | ThomasWilliamMarsh/EggRecipes | https://github.com/ThomasWilliamMarsh/EggRecipes | cd889fb27a7ea8aedfbcd7c33616a92ed2fa75c8 | 4a738eef5b8c3823177322046bab6a2b37d97f9c | HEAD | 2018-04-10T13:39:49.702000 | 2018-03-07T20:24:52 | 2018-03-07T20:24:52 | 82,470,599 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package air.net.deflexion.mobile.LucidEggApp.presentation.di.modules;
import javax.inject.Singleton;
import air.net.deflexion.mobile.LucidEggApp.data.repository.CategoriesDataRepository;
import air.net.deflexion.mobile.LucidEggApp.data.repository.RecipesDataRepository;
import air.net.deflexion.mobile.LucidEggApp.data.repository.VideosDataRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.CategoriesRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.RecipesRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.VideosRepository;
import dagger.Module;
import dagger.Provides;
/**
* Created by thomas on 10/27/2017.
*/
@Module
public class RepositoryModule {
@Provides
@Singleton
CategoriesRepository provideCategoriesRepository(CategoriesDataRepository categoriesDataRepository) {
return categoriesDataRepository;
}
@Provides
@Singleton
RecipesRepository provideRecipesRepository(RecipesDataRepository recipesDataRepository) {
return recipesDataRepository;
}
@Provides
@Singleton
VideosRepository provideVideosRepository(VideosDataRepository videosDataRepository) {
return videosDataRepository;
}
}
| UTF-8 | Java | 1,247 | java | RepositoryModule.java | Java | [
{
"context": "Module;\nimport dagger.Provides;\n\n/**\n * Created by thomas on 10/27/2017.\n */\n\n@Module\npublic class Reposito",
"end": 670,
"score": 0.9873238801956177,
"start": 664,
"tag": "USERNAME",
"value": "thomas"
}
] | null | [] | package air.net.deflexion.mobile.LucidEggApp.presentation.di.modules;
import javax.inject.Singleton;
import air.net.deflexion.mobile.LucidEggApp.data.repository.CategoriesDataRepository;
import air.net.deflexion.mobile.LucidEggApp.data.repository.RecipesDataRepository;
import air.net.deflexion.mobile.LucidEggApp.data.repository.VideosDataRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.CategoriesRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.RecipesRepository;
import air.net.deflexion.mobile.LucidEggApp.domain.repository.VideosRepository;
import dagger.Module;
import dagger.Provides;
/**
* Created by thomas on 10/27/2017.
*/
@Module
public class RepositoryModule {
@Provides
@Singleton
CategoriesRepository provideCategoriesRepository(CategoriesDataRepository categoriesDataRepository) {
return categoriesDataRepository;
}
@Provides
@Singleton
RecipesRepository provideRecipesRepository(RecipesDataRepository recipesDataRepository) {
return recipesDataRepository;
}
@Provides
@Singleton
VideosRepository provideVideosRepository(VideosDataRepository videosDataRepository) {
return videosDataRepository;
}
}
| 1,247 | 0.809142 | 0.802727 | 38 | 31.81579 | 33.82996 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.342105 | false | false | 9 |
eb8422bab63a913ef32845d056557b642f2da460 | 29,154,238,072,023 | 94df773f2993d98b8a0c388967a8b82b7ca3b269 | /src/org/zkoss/eclipse/componentwizard/wizards/NewComponentWizardPage.java | aac4f1d6083b211038457bc2e2a196c1c94c429b | [] | no_license | chun13009/zk-cdt | https://github.com/chun13009/zk-cdt | 6b15af49178f1030da2b5e5544e712c8932b6d91 | 759f9198bc6869580e7f878757958eb07a1f75cd | refs/heads/master | 2016-09-06T16:25:01.277000 | 2011-08-18T06:30:46 | 2011-08-18T06:30:46 | 38,148,519 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.zkoss.eclipse.componentwizard.wizards;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The "New" wizard page allows setting the container for the new file as well
* as the file name. The page will only accept file name without the extension
* OR with the extension that matches the expected one (xml).
*/
public class NewComponentWizardPage extends WizardPage {
protected Text projectNameText;
protected Text componentNameText;
protected Text componentClassText;
protected Text widgetNameText;
protected ISelection selection;
public static final String PAGE_NAME = " ZKComponentWizardPage";
/**
* Constructor for SampleNewWizardPage.
*
* @param pageName
*/
public NewComponentWizardPage(ISelection selection) {
super(PAGE_NAME);
setTitle("ZK Component Wizard");
setDescription("The wizard create a ZK Component skeleton.");
this.selection = selection;
}
public NewComponentWizardPage(String pageName,ISelection selection) {
super(pageName);
setTitle("ZK Component Wizard");
setDescription("The wizard create a ZK Component skeleton.");
this.selection = selection;
}
protected void createSubControls(Composite container){
Label label = new Label(container, SWT.NULL);
label.setText("&ProjectName:");
projectNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
projectNameText.setLayoutData(gd);
projectNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateProject();
}
});
label = new Label(container, SWT.NULL);
label.setText("&Component name:");
componentNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
componentNameText.setLayoutData(gd);
componentNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
label = new Label(container, SWT.NULL);
label.setText("&Component class name:");
componentClassText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
componentClassText.setLayoutData(gd);
componentClassText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
label = new Label(container, SWT.NULL);
label.setText("&Widget name:");
widgetNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
widgetNameText.setLayoutData(gd);
widgetNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
projectNameText.setText("test");
componentClassText.setText("org.test.Mylabel");
componentNameText.setText("mylabel");
widgetNameText.setText("test.Mylabel");
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
/**
* TODO add workspace location
*/
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
layout.verticalSpacing = 9;
createSubControls(container);
initialize();
setControl(container);
}
public boolean validateProject() {
String projectName = projectNameText.getText();
if ("".equals(projectName) || projectName == null) {
showError("You have to enter a project name.");
return false;
}
if (ResourcesPlugin.getWorkspace().getRoot().findMember(projectName) != null) {
showError("project is already exist");
return false;
}
showPass();
return true;
}
public void showPass() {
setErrorMessage(null);
setMessage(null);
setPageComplete(true);
}
public void showError(String message) {
setErrorMessage(message);
setMessage("......");
setPageComplete(false);
}
public void validate() {
setErrorMessage(null);
setMessage("......");
setPageComplete(false);
}
/**
* Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
if (selection != null && selection.isEmpty() == false
&& selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
if (ssel.size() > 1)
return;
Object obj = ssel.getFirstElement();
if (obj instanceof IResource) {
IContainer container;
if (obj instanceof IContainer)
container = (IContainer) obj;
else
container = ((IResource) obj).getParent();
projectNameText.setText(container.getFullPath().toString());
}
}
}
public String getProjectName() {
return projectNameText.getText();
}
public String getComponentPackage() {
String val = componentClassText.getText();
if(val.lastIndexOf(".")!= -1 )
return val.substring(0,val.lastIndexOf(".") +1 );
else
return "";
}
public String getComponentClass() {
String val = componentClassText.getText();
if(val.lastIndexOf(".") != -1 )
return val.substring(val.lastIndexOf(".")+1);
else
return val;
}
public String getWidgetPackage() {
String val = widgetNameText.getText();
if(val.lastIndexOf(".")!= -1 )
return val.substring(0,val.lastIndexOf(".") +1 );
else
return "";
}
public String getWidgetName() {
String val = widgetNameText.getText();
if(val.lastIndexOf(".") != -1 )
return val.substring(val.lastIndexOf(".")+1);
else
return val;
}
public String getComponentName() {
return componentNameText.getText();
}
} | UTF-8 | Java | 6,065 | java | NewComponentWizardPage.java | Java | [] | null | [] | package org.zkoss.eclipse.componentwizard.wizards;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The "New" wizard page allows setting the container for the new file as well
* as the file name. The page will only accept file name without the extension
* OR with the extension that matches the expected one (xml).
*/
public class NewComponentWizardPage extends WizardPage {
protected Text projectNameText;
protected Text componentNameText;
protected Text componentClassText;
protected Text widgetNameText;
protected ISelection selection;
public static final String PAGE_NAME = " ZKComponentWizardPage";
/**
* Constructor for SampleNewWizardPage.
*
* @param pageName
*/
public NewComponentWizardPage(ISelection selection) {
super(PAGE_NAME);
setTitle("ZK Component Wizard");
setDescription("The wizard create a ZK Component skeleton.");
this.selection = selection;
}
public NewComponentWizardPage(String pageName,ISelection selection) {
super(pageName);
setTitle("ZK Component Wizard");
setDescription("The wizard create a ZK Component skeleton.");
this.selection = selection;
}
protected void createSubControls(Composite container){
Label label = new Label(container, SWT.NULL);
label.setText("&ProjectName:");
projectNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
projectNameText.setLayoutData(gd);
projectNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
validateProject();
}
});
label = new Label(container, SWT.NULL);
label.setText("&Component name:");
componentNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
componentNameText.setLayoutData(gd);
componentNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
label = new Label(container, SWT.NULL);
label.setText("&Component class name:");
componentClassText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
componentClassText.setLayoutData(gd);
componentClassText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
label = new Label(container, SWT.NULL);
label.setText("&Widget name:");
widgetNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
gd = new GridData(GridData.FILL_HORIZONTAL);
widgetNameText.setLayoutData(gd);
widgetNameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
}
});
projectNameText.setText("test");
componentClassText.setText("org.test.Mylabel");
componentNameText.setText("mylabel");
widgetNameText.setText("test.Mylabel");
}
/**
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
/**
* TODO add workspace location
*/
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 2;
layout.verticalSpacing = 9;
createSubControls(container);
initialize();
setControl(container);
}
public boolean validateProject() {
String projectName = projectNameText.getText();
if ("".equals(projectName) || projectName == null) {
showError("You have to enter a project name.");
return false;
}
if (ResourcesPlugin.getWorkspace().getRoot().findMember(projectName) != null) {
showError("project is already exist");
return false;
}
showPass();
return true;
}
public void showPass() {
setErrorMessage(null);
setMessage(null);
setPageComplete(true);
}
public void showError(String message) {
setErrorMessage(message);
setMessage("......");
setPageComplete(false);
}
public void validate() {
setErrorMessage(null);
setMessage("......");
setPageComplete(false);
}
/**
* Tests if the current workbench selection is a suitable container to use.
*/
private void initialize() {
if (selection != null && selection.isEmpty() == false
&& selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
if (ssel.size() > 1)
return;
Object obj = ssel.getFirstElement();
if (obj instanceof IResource) {
IContainer container;
if (obj instanceof IContainer)
container = (IContainer) obj;
else
container = ((IResource) obj).getParent();
projectNameText.setText(container.getFullPath().toString());
}
}
}
public String getProjectName() {
return projectNameText.getText();
}
public String getComponentPackage() {
String val = componentClassText.getText();
if(val.lastIndexOf(".")!= -1 )
return val.substring(0,val.lastIndexOf(".") +1 );
else
return "";
}
public String getComponentClass() {
String val = componentClassText.getText();
if(val.lastIndexOf(".") != -1 )
return val.substring(val.lastIndexOf(".")+1);
else
return val;
}
public String getWidgetPackage() {
String val = widgetNameText.getText();
if(val.lastIndexOf(".")!= -1 )
return val.substring(0,val.lastIndexOf(".") +1 );
else
return "";
}
public String getWidgetName() {
String val = widgetNameText.getText();
if(val.lastIndexOf(".") != -1 )
return val.substring(val.lastIndexOf(".")+1);
else
return val;
}
public String getComponentName() {
return componentNameText.getText();
}
} | 6,065 | 0.723825 | 0.721682 | 225 | 25.959999 | 21.808727 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.991111 | false | false | 9 |
b731570953f075ab2f97ae3706bdaee636a730ee | 33,990,371,202,886 | 5586fcea50a25dbb108438e7ee602aa50077efee | /src/main/java/com/cai/item/pojo/Perms.java | bd688f2dd0476df8c4645bfb57eb2dc6e048b8fe | [] | no_license | cai8606/bysj | https://github.com/cai8606/bysj | 05317714bb3eb6c9e0fea1e1c8df5f7cd15ef29f | 747a073da4afb1ce9fb46331c6949620eb325b95 | refs/heads/master | 2022-10-19T10:37:24.722000 | 2020-03-23T13:25:59 | 2020-03-23T13:25:59 | 249,435,775 | 0 | 1 | null | false | 2022-10-12T20:37:52 | 2020-03-23T13:17:24 | 2020-03-23T13:27:38 | 2022-10-12T20:37:50 | 29 | 0 | 1 | 4 | Java | false | false | package com.cai.item.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "permission")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
@Id
@KeySql(useGeneratedKeys = true)
private Integer id;
private String permissionName;
private String url;
private Integer pid;
private String flagName;
private Integer level;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date createTime;
}
| UTF-8 | Java | 671 | java | Perms.java | Java | [] | null | [] | package com.cai.item.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
@Table(name = "permission")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
@Id
@KeySql(useGeneratedKeys = true)
private Integer id;
private String permissionName;
private String url;
private Integer pid;
private String flagName;
private Integer level;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date createTime;
}
| 671 | 0.76155 | 0.76155 | 28 | 22.964285 | 13.097116 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 9 |
ea4540daafc83c9f667daaa69eef6415532cf0b9 | 4,836,133,194,287 | f756830dab3b61b262419ff9b93cb5267f8e918a | /src/main/java/com/gl365/validator/mapper/SzbIdCardMapper.java | f2fd25ec9217b9c712c229e7c59ca19f50278360 | [] | no_license | pengjianbo3478/validator | https://github.com/pengjianbo3478/validator | db970b73e2e39fa7a0cd11202e97c1602bccc87f | ab7cf9b864af5572a0c1080929dde60914f06a5f | refs/heads/master | 2020-03-17T07:02:33.215000 | 2018-05-14T15:21:01 | 2018-05-14T15:21:01 | 133,380,310 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gl365.validator.mapper;
import org.apache.ibatis.annotations.Param;
import com.gl365.validator.model.SzbIdCard;
public interface SzbIdCardMapper {
int insertSelective(SzbIdCard record);
SzbIdCard selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SzbIdCard record);
SzbIdCard selective(@Param("cardId")String cardId, @Param("userName")String userName);
} | UTF-8 | Java | 416 | java | SzbIdCardMapper.java | Java | [] | null | [] | package com.gl365.validator.mapper;
import org.apache.ibatis.annotations.Param;
import com.gl365.validator.model.SzbIdCard;
public interface SzbIdCardMapper {
int insertSelective(SzbIdCard record);
SzbIdCard selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(SzbIdCard record);
SzbIdCard selective(@Param("cardId")String cardId, @Param("userName")String userName);
} | 416 | 0.752404 | 0.737981 | 17 | 22.588236 | 26.513168 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 9 |
8579bf55f7e8a70e679e55af4542e4b4740c305c | 33,543,694,646,461 | dbc12351853bc727eddca5b9c16c82d62c4d697f | /jtafi18n/src/main/java/dweb/test/templates/TestTemplate.java | fcabd4af457b0265a79b98acc55f8734db5dd82a | [] | no_license | manish6789/Sawaglabs2 | https://github.com/manish6789/Sawaglabs2 | 1d4239611b32dc841b00a95c70b318c5f45233fc | af6e610aa203d2315357bde3b3b16a069e5e3f62 | refs/heads/master | 2022-06-17T09:42:56.512000 | 2019-10-25T18:42:16 | 2019-10-25T18:42:16 | 217,573,382 | 0 | 0 | null | false | 2022-05-20T21:14:26 | 2019-10-25T16:25:59 | 2019-10-25T18:42:18 | 2022-05-20T21:14:25 | 7,783 | 0 | 0 | 2 | HTML | false | false | package dweb.test.templates;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import com.config.IConstants;
import com.config.ITestParamsConstants;
import com.excel.Xls_Reader;
import com.google.common.io.Resources;
import com.testreport.IReporter;
import com.utilities.ReusableLibs;
import com.utilities.TestUtil;
public abstract class TestTemplate {
private static final Logger LOG = Logger.getLogger(TestTemplate.class);
protected static IReporter testReport = null;
protected String ChromeDriverExe = null;
// protected String url = null;
protected static String implicitWaitInSecs = null;
protected static String pageLoadTimeOutInSecs = null;
public static ThreadLocal<WebDriver> threadLocalWebDriver = new ThreadLocal<WebDriver>();
/**
* get parameter from either test context or framework configuration file where
* test context parameter overrides framework configuration parameter
*
* @param testContext
* @param parameter
* @return
*/
protected String getTestParameter(ITestContext testContext, String parameter) {
String parameterVal = testContext.getCurrentXmlTest().getParameter(parameter) == null
? ReusableLibs.getConfigProperty(parameter)
: testContext.getCurrentXmlTest().getParameter(parameter);
LOG.info(String.format("Test Execution Input Parameter = %s, Value = %s", parameter, parameterVal));
return parameterVal;
}
/**
*
* @param testContext
* @return
*/
protected Map<String, String> getAllTestParameters(ITestContext testContext) {
return testContext.getCurrentXmlTest().getAllParameters();
}
/**
*
* @param testContext
* @param regExp
* @return
*/
protected Map<String, String> getAllTestParameters(ITestContext testContext, String regExp) {
Map<String, String> mapMobileParams = new HashMap<String, String>();
this.getAllTestParameters(testContext).forEach((k, v) -> {
if (k.matches(regExp)) {
mapMobileParams.put(k, v);
}
});
return mapMobileParams;
}
protected DesiredCapabilities convertTestParamsToCapabilities(ITestContext testContext)
{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setBrowserName(this.getTestParameter(testContext, ITestParamsConstants.BROWSER));
this.getAllTestParameters(testContext).forEach((k, v) ->{
cap.setCapability(k, v);
});
return cap;
}
/**
*
* @param testContext
* @param regExp
* @return
*/
protected DesiredCapabilities convertTestParamsToCapabilities(ITestContext testContext, String regExp)
{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setBrowserName(this.getTestParameter(testContext, ITestParamsConstants.BROWSER));
this.getAllTestParameters(testContext, regExp).forEach((k, v) ->{
cap.setCapability(k, v);
});
return cap;
}
/**
* Dataprovider to return data matrix from excel
*
* @return
* @throws URISyntaxException
*/
@DataProvider(name = "getDataFromExcel", parallel = false)
protected Object[][] getDataFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("PhoneBookSearch", xlsReader, "PhoneBook");
return objMetrics;
}
@DataProvider(name = "getTitleFromExcel", parallel = false)
protected Object[][] getTitleFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("PhoneBookPageTitleVerify", xlsReader, "PhoneBook");
return objMetrics;
}
@DataProvider(name = "getVendorDataFromExcel", parallel = false)
protected Object[][] getVendorDataFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("JDEVendorSearch", xlsReader, "VendorSearch");
return objMetrics;
}
/**
* Returns screenshot name for screenshot being captured
*
* @return
*/
protected String getScreenShotName() {
String screenShotLocation = ReusableLibs.getConfigProperty(ITestParamsConstants.SCREENSHOT_LOCATION);
String fileExtension = ReusableLibs.getConfigProperty(ITestParamsConstants.SCREENSHOT_PICTURE_FORMAT);
synchronized (this) {
String screenShotName = ReusableLibs.getScreenshotFile(screenShotLocation, fileExtension);
LOG.debug(String.format("ScreenShot Name For Captured Screen Shot = %s", screenShotName));
return screenShotName;
}
}
}
| UTF-8 | Java | 5,436 | java | TestTemplate.java | Java | [] | null | [] | package dweb.test.templates;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import com.config.IConstants;
import com.config.ITestParamsConstants;
import com.excel.Xls_Reader;
import com.google.common.io.Resources;
import com.testreport.IReporter;
import com.utilities.ReusableLibs;
import com.utilities.TestUtil;
public abstract class TestTemplate {
private static final Logger LOG = Logger.getLogger(TestTemplate.class);
protected static IReporter testReport = null;
protected String ChromeDriverExe = null;
// protected String url = null;
protected static String implicitWaitInSecs = null;
protected static String pageLoadTimeOutInSecs = null;
public static ThreadLocal<WebDriver> threadLocalWebDriver = new ThreadLocal<WebDriver>();
/**
* get parameter from either test context or framework configuration file where
* test context parameter overrides framework configuration parameter
*
* @param testContext
* @param parameter
* @return
*/
protected String getTestParameter(ITestContext testContext, String parameter) {
String parameterVal = testContext.getCurrentXmlTest().getParameter(parameter) == null
? ReusableLibs.getConfigProperty(parameter)
: testContext.getCurrentXmlTest().getParameter(parameter);
LOG.info(String.format("Test Execution Input Parameter = %s, Value = %s", parameter, parameterVal));
return parameterVal;
}
/**
*
* @param testContext
* @return
*/
protected Map<String, String> getAllTestParameters(ITestContext testContext) {
return testContext.getCurrentXmlTest().getAllParameters();
}
/**
*
* @param testContext
* @param regExp
* @return
*/
protected Map<String, String> getAllTestParameters(ITestContext testContext, String regExp) {
Map<String, String> mapMobileParams = new HashMap<String, String>();
this.getAllTestParameters(testContext).forEach((k, v) -> {
if (k.matches(regExp)) {
mapMobileParams.put(k, v);
}
});
return mapMobileParams;
}
protected DesiredCapabilities convertTestParamsToCapabilities(ITestContext testContext)
{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setBrowserName(this.getTestParameter(testContext, ITestParamsConstants.BROWSER));
this.getAllTestParameters(testContext).forEach((k, v) ->{
cap.setCapability(k, v);
});
return cap;
}
/**
*
* @param testContext
* @param regExp
* @return
*/
protected DesiredCapabilities convertTestParamsToCapabilities(ITestContext testContext, String regExp)
{
DesiredCapabilities cap = new DesiredCapabilities();
cap.setBrowserName(this.getTestParameter(testContext, ITestParamsConstants.BROWSER));
this.getAllTestParameters(testContext, regExp).forEach((k, v) ->{
cap.setCapability(k, v);
});
return cap;
}
/**
* Dataprovider to return data matrix from excel
*
* @return
* @throws URISyntaxException
*/
@DataProvider(name = "getDataFromExcel", parallel = false)
protected Object[][] getDataFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("PhoneBookSearch", xlsReader, "PhoneBook");
return objMetrics;
}
@DataProvider(name = "getTitleFromExcel", parallel = false)
protected Object[][] getTitleFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("PhoneBookPageTitleVerify", xlsReader, "PhoneBook");
return objMetrics;
}
@DataProvider(name = "getVendorDataFromExcel", parallel = false)
protected Object[][] getVendorDataFromExcel() throws URISyntaxException {
URL urlFilePath = Resources.getResource(String.format("%s/%s", IConstants.TEST_DATA_LOCATION, IConstants.TEST_DATA_EXCEL_FILE));
String filePath = Paths.get(urlFilePath.toURI()).toFile().getAbsolutePath();
Xls_Reader xlsReader = new Xls_Reader(filePath);
Object[][] objMetrics = TestUtil.getData("JDEVendorSearch", xlsReader, "VendorSearch");
return objMetrics;
}
/**
* Returns screenshot name for screenshot being captured
*
* @return
*/
protected String getScreenShotName() {
String screenShotLocation = ReusableLibs.getConfigProperty(ITestParamsConstants.SCREENSHOT_LOCATION);
String fileExtension = ReusableLibs.getConfigProperty(ITestParamsConstants.SCREENSHOT_PICTURE_FORMAT);
synchronized (this) {
String screenShotName = ReusableLibs.getScreenshotFile(screenShotLocation, fileExtension);
LOG.debug(String.format("ScreenShot Name For Captured Screen Shot = %s", screenShotName));
return screenShotName;
}
}
}
| 5,436 | 0.737859 | 0.737675 | 153 | 33.529411 | 33.700928 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.856209 | false | false | 9 |
7e6297eb03d7b0066e913d15c00bbe0c762dcbf5 | 9,380,208,580,292 | 213313eef6d77a0e5d616f9171f25cdf1bf6d9ae | /src/main/java/Shapes/Circle.java | 291f06839d19e4bc460e2b0782509c18cc96cc90 | [] | no_license | Vlad-Kliucharov/Projects | https://github.com/Vlad-Kliucharov/Projects | 1e8e446ff742106e6c4c110807ae4677539e6e06 | 38c9497d9a4517dd3a2d8433e872569b4db6ac82 | refs/heads/master | 2016-09-14T03:14:08.043000 | 2016-08-03T11:38:41 | 2016-08-03T11:38:41 | 64,837,777 | 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 Shapes;
/**
*
* @author Lenovo
*/
public class Circle {
public static void main(String[] args) {
int sr = 3;
int c = 5;
int R = 4;
System.out.println(" = " + 3.14 * (double) (sr * 2));
System.out.println(" = " + 3.14 * (double) c);
System.out.println(" = " + 3.14 * (double) (R * 2 - sr * 2));
}
}
| UTF-8 | Java | 574 | java | Circle.java | Java | [
{
"context": "itor.\r\n */\r\npackage Shapes;\r\n\r\n/**\r\n *\r\n * @author Lenovo\r\n */\r\npublic class Circle {\r\n\r\n public static ",
"end": 235,
"score": 0.9938435554504395,
"start": 229,
"tag": "USERNAME",
"value": "Lenovo"
}
] | 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 Shapes;
/**
*
* @author Lenovo
*/
public class Circle {
public static void main(String[] args) {
int sr = 3;
int c = 5;
int R = 4;
System.out.println(" = " + 3.14 * (double) (sr * 2));
System.out.println(" = " + 3.14 * (double) c);
System.out.println(" = " + 3.14 * (double) (R * 2 - sr * 2));
}
}
| 574 | 0.538328 | 0.512195 | 22 | 24.09091 | 24.864923 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 9 |
97b6f0cb9dc86eefc7d7cbca9d710189953185f2 | 7,584,912,249,278 | 1b978d4e59d21a3abc62d1623608d20ba4fd7533 | /demo/src/main/java/me/yokeyword/sample/demo_wechat/MainActivity.java | 0d18b37fa40f5cc53ea11f0e0e5f0f2e15c86145 | [
"Apache-2.0"
] | permissive | No1CharlesWu/ticker-android-fragmentation | https://github.com/No1CharlesWu/ticker-android-fragmentation | 524630f86e4da12c94b74eb244affeb3bb761490 | 268630be7436d7099265988d94bb4f30f75855e9 | refs/heads/master | 2021-08-30T16:05:10.593000 | 2017-12-17T07:36:33 | 2017-12-17T07:36:33 | 110,708,680 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.yokeyword.sample.demo_wechat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import me.yokeyword.sample.R;
import me.yokeyword.sample.demo_wechat.net.AlertService;
import me.yokeyword.sample.demo_wechat.ui.fragment.MainFragment;
import me.yokeyword.sample.demo_wechat.ui.fragment.second.WechatSecondTabFragment;
import me.yokeyword.sample.demo_wechat.ui.fragment.setting.AlertListFragment;
/**
* 仿微信交互方式Demo
* Created by YoKeyword on 16/6/30.
*/
public class MainActivity extends SupportActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wechat_activity_main);
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, mainFragment, "MainFragment").commit();
Intent intent = new Intent(this, AlertService.class);
startService(intent);
if (findFragment(MainFragment.class) == null) {
loadRootFragment(R.id.fl_container, MainFragment.newInstance());
}
}
@Override
public void onBackPressedSupport() {
// 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
super.onBackPressedSupport();
}
@Override
public FragmentAnimator onCreateFragmentAnimator() {
// 设置横向(和安卓4.x动画相同)
return new DefaultHorizontalAnimator();
}
@Override
protected void onResume() {
// getNotify(getIntent());
super.onResume();
}
@Override
protected void onNewIntent(Intent intent) {
// getNotify(intent);
setIntent(intent);
}
private void getNotify(Intent intent){
String value = intent.getStringExtra("toValue");
Log.i("TAG", "onNewIntent: " + value);
if(!TextUtils.isEmpty(value)) {
switch (value) {
case "href":
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, mainFragment, "MainFragment").commitAllowingStateLoss();
if (findFragment(MainFragment.class) == null) {
loadRootFragment(R.id.fl_container, MainFragment.newInstance());
}
//这里不是用的commit提交,用的commitAllowingStateLoss方式。commit不允许后台执行,不然会报Deferring update until onResume 错误
break;
}
}
super.onNewIntent(intent);
}
}
| UTF-8 | Java | 3,005 | java | MainActivity.java | Java | [
{
"context": "ertListFragment;\n\n/**\n * 仿微信交互方式Demo\n * Created by YoKeyword on 16/6/30.\n */\npublic class MainActivity extends",
"end": 773,
"score": 0.9994044899940491,
"start": 764,
"tag": "USERNAME",
"value": "YoKeyword"
}
] | null | [] | package me.yokeyword.sample.demo_wechat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import me.yokeyword.sample.R;
import me.yokeyword.sample.demo_wechat.net.AlertService;
import me.yokeyword.sample.demo_wechat.ui.fragment.MainFragment;
import me.yokeyword.sample.demo_wechat.ui.fragment.second.WechatSecondTabFragment;
import me.yokeyword.sample.demo_wechat.ui.fragment.setting.AlertListFragment;
/**
* 仿微信交互方式Demo
* Created by YoKeyword on 16/6/30.
*/
public class MainActivity extends SupportActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wechat_activity_main);
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, mainFragment, "MainFragment").commit();
Intent intent = new Intent(this, AlertService.class);
startService(intent);
if (findFragment(MainFragment.class) == null) {
loadRootFragment(R.id.fl_container, MainFragment.newInstance());
}
}
@Override
public void onBackPressedSupport() {
// 对于 4个类别的主Fragment内的回退back逻辑,已经在其onBackPressedSupport里各自处理了
super.onBackPressedSupport();
}
@Override
public FragmentAnimator onCreateFragmentAnimator() {
// 设置横向(和安卓4.x动画相同)
return new DefaultHorizontalAnimator();
}
@Override
protected void onResume() {
// getNotify(getIntent());
super.onResume();
}
@Override
protected void onNewIntent(Intent intent) {
// getNotify(intent);
setIntent(intent);
}
private void getNotify(Intent intent){
String value = intent.getStringExtra("toValue");
Log.i("TAG", "onNewIntent: " + value);
if(!TextUtils.isEmpty(value)) {
switch (value) {
case "href":
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, mainFragment, "MainFragment").commitAllowingStateLoss();
if (findFragment(MainFragment.class) == null) {
loadRootFragment(R.id.fl_container, MainFragment.newInstance());
}
//这里不是用的commit提交,用的commitAllowingStateLoss方式。commit不允许后台执行,不然会报Deferring update until onResume 错误
break;
}
}
super.onNewIntent(intent);
}
}
| 3,005 | 0.680851 | 0.678061 | 84 | 33.130951 | 30.432899 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.52381 | false | false | 9 |
c8c7296e8a1b52c4805064f4947561c49bfab18b | 16,612,933,502,933 | 39dfb03c483956f351481338a623017571ce36f7 | /src/org/gss/adi/dialogs/OpenImageFromURL.java | 40b34c361c6d5842c8f391001db8957003f0f3f3 | [] | no_license | MaximeIJ/Analyzing-Digital-Images | https://github.com/MaximeIJ/Analyzing-Digital-Images | 12ad697a9a85526641982898c71be75417403991 | cc02058019d9e85ea607934eb4745fc4a7b0ffd3 | refs/heads/master | 2021-01-18T12:01:44.832000 | 2015-02-20T17:23:00 | 2015-02-20T17:23:00 | 23,059,506 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.gss.adi.dialogs;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.gss.adi.Entrance;
import org.gss.adi.Updatable;
public class OpenImageFromURL extends JDialog
{
private static final long serialVersionUID = 7441043699183274678L;
private JTextField textField;
private Entrance entrance;
public static final byte IMAGE = 0;
public static final byte TIME_SERIES1 = 1;
public static final byte TIME_SERIES2 = 2;
public static final byte TIME_SERIES3 = 3;
public OpenImageFromURL(Entrance e, final byte imgType)
{
setTitle("Upload an Image from a URL");
setBounds(100, 100, 450, 120);
getContentPane().setLayout(null);
setAlwaysOnTop(true);
this.entrance = e;
this.textField = new JTextField();
this.textField.setBounds(10, 16, 414, 20);
getContentPane().add(this.textField);
this.textField.setColumns(10);
JTextField txtUrl = new JTextField();
txtUrl.setOpaque(false);
txtUrl.setBorder(null);
txtUrl.setEditable(false);
txtUrl.setFont(new Font("SansSerif", 0, 10));
txtUrl.setText("URL");
txtUrl.setBounds(10, 0, 86, 15);
getContentPane().add(txtUrl);
txtUrl.setColumns(10);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OpenImageFromURL.this.dispose();
}
});
btnCancel.setBounds(335, 47, 89, 23);
getContentPane().add(btnCancel);
JButton btnUpload = new JButton("Upload");
btnUpload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
URL url = new URL(OpenImageFromURL.this.textField.getText());
BufferedImage img = ImageIO.read(url);
switch (imgType) {
case 0:
OpenImageFromURL.this.entrance.setImageTrim(img);
OpenImageFromURL.this.entrance.setTitle(url.toString());
break;
case 1:
OpenImageFromURL.this.entrance.setTimeSeries1(img);
OpenImageFromURL.this.entrance.setTitle1(url.toString());
break;
case 2:
OpenImageFromURL.this.entrance.setTimeSeries2(img);
OpenImageFromURL.this.entrance.setTitle2(url.toString());
break;
case 3:
OpenImageFromURL.this.entrance.setTimeSeries3(img);
OpenImageFromURL.this.entrance.setTitle3(url.toString());
}
if ((OpenImageFromURL.this.entrance.getPane() instanceof Updatable))
((Updatable)OpenImageFromURL.this.entrance.getPane()).updatePic();
OpenImageFromURL.this.dispose();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "URL is malformed.", null, -1);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "URL does not specify an image.", null, -1);
}
}
});
btnUpload.setBounds(236, 47, 89, 23);
getContentPane().add(btnUpload);
}
}
/* Location: C:\Users\Jordan\Downloads\ADIjava\AnalyzingDigitalImages.jar
* Qualified Name: org.gss.adi.dialogs.OpenImageFromURL
* JD-Core Version: 0.6.2
*/ | UTF-8 | Java | 3,755 | java | OpenImageFromURL.java | Java | [
{
"context": "ad);\r\n }\r\n }\r\n\r\n/* Location: C:\\Users\\Jordan\\Downloads\\ADIjava\\AnalyzingDigitalImages.jar\r\n * ",
"end": 3614,
"score": 0.9895663261413574,
"start": 3608,
"tag": "NAME",
"value": "Jordan"
}
] | null | [] | package org.gss.adi.dialogs;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.gss.adi.Entrance;
import org.gss.adi.Updatable;
public class OpenImageFromURL extends JDialog
{
private static final long serialVersionUID = 7441043699183274678L;
private JTextField textField;
private Entrance entrance;
public static final byte IMAGE = 0;
public static final byte TIME_SERIES1 = 1;
public static final byte TIME_SERIES2 = 2;
public static final byte TIME_SERIES3 = 3;
public OpenImageFromURL(Entrance e, final byte imgType)
{
setTitle("Upload an Image from a URL");
setBounds(100, 100, 450, 120);
getContentPane().setLayout(null);
setAlwaysOnTop(true);
this.entrance = e;
this.textField = new JTextField();
this.textField.setBounds(10, 16, 414, 20);
getContentPane().add(this.textField);
this.textField.setColumns(10);
JTextField txtUrl = new JTextField();
txtUrl.setOpaque(false);
txtUrl.setBorder(null);
txtUrl.setEditable(false);
txtUrl.setFont(new Font("SansSerif", 0, 10));
txtUrl.setText("URL");
txtUrl.setBounds(10, 0, 86, 15);
getContentPane().add(txtUrl);
txtUrl.setColumns(10);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
OpenImageFromURL.this.dispose();
}
});
btnCancel.setBounds(335, 47, 89, 23);
getContentPane().add(btnCancel);
JButton btnUpload = new JButton("Upload");
btnUpload.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
URL url = new URL(OpenImageFromURL.this.textField.getText());
BufferedImage img = ImageIO.read(url);
switch (imgType) {
case 0:
OpenImageFromURL.this.entrance.setImageTrim(img);
OpenImageFromURL.this.entrance.setTitle(url.toString());
break;
case 1:
OpenImageFromURL.this.entrance.setTimeSeries1(img);
OpenImageFromURL.this.entrance.setTitle1(url.toString());
break;
case 2:
OpenImageFromURL.this.entrance.setTimeSeries2(img);
OpenImageFromURL.this.entrance.setTitle2(url.toString());
break;
case 3:
OpenImageFromURL.this.entrance.setTimeSeries3(img);
OpenImageFromURL.this.entrance.setTitle3(url.toString());
}
if ((OpenImageFromURL.this.entrance.getPane() instanceof Updatable))
((Updatable)OpenImageFromURL.this.entrance.getPane()).updatePic();
OpenImageFromURL.this.dispose();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "URL is malformed.", null, -1);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "URL does not specify an image.", null, -1);
}
}
});
btnUpload.setBounds(236, 47, 89, 23);
getContentPane().add(btnUpload);
}
}
/* Location: C:\Users\Jordan\Downloads\ADIjava\AnalyzingDigitalImages.jar
* Qualified Name: org.gss.adi.dialogs.OpenImageFromURL
* JD-Core Version: 0.6.2
*/ | 3,755 | 0.642344 | 0.617044 | 102 | 34.823528 | 21.759115 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.892157 | false | false | 9 |
c6252af8d86fdcecbdef851e34a02faf1bfa04b9 | 22,351,009,852,005 | 1246b448cb66b6d06081c6c1d69c64cc4cdd9274 | /src/main/java/ru/bedward70/fitnesse/server/OneConnector.java | edac8ca44c0bc3c54f623d44b410c6ddb135fdc6 | [
"MIT"
] | permissive | bedward70/bedward70-fitnesse-io | https://github.com/bedward70/bedward70-fitnesse-io | 0958540d6bb857d062888268adce0aa38533973f | f71f19cf912358498e3b3da89091d4fae5a1c91f | refs/heads/master | 2023-08-01T03:27:58.713000 | 2023-07-10T07:21:58 | 2023-07-10T07:21:58 | 94,161,603 | 0 | 0 | MIT | false | 2023-07-10T07:21:59 | 2017-06-13T02:44:29 | 2022-01-07T03:56:20 | 2023-07-10T07:21:58 | 73 | 0 | 0 | 0 | Java | false | false | package ru.bedward70.fitnesse.server;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.thread.ExecutorThreadPool;
/**
* Created by ebalovnev on 13.07.17.
*/
public class OneConnector {
public static void main( String[] args ) throws Exception
{
// The Server
Server server = new Server(new ExecutorThreadPool());
// HTTP connector
ServerConnector http = new ServerConnector(server);
http.setHost("localhost");
http.setPort(8080);
http.setIdleTimeout(30000);
// Set the connector
server.addConnector(http);
// Set a handler
server.setHandler(new B70HelloHandler());
// Start the server
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("bb");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// server.start();
// while(true) {
// Thread.sleep(100L);
// }
//server.join();
Thread.sleep(10000L);
System.out.println("aa");
server.stop();
}
}
| UTF-8 | Java | 1,342 | java | OneConnector.java | Java | [
{
"context": "package ru.bedward70.fitnesse.server;\n\nimport org.eclipse.jetty.serve",
"end": 19,
"score": 0.710334300994873,
"start": 14,
"tag": "USERNAME",
"value": "ward7"
},
{
"context": "util.thread.ExecutorThreadPool;\n\n/**\n * Created by ebalovnev on 13.07.17.\n */\npublic c... | null | [] | package ru.bedward70.fitnesse.server;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.thread.ExecutorThreadPool;
/**
* Created by ebalovnev on 13.07.17.
*/
public class OneConnector {
public static void main( String[] args ) throws Exception
{
// The Server
Server server = new Server(new ExecutorThreadPool());
// HTTP connector
ServerConnector http = new ServerConnector(server);
http.setHost("localhost");
http.setPort(8080);
http.setIdleTimeout(30000);
// Set the connector
server.addConnector(http);
// Set a handler
server.setHandler(new B70HelloHandler());
// Start the server
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("bb");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// server.start();
// while(true) {
// Thread.sleep(100L);
// }
//server.join();
Thread.sleep(10000L);
System.out.println("aa");
server.stop();
}
}
| 1,342 | 0.536513 | 0.516393 | 53 | 24.320755 | 17.437515 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.415094 | false | false | 9 |
b929dc5234ff9b73f190ab15c457e766f70e21f2 | 7,713,761,312,231 | 1da7ca70b37da871aaf55a36f6d97815fdc91336 | /src/ServerForm.java | 36eaf2a4478177ae0cef5a977899d0e98eb13dc1 | [] | no_license | MitoroMisaka/OFICQ | https://github.com/MitoroMisaka/OFICQ | 16086fdec86dbe0b35259c38ab7ce6eddda810cb | 299326399058f3a352ceddf664712fdc2e821380 | refs/heads/master | 2023-06-13T02:35:46.245000 | 2021-07-09T10:45:30 | 2021-07-09T10:45:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import javax.swing.*;
import java.io.IOException;
public class ServerForm {
private int tabNum = 0;
JPanel root;
private JButton startButton;
private JTextField sayField;
private JButton sayButton;
private JTextField portTextField;
private JTabbedPane tabbedPane1;
private JTextArea privateChatArea;
private JTextArea textAreaOnline;
private JTextArea groupChatArea;
public ServerForm(final OFICQServer oficqServer) {
tabbedPane1.addChangeListener(e -> tabNum = tabbedPane1.getSelectedIndex());
startButton.addActionListener(e -> {
if (e.getSource() == startButton) {
try {
if (tabNum == 0) {
oficqServer.getClientsList().clear();
oficqServer.server = oficqServer.serverStart(portTextField.getText(), privateChatArea);
oficqServer.connectClient(privateChatArea,null);
} else if (tabNum == 1) {
oficqServer.clientsList.clear();
oficqServer.serverStart(portTextField.getText(), groupChatArea);
oficqServer.connectClient(groupChatArea, textAreaOnline);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
sayButton.addActionListener(e -> {
if (e.getSource() == sayButton) {
if (tabNum == 0){
oficqServer.sendData(sayField.getText(),0);
}
else if (tabNum == 1){
oficqServer.send2All(sayField.getText());
}
}
});
}
public static void main(String[] args) {
OFICQServer testServer = new OFICQServer();
JFrame frame = new JFrame("服务器");
frame.setContentPane(new ServerForm(testServer).root);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setVisible(true);
}
}
| UTF-8 | Java | 2,097 | java | ServerForm.java | Java | [] | null | [] | import javax.swing.*;
import java.io.IOException;
public class ServerForm {
private int tabNum = 0;
JPanel root;
private JButton startButton;
private JTextField sayField;
private JButton sayButton;
private JTextField portTextField;
private JTabbedPane tabbedPane1;
private JTextArea privateChatArea;
private JTextArea textAreaOnline;
private JTextArea groupChatArea;
public ServerForm(final OFICQServer oficqServer) {
tabbedPane1.addChangeListener(e -> tabNum = tabbedPane1.getSelectedIndex());
startButton.addActionListener(e -> {
if (e.getSource() == startButton) {
try {
if (tabNum == 0) {
oficqServer.getClientsList().clear();
oficqServer.server = oficqServer.serverStart(portTextField.getText(), privateChatArea);
oficqServer.connectClient(privateChatArea,null);
} else if (tabNum == 1) {
oficqServer.clientsList.clear();
oficqServer.serverStart(portTextField.getText(), groupChatArea);
oficqServer.connectClient(groupChatArea, textAreaOnline);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
sayButton.addActionListener(e -> {
if (e.getSource() == sayButton) {
if (tabNum == 0){
oficqServer.sendData(sayField.getText(),0);
}
else if (tabNum == 1){
oficqServer.send2All(sayField.getText());
}
}
});
}
public static void main(String[] args) {
OFICQServer testServer = new OFICQServer();
JFrame frame = new JFrame("服务器");
frame.setContentPane(new ServerForm(testServer).root);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setVisible(true);
}
}
| 2,097 | 0.564323 | 0.556671 | 58 | 35.034481 | 24.504023 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62069 | false | false | 9 |
977c3544850d441b051b24d76b5e5acd0496a872 | 25,967,372,309,719 | 7b5ca6c0d81311c13d9001d7e83e642965e0d4ae | /src/main/java/com/fyn/demo/reflexDemo/reflex.java | debbc3725fc54a475bc4d4d4a95847bbd03cc41a | [] | no_license | fengyuning/girl | https://github.com/fengyuning/girl | dd9800f71f95c929cfa7d159b0c817a5237fd4b0 | 7abf425cdb30d8a42141b7348335ff90e84e2c33 | refs/heads/master | 2018-07-20T12:38:38.075000 | 2018-06-02T03:05:48 | 2018-06-02T03:05:48 | 135,093,718 | 1 | 0 | null | false | 2018-06-02T03:02:59 | 2018-05-28T01:03:39 | 2018-06-02T01:28:04 | 2018-06-02T03:00:33 | 82 | 0 | 0 | 1 | Java | false | null | package com.fyn.demo.reflexDemo;
public class reflex {
public static void main(String[] args){
//Foo的实例对象 new就出来了
Foo foo = new Foo();
//Foo这个类也是一个实例对象 但是要怎么表示呢
//任何一个类都是Class的实例对象 有三种表示方式
//第一种----------实际证明,每个类都有一个隐含的静态成员变量class
Class c1 = Foo.class; //静态成员变量class
//第二种----------使用该类对象getClass
Class c2 = foo.getClass();
//第三种
Class c3 = null;
try {
c3 = Class.forName("com.fyn.demo.reflexDemo.Foo"); //动态加载
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/**
* c1,c2表示Foo类的类 类型(class type)
* 不管用什么方式获取,一个类只可能是Class类的一个对象
*/
System.out.println(c1 == c2); //true
//可以使用类 类型(c1 c2)创建该类对象
try {
Foo foo1 = (Foo)c3.newInstance(); //需要有无参数的构造方法
foo1.say();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
class Foo{
public void say(){
System.out.println("11");
}
} | UTF-8 | Java | 1,443 | java | reflex.java | Java | [] | null | [] | package com.fyn.demo.reflexDemo;
public class reflex {
public static void main(String[] args){
//Foo的实例对象 new就出来了
Foo foo = new Foo();
//Foo这个类也是一个实例对象 但是要怎么表示呢
//任何一个类都是Class的实例对象 有三种表示方式
//第一种----------实际证明,每个类都有一个隐含的静态成员变量class
Class c1 = Foo.class; //静态成员变量class
//第二种----------使用该类对象getClass
Class c2 = foo.getClass();
//第三种
Class c3 = null;
try {
c3 = Class.forName("com.fyn.demo.reflexDemo.Foo"); //动态加载
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/**
* c1,c2表示Foo类的类 类型(class type)
* 不管用什么方式获取,一个类只可能是Class类的一个对象
*/
System.out.println(c1 == c2); //true
//可以使用类 类型(c1 c2)创建该类对象
try {
Foo foo1 = (Foo)c3.newInstance(); //需要有无参数的构造方法
foo1.say();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
class Foo{
public void say(){
System.out.println("11");
}
} | 1,443 | 0.521286 | 0.508254 | 54 | 20.333334 | 18.652773 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false | 9 |
722c3d3796d9c5e1bdf045dbb5f2b6a8a0f8b363 | 14,980,845,979,602 | 7f836b2c71371eb176d6d71e04fea495953647d8 | /src/test/java/com/tdd/demotdd/TodoServiceTest.java | bf11c71bbaf6662ee165224ee391a87d2bfe5eae | [] | no_license | AmanuelChorito/demotdd | https://github.com/AmanuelChorito/demotdd | 20a7dd8bcfd42ec4711309b3afc4e75295f658cd | 779e8a00fc3fa3d32879045052a135a35fa745dd | refs/heads/master | 2023-08-17T06:31:12.905000 | 2021-09-20T16:45:04 | 2021-09-20T16:45:04 | 408,227,670 | 0 | 0 | null | false | 2021-09-20T13:01:10 | 2021-09-19T20:16:46 | 2021-09-19T20:16:55 | 2021-09-20T13:01:09 | 59 | 0 | 0 | 0 | Java | false | false | package com.tdd.demotdd;
import com.tdd.demotdd.domain.TodoItem;
import com.tdd.demotdd.repos.TodoRepository;
import com.tdd.demotdd.service.TodoService;
import com.tdd.demotdd.utils.TodoValidator;
import com.tdd.demotdd.domain.TaskStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class TodoServiceTest {
@Mock
private TodoValidator todoValidator;
@Mock
private TodoRepository todoRepository;
@InjectMocks
private TodoService todoService;
@Captor
ArgumentCaptor<TodoItem> todoItemArgumentCaptor;
TodoItem todoItem1,todoItem2;
@BeforeEach
void setUp() {
todoItem1 = new TodoItem(1,"code", LocalDate.now(), "coding intervew", TaskStatus.PENDING);
todoItem2 = new TodoItem(2,"learn", LocalDate.now(), "learning", TaskStatus.PENDING);
}
@Test
void itShouldAddNewTodoTask() throws IOException {
//action
when(todoRepository.save(todoItem1)).thenReturn(todoItem1);
//assert
assertEquals(todoService.save(todoItem1),todoItem1);
}
@Test
void getAllTasks(){
//assign
Page<TodoItem> todoItems= (Page<TodoItem>) Arrays.asList(todoItem1,todoItem2);
//action
org.springframework.data.domain.Pageable paging = PageRequest.of(1, 1);
when(todoRepository.findAll(paging)).thenReturn(todoItems);
//assert
assertEquals(todoService.findAll(paging),todoItems);
}
}
| UTF-8 | Java | 2,056 | java | TodoServiceTest.java | Java | [] | null | [] | package com.tdd.demotdd;
import com.tdd.demotdd.domain.TodoItem;
import com.tdd.demotdd.repos.TodoRepository;
import com.tdd.demotdd.service.TodoService;
import com.tdd.demotdd.utils.TodoValidator;
import com.tdd.demotdd.domain.TaskStatus;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class TodoServiceTest {
@Mock
private TodoValidator todoValidator;
@Mock
private TodoRepository todoRepository;
@InjectMocks
private TodoService todoService;
@Captor
ArgumentCaptor<TodoItem> todoItemArgumentCaptor;
TodoItem todoItem1,todoItem2;
@BeforeEach
void setUp() {
todoItem1 = new TodoItem(1,"code", LocalDate.now(), "coding intervew", TaskStatus.PENDING);
todoItem2 = new TodoItem(2,"learn", LocalDate.now(), "learning", TaskStatus.PENDING);
}
@Test
void itShouldAddNewTodoTask() throws IOException {
//action
when(todoRepository.save(todoItem1)).thenReturn(todoItem1);
//assert
assertEquals(todoService.save(todoItem1),todoItem1);
}
@Test
void getAllTasks(){
//assign
Page<TodoItem> todoItems= (Page<TodoItem>) Arrays.asList(todoItem1,todoItem2);
//action
org.springframework.data.domain.Pageable paging = PageRequest.of(1, 1);
when(todoRepository.findAll(paging)).thenReturn(todoItems);
//assert
assertEquals(todoService.findAll(paging),todoItems);
}
}
| 2,056 | 0.742218 | 0.735409 | 67 | 29.686567 | 25.285362 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.701493 | false | false | 9 |
59e5109961fd22501b3b99d087667e3cef010561 | 29,454,885,756,343 | c64e1313de06fb7a40c7d79caa0802c0ad9f0ee9 | /app/src/main/java/io/agora/chatdemo/settings/SettingsActivity.java | e8c5af53b1c2a7bc5bbb831dd0ebefdaa7033b9e | [
"MIT"
] | permissive | TianyaHelp/Hyphenate-Demo-Android | https://github.com/TianyaHelp/Hyphenate-Demo-Android | 35913b9f1e9c1873c9eea4d249d7fc2af6f35f7f | b65cf5e806fbedfa600283bab23fb6ab1968978b | refs/heads/master | 2023-07-27T14:59:13.704000 | 2021-08-26T05:19:19 | 2021-08-26T05:19:19 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.agora.chatdemo.settings;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.preference.PreferenceFragmentCompat;
import io.agora.chatdemo.Constant;
import io.agora.chatdemo.R;
import io.agora.chatdemo.ui.BaseInitActivity;
public class SettingsActivity extends BaseInitActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_activity_settings);
Intent intent = getIntent();
String type = intent.getStringExtra("type");
if(TextUtils.isEmpty(type)) {
finish();
return;
}
if(TextUtils.equals(type, Constant.SETTINGS_NOTIFICATION)) {
setTitle(getResources().getString(R.string.em_pref_notification));
showFragment(new NotificationSettingsPreference());
}else if(TextUtils.equals(type, Constant.SETTINGS_CHAT)) {
setTitle(getResources().getString(R.string.em_pref_chat_call));
showFragment(new ChatSettingsPreference());
}else {
finish();
return;
}
}
private void showFragment(PreferenceFragmentCompat fragment) {
if(fragment == null) {
finish();
return;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, fragment)
.commit();
}
private void setTitle(String title) {
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setTitle(title);
}
}
}
| UTF-8 | Java | 1,764 | java | SettingsActivity.java | Java | [] | null | [] | package io.agora.chatdemo.settings;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.preference.PreferenceFragmentCompat;
import io.agora.chatdemo.Constant;
import io.agora.chatdemo.R;
import io.agora.chatdemo.ui.BaseInitActivity;
public class SettingsActivity extends BaseInitActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.em_activity_settings);
Intent intent = getIntent();
String type = intent.getStringExtra("type");
if(TextUtils.isEmpty(type)) {
finish();
return;
}
if(TextUtils.equals(type, Constant.SETTINGS_NOTIFICATION)) {
setTitle(getResources().getString(R.string.em_pref_notification));
showFragment(new NotificationSettingsPreference());
}else if(TextUtils.equals(type, Constant.SETTINGS_CHAT)) {
setTitle(getResources().getString(R.string.em_pref_chat_call));
showFragment(new ChatSettingsPreference());
}else {
finish();
return;
}
}
private void showFragment(PreferenceFragmentCompat fragment) {
if(fragment == null) {
finish();
return;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, fragment)
.commit();
}
private void setTitle(String title) {
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setTitle(title);
}
}
}
| 1,764 | 0.641723 | 0.641723 | 57 | 29.929825 | 22.23547 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 9 |
43bd09221577fe3f6307b5651cf4ffa85f747c0e | 1,357,209,703,126 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/7/7_a2f3a5adb98f98ab9ce13528bb3326f6ca1783df/EditableImagePanel/7_a2f3a5adb98f98ab9ce13528bb3326f6ca1783df_EditableImagePanel_t.java | 8d4b92ad78ce7dd85a13dffd5035584c38ee79cc | [] | no_license | zhongxingyu/Seer | https://github.com/zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516000 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | false | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | 2023-06-21T00:53:27 | 2023-06-22T07:55:57 | 2,849,868 | 2 | 2 | 0 | null | false | false | package util;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Stack;
import javax.swing.JPanel;
import org.imgscalr.Scalr;
public class EditableImagePanel extends JPanel implements MouseListener,
MouseMotionListener {
/**
* The image to be used
*/
private BufferedImage image;
/**
* This determines what to draw on the image panel in the pain method
*/
private int editingMode;
/**
* Flag variable for cropping mode. True by default.
*/
private boolean isNewCropRect = true;
/**
* The start and end x,y coordinates of cropping rectangle being drawn on
* image for cropping
*/
private int cropx1, cropx2, cropy1, cropy2;
/**
* A cropped image
*/
private BufferedImage croppedImage;
/**
* Text for the top of the Meme
*/
private String topText;
/**
* Text for the bottom of the Meme
*/
private String bottomText;
/**
* The Font for the Meme
*/
private Font font;
/**
* The Font Size for the Meme
*/
private int fontSize;
/**
* The Font Color for the Meme
*/
private Color fontColor;
/**
* FontMetrics
*/
private FontMetrics fontMetrics;
/**
* When resizing image, use this to let the class decide how to constrain
* proportions
*/
public static final int RESIZE_CONSTRAIN_PROPORTIONS = 0;
/**
* When resizing image, use this to constrain proportions based on image
* width
*/
public static final int RESIZE_CONSTRAIN_WIDTH = 1;
/**
* When resizing image, use this to constrain proportions based on image
* height
*/
public static final int RESIZE_CONSTRAIN_HEIGHT = 2;
/**
* When resizing image, use this to resize width and height regardless of
* width/height ratio
*/
public static final int RESIZE_FIT_EXACT = 3;
/**
* Constant for normal image viewing mode
*/
public static final int MODE_VIEW = 0;
/**
* Constant for cropping mode
*/
public static final int MODE_CROP = 1;
/**
* Constant for adding/editing/deleting text
*/
public static final int MODE_TEXT = 2;
/**
* Default constructor
*/
public EditableImagePanel() {
setEditingMode(MODE_VIEW);
topText = "";
bottomText = "";
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Create a new image panel from an image object
*
* @param image
* The image object to be used
*/
public EditableImagePanel(BufferedImage image) {
this();
this.image = image;
}
/**
* Sets the editing mode of the panel
*
* @param editingMode
* The mode to be set
*/
public void setEditingMode(int editingMode) {
this.editingMode = editingMode;
repaint();
}
/**
* Returns the mode the image panel is in
*
* @return The editing mode the panel is in
*/
public int getEditingMode() {
return this.editingMode;
}
public void setImage(BufferedImage image) {
this.image = image;
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
repaint();
}
/**
* Returns the image being used for the panel
*
* @return Image object being used for panel
*/
public BufferedImage getImage() {
return image;
}
/**
* Return the width of the image
*
* @return Width in pixels
*/
public int getWidth() {
return image.getWidth();
}
/**
* Return the height of the image
*
* @return Height in pixels
*/
public int getHeight() {
return image.getHeight();
}
/**
* Override the JPanel's getPreferredSize() method to return the size of the
* image, not the JPanel
*/
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
/**
* This will paint stuff differently according to the mode
*
* @param g
* The graphics object
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the image
g.drawImage(image, 0, 0, null);
if (getEditingMode() == MODE_CROP) {
drawCropBox(g);
} else if (getEditingMode() == MODE_TEXT) {
drawTopTextOnImage(g);
drawBottomTextOnImage(g);
}
}
/**
* Draws the CropBox on image
* @param g
*/
private void drawCropBox(Graphics g) {
// get the actual width and height of the drawn rectangle
int width = getCropx1() - getCropx2();
int height = getCropy1() - getCropy2();
// get the width and height to use for drawing the rectangle
int w = Math.abs(width);
int h = Math.abs(height);
// get the coordinates for placing the rectangle
int x = width < 0 ? getCropx1() : getCropx2();
int y = height < 0 ? getCropy1() : getCropy2();
if (!this.isNewCropRect) {
// draw a rectangle to show the user the area
g.drawRect(x, y, w, h);
// create a cropped image
setCroppedImage(x, y, w, h);
}
}
/**
* Sets the cropped image
* @param x
* @param y
* @param width
* @param height
*/
private void setCroppedImage(int x, int y, int width, int height) {
if (width > 0 && height > 0) {
croppedImage = image.getSubimage(x, y, width, height);
} else {
croppedImage = image;
}
}
/**
*
* @return croppedImage
*/
public BufferedImage getCroppedImage() {
return croppedImage;
}
private void drawTopTextOnImage(Graphics g) {
//Graphics2D g2d = image.createGraphics();
g.setFont(font);
fontMetrics = g.getFontMetrics();
g.setColor(fontColor);
ArrayList<String> strings = (ArrayList<String>) StringUtils.wrap(topText, fontMetrics, image.getWidth());
int y = getTopFontPosY(fontMetrics);
if (strings.size()>1){
for(String line : strings){
int x = getFontPosX(fontMetrics, line);
g.drawString(line, x, y);
y = y + fontMetrics.getHeight();
}
} else {
int x = getFontPosX(fontMetrics, topText);
g.drawString(topText, x, y);
}
}
private void drawBottomTextOnImage(Graphics g) {
//Graphics2D g2d = image.createGraphics();
g.setFont(font);
fontMetrics = g.getFontMetrics();
g.setColor(fontColor);
ArrayList<String> strings = (ArrayList<String>) StringUtils.wrap(bottomText, fontMetrics, image.getWidth());
int y = getBottomFontPosY(fontMetrics);
if (strings.size()>1){
Stack<String> stack = new Stack<String>();
for(String line : strings){
stack.push(line);
}
while(!stack.isEmpty()){
String line = stack.pop();
int x = getFontPosX(fontMetrics, line);
g.drawString(line, x, y);
y = y - fontMetrics.getHeight();
}
} else {
int x = getFontPosX(fontMetrics, bottomText);
g.drawString(bottomText, x, y);
}
}
private int getTopFontPosY(FontMetrics fontMetrics) {
int topBuffer = (int) (image.getHeight() * .005);
int textHeight = fontMetrics.getHeight();
int yPos = topBuffer + textHeight;
return yPos;
}
private int getBottomFontPosY(FontMetrics fontMetrics) {
int yPos = (int) ((int) image.getHeight() - (image.getHeight() * .010) - fontMetrics.getDescent());
return yPos;
}
private int getFontPosX(FontMetrics fontMetrics, String text) {
int textWidth = fontMetrics.stringWidth(text);
int xPos = (image.getWidth() - textWidth) / 2;
return xPos;
}
/**
* @return the topText
*/
public String getTopText() {
return topText;
}
/**
* @param topText the topText to set
*/
public void setTopText(String topText) {
this.topText = topText;
}
/**
* @return the bottomText
*/
public String getBottomText() {
return bottomText;
}
/**
* @param bottomText the bottomText to set
*/
public void setBottomText(String bottomText) {
this.bottomText = bottomText;
}
/**
* @return the font
*/
public Font getFont() {
return font;
}
/**
* @param font the font to set
*/
public void setFont(Font font) {
this.font = font;
}
/**
* @return the fontColor
*/
public Color getFontColor() {
return fontColor;
}
/**
* @param fontColor the fontColor to set
*/
public void setFontColor(Color fontColor) {
this.fontColor = fontColor;
}
@Override
public void mouseDragged(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx2(e.getX());
setCropy2(e.getY());
isNewCropRect = false;
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
/* if (getEditingMode() == MODE_TEXT) {
repaint();
}*/
}
@Override
public void mouseEntered(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
} else if (getEditingMode() == MODE_TEXT) {
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
}
}
@Override
public void mouseExited(MouseEvent e) {
// set back to default when mouse outside image
setCursor(Cursor.getDefaultCursor());
}
@Override
public void mousePressed(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx1(e.getX());
setCropy1(e.getY());
isNewCropRect = true;
repaint();
} else if (getEditingMode() == MODE_TEXT) {
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx2(e.getX());
setCropy2(e.getY());
repaint();
} else if (getEditingMode() == MODE_TEXT) {
}
}
/**
* @return the cropx1
*/
public int getCropx1() {
return cropx1;
}
/**
* @param cropx1
* the cropx1 to set
*/
public void setCropx1(int cropx1) {
this.cropx1 = cropx1;
}
/**
* @return the cropx2
*/
public int getCropx2() {
return cropx2;
}
/**
* @param cropx2
* the cropx2 to set
*/
public void setCropx2(int cropx2) {
this.cropx2 = cropx2;
}
/**
* @return the cropy1
*/
public int getCropy1() {
return cropy1;
}
/**
* @param cropy1
* the cropy1 to set
*/
public void setCropy1(int cropy1) {
this.cropy1 = cropy1;
}
/**
* @return the cropy2
*/
public int getCropy2() {
return cropy2;
}
/**
* @param cropy2
* the cropy2 to set
*/
public void setCropy2(int cropy2) {
this.cropy2 = cropy2;
}
/**
* Returns a resized image
*
* @param width
* The new width in pixels
* @param height
* The new height in pixels
* @param resizeMode
* How to resize the image
* @return An Image
*/
public BufferedImage getResizedImage(int width, int height, int resizeMode) {
BufferedImage resizedImage = null;
if (resizeMode == RESIZE_CONSTRAIN_PROPORTIONS) {
resizedImage = Scalr.resize(image, width);
} else if (resizeMode == RESIZE_CONSTRAIN_WIDTH) {
resizedImage = Scalr.resize(image, Scalr.Mode.FIT_TO_WIDTH, width);
} else if (resizeMode == RESIZE_CONSTRAIN_HEIGHT) {
resizedImage = Scalr
.resize(image, Scalr.Mode.FIT_TO_HEIGHT, height);
} else if (resizeMode == RESIZE_FIT_EXACT) {
resizedImage = Scalr.resize(image, Scalr.Mode.FIT_EXACT, width,
height);
}
return resizedImage;
}
}
| UTF-8 | Java | 11,640 | java | 7_a2f3a5adb98f98ab9ce13528bb3326f6ca1783df_EditableImagePanel_t.java | Java | [] | null | [] | package util;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Stack;
import javax.swing.JPanel;
import org.imgscalr.Scalr;
public class EditableImagePanel extends JPanel implements MouseListener,
MouseMotionListener {
/**
* The image to be used
*/
private BufferedImage image;
/**
* This determines what to draw on the image panel in the pain method
*/
private int editingMode;
/**
* Flag variable for cropping mode. True by default.
*/
private boolean isNewCropRect = true;
/**
* The start and end x,y coordinates of cropping rectangle being drawn on
* image for cropping
*/
private int cropx1, cropx2, cropy1, cropy2;
/**
* A cropped image
*/
private BufferedImage croppedImage;
/**
* Text for the top of the Meme
*/
private String topText;
/**
* Text for the bottom of the Meme
*/
private String bottomText;
/**
* The Font for the Meme
*/
private Font font;
/**
* The Font Size for the Meme
*/
private int fontSize;
/**
* The Font Color for the Meme
*/
private Color fontColor;
/**
* FontMetrics
*/
private FontMetrics fontMetrics;
/**
* When resizing image, use this to let the class decide how to constrain
* proportions
*/
public static final int RESIZE_CONSTRAIN_PROPORTIONS = 0;
/**
* When resizing image, use this to constrain proportions based on image
* width
*/
public static final int RESIZE_CONSTRAIN_WIDTH = 1;
/**
* When resizing image, use this to constrain proportions based on image
* height
*/
public static final int RESIZE_CONSTRAIN_HEIGHT = 2;
/**
* When resizing image, use this to resize width and height regardless of
* width/height ratio
*/
public static final int RESIZE_FIT_EXACT = 3;
/**
* Constant for normal image viewing mode
*/
public static final int MODE_VIEW = 0;
/**
* Constant for cropping mode
*/
public static final int MODE_CROP = 1;
/**
* Constant for adding/editing/deleting text
*/
public static final int MODE_TEXT = 2;
/**
* Default constructor
*/
public EditableImagePanel() {
setEditingMode(MODE_VIEW);
topText = "";
bottomText = "";
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Create a new image panel from an image object
*
* @param image
* The image object to be used
*/
public EditableImagePanel(BufferedImage image) {
this();
this.image = image;
}
/**
* Sets the editing mode of the panel
*
* @param editingMode
* The mode to be set
*/
public void setEditingMode(int editingMode) {
this.editingMode = editingMode;
repaint();
}
/**
* Returns the mode the image panel is in
*
* @return The editing mode the panel is in
*/
public int getEditingMode() {
return this.editingMode;
}
public void setImage(BufferedImage image) {
this.image = image;
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
repaint();
}
/**
* Returns the image being used for the panel
*
* @return Image object being used for panel
*/
public BufferedImage getImage() {
return image;
}
/**
* Return the width of the image
*
* @return Width in pixels
*/
public int getWidth() {
return image.getWidth();
}
/**
* Return the height of the image
*
* @return Height in pixels
*/
public int getHeight() {
return image.getHeight();
}
/**
* Override the JPanel's getPreferredSize() method to return the size of the
* image, not the JPanel
*/
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
/**
* This will paint stuff differently according to the mode
*
* @param g
* The graphics object
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the image
g.drawImage(image, 0, 0, null);
if (getEditingMode() == MODE_CROP) {
drawCropBox(g);
} else if (getEditingMode() == MODE_TEXT) {
drawTopTextOnImage(g);
drawBottomTextOnImage(g);
}
}
/**
* Draws the CropBox on image
* @param g
*/
private void drawCropBox(Graphics g) {
// get the actual width and height of the drawn rectangle
int width = getCropx1() - getCropx2();
int height = getCropy1() - getCropy2();
// get the width and height to use for drawing the rectangle
int w = Math.abs(width);
int h = Math.abs(height);
// get the coordinates for placing the rectangle
int x = width < 0 ? getCropx1() : getCropx2();
int y = height < 0 ? getCropy1() : getCropy2();
if (!this.isNewCropRect) {
// draw a rectangle to show the user the area
g.drawRect(x, y, w, h);
// create a cropped image
setCroppedImage(x, y, w, h);
}
}
/**
* Sets the cropped image
* @param x
* @param y
* @param width
* @param height
*/
private void setCroppedImage(int x, int y, int width, int height) {
if (width > 0 && height > 0) {
croppedImage = image.getSubimage(x, y, width, height);
} else {
croppedImage = image;
}
}
/**
*
* @return croppedImage
*/
public BufferedImage getCroppedImage() {
return croppedImage;
}
private void drawTopTextOnImage(Graphics g) {
//Graphics2D g2d = image.createGraphics();
g.setFont(font);
fontMetrics = g.getFontMetrics();
g.setColor(fontColor);
ArrayList<String> strings = (ArrayList<String>) StringUtils.wrap(topText, fontMetrics, image.getWidth());
int y = getTopFontPosY(fontMetrics);
if (strings.size()>1){
for(String line : strings){
int x = getFontPosX(fontMetrics, line);
g.drawString(line, x, y);
y = y + fontMetrics.getHeight();
}
} else {
int x = getFontPosX(fontMetrics, topText);
g.drawString(topText, x, y);
}
}
private void drawBottomTextOnImage(Graphics g) {
//Graphics2D g2d = image.createGraphics();
g.setFont(font);
fontMetrics = g.getFontMetrics();
g.setColor(fontColor);
ArrayList<String> strings = (ArrayList<String>) StringUtils.wrap(bottomText, fontMetrics, image.getWidth());
int y = getBottomFontPosY(fontMetrics);
if (strings.size()>1){
Stack<String> stack = new Stack<String>();
for(String line : strings){
stack.push(line);
}
while(!stack.isEmpty()){
String line = stack.pop();
int x = getFontPosX(fontMetrics, line);
g.drawString(line, x, y);
y = y - fontMetrics.getHeight();
}
} else {
int x = getFontPosX(fontMetrics, bottomText);
g.drawString(bottomText, x, y);
}
}
private int getTopFontPosY(FontMetrics fontMetrics) {
int topBuffer = (int) (image.getHeight() * .005);
int textHeight = fontMetrics.getHeight();
int yPos = topBuffer + textHeight;
return yPos;
}
private int getBottomFontPosY(FontMetrics fontMetrics) {
int yPos = (int) ((int) image.getHeight() - (image.getHeight() * .010) - fontMetrics.getDescent());
return yPos;
}
private int getFontPosX(FontMetrics fontMetrics, String text) {
int textWidth = fontMetrics.stringWidth(text);
int xPos = (image.getWidth() - textWidth) / 2;
return xPos;
}
/**
* @return the topText
*/
public String getTopText() {
return topText;
}
/**
* @param topText the topText to set
*/
public void setTopText(String topText) {
this.topText = topText;
}
/**
* @return the bottomText
*/
public String getBottomText() {
return bottomText;
}
/**
* @param bottomText the bottomText to set
*/
public void setBottomText(String bottomText) {
this.bottomText = bottomText;
}
/**
* @return the font
*/
public Font getFont() {
return font;
}
/**
* @param font the font to set
*/
public void setFont(Font font) {
this.font = font;
}
/**
* @return the fontColor
*/
public Color getFontColor() {
return fontColor;
}
/**
* @param fontColor the fontColor to set
*/
public void setFontColor(Color fontColor) {
this.fontColor = fontColor;
}
@Override
public void mouseDragged(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx2(e.getX());
setCropy2(e.getY());
isNewCropRect = false;
repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
/* if (getEditingMode() == MODE_TEXT) {
repaint();
}*/
}
@Override
public void mouseEntered(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
} else if (getEditingMode() == MODE_TEXT) {
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
}
}
@Override
public void mouseExited(MouseEvent e) {
// set back to default when mouse outside image
setCursor(Cursor.getDefaultCursor());
}
@Override
public void mousePressed(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx1(e.getX());
setCropy1(e.getY());
isNewCropRect = true;
repaint();
} else if (getEditingMode() == MODE_TEXT) {
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (getEditingMode() == MODE_CROP) {
setCropx2(e.getX());
setCropy2(e.getY());
repaint();
} else if (getEditingMode() == MODE_TEXT) {
}
}
/**
* @return the cropx1
*/
public int getCropx1() {
return cropx1;
}
/**
* @param cropx1
* the cropx1 to set
*/
public void setCropx1(int cropx1) {
this.cropx1 = cropx1;
}
/**
* @return the cropx2
*/
public int getCropx2() {
return cropx2;
}
/**
* @param cropx2
* the cropx2 to set
*/
public void setCropx2(int cropx2) {
this.cropx2 = cropx2;
}
/**
* @return the cropy1
*/
public int getCropy1() {
return cropy1;
}
/**
* @param cropy1
* the cropy1 to set
*/
public void setCropy1(int cropy1) {
this.cropy1 = cropy1;
}
/**
* @return the cropy2
*/
public int getCropy2() {
return cropy2;
}
/**
* @param cropy2
* the cropy2 to set
*/
public void setCropy2(int cropy2) {
this.cropy2 = cropy2;
}
/**
* Returns a resized image
*
* @param width
* The new width in pixels
* @param height
* The new height in pixels
* @param resizeMode
* How to resize the image
* @return An Image
*/
public BufferedImage getResizedImage(int width, int height, int resizeMode) {
BufferedImage resizedImage = null;
if (resizeMode == RESIZE_CONSTRAIN_PROPORTIONS) {
resizedImage = Scalr.resize(image, width);
} else if (resizeMode == RESIZE_CONSTRAIN_WIDTH) {
resizedImage = Scalr.resize(image, Scalr.Mode.FIT_TO_WIDTH, width);
} else if (resizeMode == RESIZE_CONSTRAIN_HEIGHT) {
resizedImage = Scalr
.resize(image, Scalr.Mode.FIT_TO_HEIGHT, height);
} else if (resizeMode == RESIZE_FIT_EXACT) {
resizedImage = Scalr.resize(image, Scalr.Mode.FIT_EXACT, width,
height);
}
return resizedImage;
}
}
| 11,640 | 0.624914 | 0.618041 | 544 | 20.39522 | 19.709751 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.595588 | false | false | 9 |
0bb2482e292814ac48c96060c022ab30592fd4a4 | 20,117,626,881,803 | 7ce47605a889ede11dd058512bf6ede9beb513dd | /src/br/com/cetip/aplicacao/garantias/negocio/ContratosCesta.java | 46c2ba9dd5fb7864ac81d351ce38a9965c232525 | [] | no_license | codetime66/guarantee | https://github.com/codetime66/guarantee | ecf50b8c64ea765dfd8f4afe8543b216acaa8297 | dd472059b0f3e51f3dc7093d50b57ce045e139cf | refs/heads/master | 2020-03-11T22:27:46.379000 | 2018-04-20T01:43:47 | 2018-04-20T01:43:47 | 130,292,861 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.cetip.aplicacao.garantias.negocio;
import java.util.List;
import br.com.cetip.aplicacao.garantias.apinegocio.IContratosCesta;
import br.com.cetip.aplicacao.garantias.apinegocio.VinculacaoContratoVO;
import br.com.cetip.aplicacao.instrumentofinanceiro.apinegocio.sec.ComitenteFactory;
import br.com.cetip.aplicacao.instrumentofinanceiro.apinegocio.sec.IComitente;
import br.com.cetip.aplicacao.instrumentofinanceiro.servico.swap.RequisicaoServicoVinculaCestaContrato;
import br.com.cetip.dados.aplicacao.garantias.CestaGarantiasDO;
import br.com.cetip.dados.aplicacao.garantias.ContratoCestaGarantiaDO;
import br.com.cetip.dados.aplicacao.instrumentofinanceiro.ComplementoContratoDO;
import br.com.cetip.dados.aplicacao.instrumentofinanceiro.ParametroPontaDO;
import br.com.cetip.dados.aplicacao.sap.ComitenteDO;
import br.com.cetip.dados.aplicacao.sap.ContaParticipanteDO;
import br.com.cetip.infra.atributo.CodigoErro;
import br.com.cetip.infra.atributo.Contexto;
import br.com.cetip.infra.atributo.Erro;
import br.com.cetip.infra.atributo.tipo.expressao.Booleano;
import br.com.cetip.infra.atributo.tipo.identificador.CPFOuCNPJ;
import br.com.cetip.infra.atributo.tipo.identificador.CodigoIF;
import br.com.cetip.infra.atributo.tipo.identificador.CodigoIFContrato;
import br.com.cetip.infra.atributo.tipo.identificador.Id;
import br.com.cetip.infra.atributo.tipo.texto.Texto;
import br.com.cetip.infra.atributo.utilitario.Condicional;
import br.com.cetip.infra.log.Logger;
import br.com.cetip.infra.persistencia.IConsulta;
import br.com.cetip.infra.persistencia.IGerenciadorPersistencia;
import br.com.cetip.infra.servico.interfaces.Requisicao;
final class ContratosCesta extends BaseGarantias implements IContratosCesta {
public ContratoCestaGarantiaDO obterVinculoContrato(CodigoIF contrato) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.contrato.codigoIF = ?";
List contratos = gp.find(hql, new Object[] { contrato });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public ContratoCestaGarantiaDO obterVinculoContrato(CestaGarantiasDO cesta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.cestaParte = ? or cc.cestaContraparte = ?";
List contratos = gp.find(hql, new Object[] { cesta, cesta });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public void desvinculaPontaCesta(CestaGarantiasDO cesta) {
ParametroPontaDO ponta = cesta.getParametroPonta();
ponta.setPossuiCestaGarantia(new Booleano(Booleano.FALSO));
}
public CestaGarantiasDO obterCestaPorPonta(Id idParametroPonta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from CestaGarantiasDO cg where cg.parametroPonta.idParametroPonta = ?";
List cesta = gp.find(hql, new Object[] { idParametroPonta });
if (!cesta.isEmpty()) {
return (CestaGarantiasDO) cesta.get(0);
}
return null;
}
public ContratoCestaGarantiaDO obterVinculoContrato(ComplementoContratoDO contrato) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.contrato.codigoIF = ?";
List contratos = gp.find(hql, new Object[] { contrato.getCodigoIF() });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public CestaGarantiasDO obterCestaPorPonta(ParametroPontaDO ponta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from CestaGarantiasDO cg where cg.parametroPonta.idParametroPonta = ?";
List cesta = gp.find(hql, new Object[] { ponta.getIdParametroPonta() });
if (!cesta.isEmpty()) {
return (CestaGarantiasDO) cesta.get(0);
}
return null;
}
public ParametroPontaDO[] obterPontas(ComplementoContratoDO contrato) {
String hql = "from ParametroPontaDO p where p.contrato = ?";
List l = getGp().find(hql, contrato);
ParametroPontaDO[] pontas = (ParametroPontaDO[]) l.toArray(new ParametroPontaDO[l.size()]);
return pontas;
}
public ParametroPontaDO obterPonta(ComplementoContratoDO contrato, ContaParticipanteDO conta, CPFOuCNPJ cpfCnpj) {
if (conta.getCodContaParticipante().ehContaCliente()) {
ComitenteDO comitente = null;
try {
IComitente cDao = ComitenteFactory.getInstance();
comitente = cDao.obterComitente(cpfCnpj, cpfCnpj.obterNatureza(), conta.getCodContaParticipante());
} catch (Exception e) {
Logger.error(this, e);
throw new Erro(CodigoErro.ERRO, "SIC: " + e.getMessage());
}
StringBuffer hql = new StringBuffer();
hql.append(" select ppc.parametroPonta ");
hql.append(" from ParametroPontaComitenteDO ppc ");
hql.append(" where ppc.comitente = :comitente and ppc.parametroPonta.contrato = :contrato ");
hql.append(" and ppc.parametroPonta.contaParticipante = :conta ");
IConsulta c = getGp().criarConsulta(hql.toString());
c.setAtributo("comitente", comitente);
c.setAtributo("contrato", contrato);
c.setAtributo("conta", conta);
List l = c.list();
if (l.size() != 1) {
Erro erro = new Erro(CodigoErro.ERRO);
erro.parametroMensagem("Contrato de conta cliente sem comitente.", 0);
throw erro;
}
return (ParametroPontaDO) l.get(0);
}
StringBuffer hql = new StringBuffer();
hql.append(" select pp ");
hql.append(" from ParametroPontaDO pp ");
hql.append(" where pp.contrato = :contrato ");
hql.append(" and pp.contaParticipante = :conta ");
IConsulta c = getGp().criarConsulta(hql.toString());
c.setAtributo("contrato", contrato);
c.setAtributo("conta", conta);
List l = c.list();
if (l.size() != 1) {
Erro erro = new Erro(CodigoErro.ERRO);
erro.parametroMensagem("Parametro ponta nao encontrado.", 0);
throw erro;
}
return (ParametroPontaDO) l.get(0);
}
public ComplementoContratoDO obterContrato(CodigoIF codigoIF) {
String hql = "select c from ComplementoContratoDO c where c.codigoIF = ? and c.dataHoraExclusao is null";
List l = getGp().find(hql, codigoIF);
if (l.isEmpty()) {
throw new Erro(CodigoErro.INSTRUMENTO_FINANCEIRO_INEXISTENTE);
}
return (ComplementoContratoDO) l.get(0);
}
public Requisicao construirRequisicaoSwap(VinculacaoContratoVO vc) {
RequisicaoServicoVinculaCestaContrato r = new RequisicaoServicoVinculaCestaContrato();
// PARTE
Id idCestaParte = null;
if (!Condicional.vazio(vc.cestaParte)) {
idCestaParte = vc.cestaParte.getNumIdCestaGarantias();
}
r.atribuirPARTE_CPFOuCNPJ(vc.comitenteParte);
r.atribuirPARTE_CodigoContaCetip(vc.contaParte.getCodContaParticipante());
r.atribuirPARTE_Id(idCestaParte);
// CONTRA-PARTE
Id idCestaContraparte = null;
if (!Condicional.vazio(vc.cestaContraparte)) {
idCestaContraparte = vc.cestaContraparte.getNumIdCestaGarantias();
}
r.atribuirCONTRA_PARTE_CPFOuCNPJ(vc.comitenteContraParte);
r.atribuirCONTRA_PARTE_CodigoContaCetip(vc.contaContraparte.getCodContaParticipante());
r.atribuirCONTRA_PARTE_Id(idCestaContraparte);
// CONTRATO
CodigoIFContrato codigoIFContrato = new CodigoIFContrato(vc.ativo.getCodigoIF().obterConteudo());
r.atribuirINSTRUMENTO_FINANCEIRO_CodigoIFContrato(codigoIFContrato);
Booleano reset = null;
Texto regra = new Texto(Contexto.RESET, vc.regraLiberacao.obterConteudo());
if (regra.mesmoConteudo(IContratosCesta.AJUSTES_EVENTO_VENC)) {
reset = Booleano.VERDADEIRO;
} else if (regra.mesmoConteudo(IContratosCesta.EVENTOS_VENCIMENTO)) {
reset = Booleano.FALSO;
}
r.atribuirRESET_Booleano(reset);
return r;
}
public CestaGarantiasDO obterCestaVinculadaPonta(Id idPonta) {
CestaGarantiasDO cesta = obterCestaPorPonta(idPonta);
if (cesta != null && (cesta.getStatusCesta().isVinculada() || cesta.getStatusCesta().isInadimplente())) {
return cesta;
}
return null;
}
}
| UTF-8 | Java | 8,707 | java | ContratosCesta.java | Java | [] | null | [] | package br.com.cetip.aplicacao.garantias.negocio;
import java.util.List;
import br.com.cetip.aplicacao.garantias.apinegocio.IContratosCesta;
import br.com.cetip.aplicacao.garantias.apinegocio.VinculacaoContratoVO;
import br.com.cetip.aplicacao.instrumentofinanceiro.apinegocio.sec.ComitenteFactory;
import br.com.cetip.aplicacao.instrumentofinanceiro.apinegocio.sec.IComitente;
import br.com.cetip.aplicacao.instrumentofinanceiro.servico.swap.RequisicaoServicoVinculaCestaContrato;
import br.com.cetip.dados.aplicacao.garantias.CestaGarantiasDO;
import br.com.cetip.dados.aplicacao.garantias.ContratoCestaGarantiaDO;
import br.com.cetip.dados.aplicacao.instrumentofinanceiro.ComplementoContratoDO;
import br.com.cetip.dados.aplicacao.instrumentofinanceiro.ParametroPontaDO;
import br.com.cetip.dados.aplicacao.sap.ComitenteDO;
import br.com.cetip.dados.aplicacao.sap.ContaParticipanteDO;
import br.com.cetip.infra.atributo.CodigoErro;
import br.com.cetip.infra.atributo.Contexto;
import br.com.cetip.infra.atributo.Erro;
import br.com.cetip.infra.atributo.tipo.expressao.Booleano;
import br.com.cetip.infra.atributo.tipo.identificador.CPFOuCNPJ;
import br.com.cetip.infra.atributo.tipo.identificador.CodigoIF;
import br.com.cetip.infra.atributo.tipo.identificador.CodigoIFContrato;
import br.com.cetip.infra.atributo.tipo.identificador.Id;
import br.com.cetip.infra.atributo.tipo.texto.Texto;
import br.com.cetip.infra.atributo.utilitario.Condicional;
import br.com.cetip.infra.log.Logger;
import br.com.cetip.infra.persistencia.IConsulta;
import br.com.cetip.infra.persistencia.IGerenciadorPersistencia;
import br.com.cetip.infra.servico.interfaces.Requisicao;
final class ContratosCesta extends BaseGarantias implements IContratosCesta {
public ContratoCestaGarantiaDO obterVinculoContrato(CodigoIF contrato) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.contrato.codigoIF = ?";
List contratos = gp.find(hql, new Object[] { contrato });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public ContratoCestaGarantiaDO obterVinculoContrato(CestaGarantiasDO cesta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.cestaParte = ? or cc.cestaContraparte = ?";
List contratos = gp.find(hql, new Object[] { cesta, cesta });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public void desvinculaPontaCesta(CestaGarantiasDO cesta) {
ParametroPontaDO ponta = cesta.getParametroPonta();
ponta.setPossuiCestaGarantia(new Booleano(Booleano.FALSO));
}
public CestaGarantiasDO obterCestaPorPonta(Id idParametroPonta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from CestaGarantiasDO cg where cg.parametroPonta.idParametroPonta = ?";
List cesta = gp.find(hql, new Object[] { idParametroPonta });
if (!cesta.isEmpty()) {
return (CestaGarantiasDO) cesta.get(0);
}
return null;
}
public ContratoCestaGarantiaDO obterVinculoContrato(ComplementoContratoDO contrato) {
IGerenciadorPersistencia gp = getGp();
String hql = "from ContratoCestaGarantiaDO cc where cc.contrato.codigoIF = ?";
List contratos = gp.find(hql, new Object[] { contrato.getCodigoIF() });
if (!contratos.isEmpty()) {
return (ContratoCestaGarantiaDO) contratos.get(0);
}
return null;
}
public CestaGarantiasDO obterCestaPorPonta(ParametroPontaDO ponta) {
IGerenciadorPersistencia gp = getGp();
String hql = "from CestaGarantiasDO cg where cg.parametroPonta.idParametroPonta = ?";
List cesta = gp.find(hql, new Object[] { ponta.getIdParametroPonta() });
if (!cesta.isEmpty()) {
return (CestaGarantiasDO) cesta.get(0);
}
return null;
}
public ParametroPontaDO[] obterPontas(ComplementoContratoDO contrato) {
String hql = "from ParametroPontaDO p where p.contrato = ?";
List l = getGp().find(hql, contrato);
ParametroPontaDO[] pontas = (ParametroPontaDO[]) l.toArray(new ParametroPontaDO[l.size()]);
return pontas;
}
public ParametroPontaDO obterPonta(ComplementoContratoDO contrato, ContaParticipanteDO conta, CPFOuCNPJ cpfCnpj) {
if (conta.getCodContaParticipante().ehContaCliente()) {
ComitenteDO comitente = null;
try {
IComitente cDao = ComitenteFactory.getInstance();
comitente = cDao.obterComitente(cpfCnpj, cpfCnpj.obterNatureza(), conta.getCodContaParticipante());
} catch (Exception e) {
Logger.error(this, e);
throw new Erro(CodigoErro.ERRO, "SIC: " + e.getMessage());
}
StringBuffer hql = new StringBuffer();
hql.append(" select ppc.parametroPonta ");
hql.append(" from ParametroPontaComitenteDO ppc ");
hql.append(" where ppc.comitente = :comitente and ppc.parametroPonta.contrato = :contrato ");
hql.append(" and ppc.parametroPonta.contaParticipante = :conta ");
IConsulta c = getGp().criarConsulta(hql.toString());
c.setAtributo("comitente", comitente);
c.setAtributo("contrato", contrato);
c.setAtributo("conta", conta);
List l = c.list();
if (l.size() != 1) {
Erro erro = new Erro(CodigoErro.ERRO);
erro.parametroMensagem("Contrato de conta cliente sem comitente.", 0);
throw erro;
}
return (ParametroPontaDO) l.get(0);
}
StringBuffer hql = new StringBuffer();
hql.append(" select pp ");
hql.append(" from ParametroPontaDO pp ");
hql.append(" where pp.contrato = :contrato ");
hql.append(" and pp.contaParticipante = :conta ");
IConsulta c = getGp().criarConsulta(hql.toString());
c.setAtributo("contrato", contrato);
c.setAtributo("conta", conta);
List l = c.list();
if (l.size() != 1) {
Erro erro = new Erro(CodigoErro.ERRO);
erro.parametroMensagem("Parametro ponta nao encontrado.", 0);
throw erro;
}
return (ParametroPontaDO) l.get(0);
}
public ComplementoContratoDO obterContrato(CodigoIF codigoIF) {
String hql = "select c from ComplementoContratoDO c where c.codigoIF = ? and c.dataHoraExclusao is null";
List l = getGp().find(hql, codigoIF);
if (l.isEmpty()) {
throw new Erro(CodigoErro.INSTRUMENTO_FINANCEIRO_INEXISTENTE);
}
return (ComplementoContratoDO) l.get(0);
}
public Requisicao construirRequisicaoSwap(VinculacaoContratoVO vc) {
RequisicaoServicoVinculaCestaContrato r = new RequisicaoServicoVinculaCestaContrato();
// PARTE
Id idCestaParte = null;
if (!Condicional.vazio(vc.cestaParte)) {
idCestaParte = vc.cestaParte.getNumIdCestaGarantias();
}
r.atribuirPARTE_CPFOuCNPJ(vc.comitenteParte);
r.atribuirPARTE_CodigoContaCetip(vc.contaParte.getCodContaParticipante());
r.atribuirPARTE_Id(idCestaParte);
// CONTRA-PARTE
Id idCestaContraparte = null;
if (!Condicional.vazio(vc.cestaContraparte)) {
idCestaContraparte = vc.cestaContraparte.getNumIdCestaGarantias();
}
r.atribuirCONTRA_PARTE_CPFOuCNPJ(vc.comitenteContraParte);
r.atribuirCONTRA_PARTE_CodigoContaCetip(vc.contaContraparte.getCodContaParticipante());
r.atribuirCONTRA_PARTE_Id(idCestaContraparte);
// CONTRATO
CodigoIFContrato codigoIFContrato = new CodigoIFContrato(vc.ativo.getCodigoIF().obterConteudo());
r.atribuirINSTRUMENTO_FINANCEIRO_CodigoIFContrato(codigoIFContrato);
Booleano reset = null;
Texto regra = new Texto(Contexto.RESET, vc.regraLiberacao.obterConteudo());
if (regra.mesmoConteudo(IContratosCesta.AJUSTES_EVENTO_VENC)) {
reset = Booleano.VERDADEIRO;
} else if (regra.mesmoConteudo(IContratosCesta.EVENTOS_VENCIMENTO)) {
reset = Booleano.FALSO;
}
r.atribuirRESET_Booleano(reset);
return r;
}
public CestaGarantiasDO obterCestaVinculadaPonta(Id idPonta) {
CestaGarantiasDO cesta = obterCestaPorPonta(idPonta);
if (cesta != null && (cesta.getStatusCesta().isVinculada() || cesta.getStatusCesta().isInadimplente())) {
return cesta;
}
return null;
}
}
| 8,707 | 0.684736 | 0.683358 | 219 | 37.757992 | 31.671846 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.639269 | false | false | 9 |
f690cea9167d55050126633948aaf77f45f38f17 | 15,333,033,279,573 | a84a54a81cee28c16dc6cd3d6fc44943ee09a76c | /app/src/main/java/com/zncg/lavie/network/DeviceApi.java | 284a4ea0150ab3a30f6bfaae6892bea6afe3a323 | [
"Apache-2.0"
] | permissive | GFZkkk/MVP | https://github.com/GFZkkk/MVP | b2c1a58150fc495562c816cc07e66f4cca27a39f | 610e387e538c6c6175f62e8650a18737df0d0980 | refs/heads/master | 2020-04-17T20:36:41.028000 | 2019-12-17T06:39:04 | 2019-12-17T06:39:04 | 166,913,254 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zncg.lavie.network;
import com.zncg.lavie.model.bean.DeviceList;
import com.zncg.lavie.base.bean.ResultBean;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
/**
* Created by gaofengze on 2019/1/12
*/
public interface DeviceApi {
@GET("api-device-control/api/v1/app/device/all")
Observable<ResultBean<DeviceList>> getDevice(@Header("Authorization") String token);
@POST("api-device-control/api/v1/app/device/control")
Observable<ResultBean<Object>> control(@Header("Authorization") String token, @Body Map<String,String> map);
}
| UTF-8 | Java | 682 | java | DeviceApi.java | Java | [
{
"context": "er;\nimport retrofit2.http.POST;\n\n/**\n * Created by gaofengze on 2019/1/12\n */\npublic interface DeviceApi {\n ",
"end": 319,
"score": 0.9994745254516602,
"start": 310,
"tag": "USERNAME",
"value": "gaofengze"
}
] | null | [] | package com.zncg.lavie.network;
import com.zncg.lavie.model.bean.DeviceList;
import com.zncg.lavie.base.bean.ResultBean;
import java.util.Map;
import io.reactivex.Observable;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
/**
* Created by gaofengze on 2019/1/12
*/
public interface DeviceApi {
@GET("api-device-control/api/v1/app/device/all")
Observable<ResultBean<DeviceList>> getDevice(@Header("Authorization") String token);
@POST("api-device-control/api/v1/app/device/control")
Observable<ResultBean<Object>> control(@Header("Authorization") String token, @Body Map<String,String> map);
}
| 682 | 0.759531 | 0.740469 | 23 | 28.652174 | 28.423212 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 9 |
04f8d84307e0178dbc21e3122a8b6f106b499f99 | 15,169,824,518,018 | df0ba07c062a3ee3e5804fb57aef1bdfc986d317 | /jdbc/dhcp/UserDao.java | 2eceb7f6afaf029d676e05d9c28a0f4fd77eb740 | [] | no_license | fate-7/MySpringLearning | https://github.com/fate-7/MySpringLearning | 42e603722ad6aa95416d326ac16f65e8d30b0013 | 55fc13f6e1bb75584f68e8cf8df160da1c77a6e4 | refs/heads/master | 2020-05-24T01:28:39.106000 | 2019-05-16T13:43:09 | 2019-05-16T13:43:09 | 187,035,600 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rj.spring.jdbc.dhcp;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void update(){
jdbcTemplate.update("insert into t_user(username,password) values(?,?);", "tom", "998");
//
}
}
| UTF-8 | Java | 402 | java | UserDao.java | Java | [
{
"context": "rt into t_user(username,password) values(?,?);\", \"tom\", \"998\");\n //\n }\n}\n",
"end": 372,
"score": 0.9901862144470215,
"start": 369,
"tag": "USERNAME",
"value": "tom"
},
{
"context": " t_user(username,password) values(?,?);\", \"tom\", \"998\");\n ... | null | [] | package com.rj.spring.jdbc.dhcp;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void update(){
jdbcTemplate.update("insert into t_user(username,password) values(?,?);", "tom", "998");
//
}
}
| 402 | 0.679105 | 0.671642 | 17 | 22.647058 | 26.574957 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 9 |
0d4f4e8a069965c6a900f876a0b682e162917beb | 13,778,255,109,521 | 7a9014d643199747f8a65c1a1990e656fbe5b852 | /src/madlib/MadLib.java | 92ecb90e11428a2ad0b1763792ab8b75d8e9d4e6 | [] | no_license | etwat3497/madLib | https://github.com/etwat3497/madLib | a74c0979b84d65aac413af6265246ae00e4d6168 | 89f1e69943dfb2953067a6577a918a30184b7a77 | refs/heads/master | 2020-07-26T04:39:49.265000 | 2016-11-17T00:50:14 | 2016-11-17T00:50:14 | 73,734,548 | 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 madlib;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author etwat3497
*/
public class MadLib {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File verbFile = new File("verbs.txt");
File nounFile = new File("nouns.txt");
File textFile = new File("story.txt");
FileReader in;
BufferedReader readFile;
String newText = "";
final String nounPlaceholder, verbPlaceholder;
nounPlaceholder = "#";
verbPlaceholder = "%";
int i=0;
ArrayList<String> verbs = new ArrayList();
ArrayList<String> nouns = new ArrayList();
ArrayList<String> text = new ArrayList();
Random rand = new Random();
try{
//Read the verb file
in = new FileReader(verbFile);
readFile = new BufferedReader(in);
//Do while loop to fill the verbs arraylist with the verb values
do{
//Add the element on each line into the verbs arraylist
verbs.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(verbs.get(i-1) != null);
//The last element in the arraylist is null so remove that element
verbs.remove(i-1);
//Read the noun file
in = new FileReader(nounFile);
readFile = new BufferedReader(in);
//Do while loop to fill the nouns arraylist with the noun values
i=0;
do{
//Add the element on each line into the nouns arraylist
nouns.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(nouns.get(i-1) != null);
//The last element in the arraylist is null so remove that element
nouns.remove(i-1);
//Read the text file
in = new FileReader(textFile);
readFile = new BufferedReader(in);
//Do while loop to fill the text arraylist with the verb values
i=0;
do{
//Add the element on each line into the text arraylist
text.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(text.get(i-1) != null);
//The last element in the arraylist is null so remove that element
text.remove(i-1);
//For loop run for the size of the text arraylist
for(int j=0;j<text.size();j++){
//Set a temporary string at the index of j
newText = text.get(j);
//Determine how many nouns are in the temporary string
int nounCounter = 0;
for( int k=0; k<newText.length(); k++ ) {
if(newText.charAt(k) == '#') {
nounCounter++;
}
}
//Determine how many verbs are in the temporary string
int verbCounter = 0;
for( int k=0; k<newText.length(); k++ ) {
if(newText.charAt(k) == '%') {
verbCounter++;
}
}
//In this temporary string replace all the noun and verb placeholders with random nouns and verbs
for(int k=0;k<nounCounter;k++){
//Set random numbers based on the size of the noun arraylist
int randomNoun = rand.nextInt(nouns.size());
//Replace the first noun placeholder available with a random noun
newText = newText.replaceFirst(nounPlaceholder, nouns.get(randomNoun));
}
for(int k=0;k<nounCounter;k++){
//Set random numbers based on the size of the verb arraylist
int randomVerb = rand.nextInt(verbs.size());
//Replace the first verb placeholder available with a random verb
newText = newText.replaceFirst(verbPlaceholder, verbs.get(randomVerb));
}
//Set the temporary string as the new element at the index j
text.set(j,newText);
}
//Print the modified arraylist
for(int k=0;k<text.size();k++){
System.out.println(text.get(k));
}
//Close the buffered reader and file reader
readFile.close();
in.close();
}
//Catch a file not found exception and print the error message
catch(FileNotFoundException e){
System.out.println("File does not exist or could not be found.");
System.err.println("IOException: "+e.getMessage());
}
//Catch an io exception and print the error message
catch(IOException e){
System.out.println("Problem reading file.");
System.err.println("IOException: "+e.getMessage());
}
}
}
| UTF-8 | Java | 5,931 | java | MadLib.java | Java | [
{
"context": "m;\r\nimport java.util.Scanner;\r\n/**\r\n *\r\n * @author etwat3497\r\n */\r\npublic class MadLib {\r\n\r\n /**\r\n * @p",
"end": 341,
"score": 0.9996483325958252,
"start": 332,
"tag": "USERNAME",
"value": "etwat3497"
}
] | 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 madlib;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
/**
*
* @author etwat3497
*/
public class MadLib {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
File verbFile = new File("verbs.txt");
File nounFile = new File("nouns.txt");
File textFile = new File("story.txt");
FileReader in;
BufferedReader readFile;
String newText = "";
final String nounPlaceholder, verbPlaceholder;
nounPlaceholder = "#";
verbPlaceholder = "%";
int i=0;
ArrayList<String> verbs = new ArrayList();
ArrayList<String> nouns = new ArrayList();
ArrayList<String> text = new ArrayList();
Random rand = new Random();
try{
//Read the verb file
in = new FileReader(verbFile);
readFile = new BufferedReader(in);
//Do while loop to fill the verbs arraylist with the verb values
do{
//Add the element on each line into the verbs arraylist
verbs.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(verbs.get(i-1) != null);
//The last element in the arraylist is null so remove that element
verbs.remove(i-1);
//Read the noun file
in = new FileReader(nounFile);
readFile = new BufferedReader(in);
//Do while loop to fill the nouns arraylist with the noun values
i=0;
do{
//Add the element on each line into the nouns arraylist
nouns.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(nouns.get(i-1) != null);
//The last element in the arraylist is null so remove that element
nouns.remove(i-1);
//Read the text file
in = new FileReader(textFile);
readFile = new BufferedReader(in);
//Do while loop to fill the text arraylist with the verb values
i=0;
do{
//Add the element on each line into the text arraylist
text.add(i,readFile.readLine());
i++;
}
//Stop the do-while when the last element in the array is null
while(text.get(i-1) != null);
//The last element in the arraylist is null so remove that element
text.remove(i-1);
//For loop run for the size of the text arraylist
for(int j=0;j<text.size();j++){
//Set a temporary string at the index of j
newText = text.get(j);
//Determine how many nouns are in the temporary string
int nounCounter = 0;
for( int k=0; k<newText.length(); k++ ) {
if(newText.charAt(k) == '#') {
nounCounter++;
}
}
//Determine how many verbs are in the temporary string
int verbCounter = 0;
for( int k=0; k<newText.length(); k++ ) {
if(newText.charAt(k) == '%') {
verbCounter++;
}
}
//In this temporary string replace all the noun and verb placeholders with random nouns and verbs
for(int k=0;k<nounCounter;k++){
//Set random numbers based on the size of the noun arraylist
int randomNoun = rand.nextInt(nouns.size());
//Replace the first noun placeholder available with a random noun
newText = newText.replaceFirst(nounPlaceholder, nouns.get(randomNoun));
}
for(int k=0;k<nounCounter;k++){
//Set random numbers based on the size of the verb arraylist
int randomVerb = rand.nextInt(verbs.size());
//Replace the first verb placeholder available with a random verb
newText = newText.replaceFirst(verbPlaceholder, verbs.get(randomVerb));
}
//Set the temporary string as the new element at the index j
text.set(j,newText);
}
//Print the modified arraylist
for(int k=0;k<text.size();k++){
System.out.println(text.get(k));
}
//Close the buffered reader and file reader
readFile.close();
in.close();
}
//Catch a file not found exception and print the error message
catch(FileNotFoundException e){
System.out.println("File does not exist or could not be found.");
System.err.println("IOException: "+e.getMessage());
}
//Catch an io exception and print the error message
catch(IOException e){
System.out.println("Problem reading file.");
System.err.println("IOException: "+e.getMessage());
}
}
}
| 5,931 | 0.495701 | 0.49216 | 158 | 35.537975 | 25.172478 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.493671 | false | false | 9 |
1420d2c2d821b881f99a9b5087c83ebff6eb3295 | 23,373,212,025,209 | 1411bc7f161e053160d9013e8eb621437d6b5fd5 | /src/main/java/fr/jsmadja/antredesdragons/core/chapters/ManualChoiceChapter.java | 8fa2466fa5dd84b2773838388380de1e1c9b1227 | [] | no_license | jsmadja/antre-des-dragons | https://github.com/jsmadja/antre-des-dragons | e04c489b7332c5f8044e0e849408beb8343bdda8 | d6f5e45febf6cc282113474915b9b2d9ced7763c | refs/heads/master | 2021-07-18T07:51:03.426000 | 2020-06-01T14:59:15 | 2020-06-01T14:59:15 | 175,958,159 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.jsmadja.antredesdragons.core.chapters;
import fr.jsmadja.antredesdragons.core.entities.Pip;
import fr.jsmadja.antredesdragons.core.execution.Action;
import fr.jsmadja.antredesdragons.core.execution.Execution;
import lombok.Builder;
import lombok.Getter;
import java.util.List;
import static fr.jsmadja.antredesdragons.core.chapters.ChapterNumber.chapter;
import static java.text.MessageFormat.format;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
public abstract class ManualChoiceChapter extends Chapter {
public abstract Paths getPossiblesPath(Pip pip);
@Override
public Execution execute(Pip pip) {
return Execution.builder()
.logEntries(pip.getCurrentChapterLogEntries())
.actions(getPossiblesPath(pip).toActions())
.build();
}
public static class Paths {
private final List<Path> paths;
public Paths(Path... paths) {
this(List.of(paths));
}
public Paths(List<Path> paths) {
this.paths = paths;
}
public void print() {
paths.stream().sorted(comparing(Path::getChapter)).forEach(System.out::println);
}
private List<Integer> getChapter() {
return paths.stream().map(Path::getChapter).collect(toList());
}
public void add(Path... paths) {
this.paths.addAll(asList(paths));
}
public List<Action> toActions() {
return paths.stream().map(Path::toAction).collect(toList());
}
}
@Builder
@Getter
public static class Path {
private Integer chapter;
private String description;
@Override
public String toString() {
return format("- {0}{1}", chapter, description == null ? "" : " - " + description);
}
public Action toAction() {
return Action.question(chapter(chapter), description);
}
}
}
| UTF-8 | Java | 2,052 | java | ManualChoiceChapter.java | Java | [] | null | [] | package fr.jsmadja.antredesdragons.core.chapters;
import fr.jsmadja.antredesdragons.core.entities.Pip;
import fr.jsmadja.antredesdragons.core.execution.Action;
import fr.jsmadja.antredesdragons.core.execution.Execution;
import lombok.Builder;
import lombok.Getter;
import java.util.List;
import static fr.jsmadja.antredesdragons.core.chapters.ChapterNumber.chapter;
import static java.text.MessageFormat.format;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;
public abstract class ManualChoiceChapter extends Chapter {
public abstract Paths getPossiblesPath(Pip pip);
@Override
public Execution execute(Pip pip) {
return Execution.builder()
.logEntries(pip.getCurrentChapterLogEntries())
.actions(getPossiblesPath(pip).toActions())
.build();
}
public static class Paths {
private final List<Path> paths;
public Paths(Path... paths) {
this(List.of(paths));
}
public Paths(List<Path> paths) {
this.paths = paths;
}
public void print() {
paths.stream().sorted(comparing(Path::getChapter)).forEach(System.out::println);
}
private List<Integer> getChapter() {
return paths.stream().map(Path::getChapter).collect(toList());
}
public void add(Path... paths) {
this.paths.addAll(asList(paths));
}
public List<Action> toActions() {
return paths.stream().map(Path::toAction).collect(toList());
}
}
@Builder
@Getter
public static class Path {
private Integer chapter;
private String description;
@Override
public String toString() {
return format("- {0}{1}", chapter, description == null ? "" : " - " + description);
}
public Action toAction() {
return Action.question(chapter(chapter), description);
}
}
}
| 2,052 | 0.635965 | 0.63499 | 72 | 27.5 | 24.808712 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.388889 | false | false | 9 |
628d7531685817db662c092fea017b2eaa50811e | 23,596,550,358,980 | e43c79e7fc96d57c6ab4469ba8620710adcd3baf | /app/src/main/java/com/shera/internexttv/model/LiveChannelDTO.java | 89323ecaad9f37db8409839f6ba13e79f8120a24 | [] | no_license | mhtparyani/Streaming | https://github.com/mhtparyani/Streaming | ca05df0a93f119446122123736308b64bd07732d | c3b62b44b6bb7096a42462be6afaa5d8c2e14398 | refs/heads/master | 2020-07-09T12:57:12.273000 | 2019-09-16T15:04:26 | 2019-09-16T15:04:26 | 203,973,053 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.shera.internexttv.model;
public class LiveChannelDTO {
private Long num;
private String name;
private String stream_type;
private String stream_icon;
private String added;
private String category_id;
private String custom_sid;
private String direct_source;
private Long stream_id;
private String epg_channel_id;
private Long tv_archive;
private Long tv_archive_duration;
public Long getNum() {
return num;
}
public void setNum(Long num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStream_type() {
return stream_type;
}
public void setStream_type(String stream_type) {
this.stream_type = stream_type;
}
public String getStream_icon() {
return stream_icon;
}
public void setStream_icon(String stream_icon) {
this.stream_icon = stream_icon;
}
public String getAdded() {
return added;
}
public void setAdded(String added) {
this.added = added;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getCustom_sid() {
return custom_sid;
}
public void setCustom_sid(String custom_sid) {
this.custom_sid = custom_sid;
}
public String getDirect_source() {
return direct_source;
}
public void setDirect_source(String direct_source) {
this.direct_source = direct_source;
}
public Long getStream_id() {
return stream_id;
}
public void setStream_id(Long stream_id) {
this.stream_id = stream_id;
}
public String getEpg_channel_id() {
return epg_channel_id;
}
public void setEpg_channel_id(String epg_channel_id) {
this.epg_channel_id = epg_channel_id;
}
public Long getTv_archive() {
return tv_archive;
}
public void setTv_archive(Long tv_archive) {
this.tv_archive = tv_archive;
}
public Long getTv_archive_duration() {
return tv_archive_duration;
}
public void setTv_archive_duration(Long tv_archive_duration) {
this.tv_archive_duration = tv_archive_duration;
}
}
| UTF-8 | Java | 2,411 | java | LiveChannelDTO.java | Java | [] | null | [] | package com.shera.internexttv.model;
public class LiveChannelDTO {
private Long num;
private String name;
private String stream_type;
private String stream_icon;
private String added;
private String category_id;
private String custom_sid;
private String direct_source;
private Long stream_id;
private String epg_channel_id;
private Long tv_archive;
private Long tv_archive_duration;
public Long getNum() {
return num;
}
public void setNum(Long num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStream_type() {
return stream_type;
}
public void setStream_type(String stream_type) {
this.stream_type = stream_type;
}
public String getStream_icon() {
return stream_icon;
}
public void setStream_icon(String stream_icon) {
this.stream_icon = stream_icon;
}
public String getAdded() {
return added;
}
public void setAdded(String added) {
this.added = added;
}
public String getCategory_id() {
return category_id;
}
public void setCategory_id(String category_id) {
this.category_id = category_id;
}
public String getCustom_sid() {
return custom_sid;
}
public void setCustom_sid(String custom_sid) {
this.custom_sid = custom_sid;
}
public String getDirect_source() {
return direct_source;
}
public void setDirect_source(String direct_source) {
this.direct_source = direct_source;
}
public Long getStream_id() {
return stream_id;
}
public void setStream_id(Long stream_id) {
this.stream_id = stream_id;
}
public String getEpg_channel_id() {
return epg_channel_id;
}
public void setEpg_channel_id(String epg_channel_id) {
this.epg_channel_id = epg_channel_id;
}
public Long getTv_archive() {
return tv_archive;
}
public void setTv_archive(Long tv_archive) {
this.tv_archive = tv_archive;
}
public Long getTv_archive_duration() {
return tv_archive_duration;
}
public void setTv_archive_duration(Long tv_archive_duration) {
this.tv_archive_duration = tv_archive_duration;
}
}
| 2,411 | 0.613438 | 0.613438 | 113 | 20.336283 | 18.011112 | 66 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.327434 | false | false | 9 |
c7a8b8e09b92fe74b435865d42b8d1c8e8527068 | 30,322,469,146,656 | e54aff389573a079232723480a0729c18b5f9c6b | /src/ApiPackage/ApiTagH5Class.java | 747c38b614301404805b1a247f438bac6f18e07d | [] | no_license | bavithiranChatly/ApiTagH5 | https://github.com/bavithiranChatly/ApiTagH5 | 189c2d270969b928b6cdbcf4e7cb8eea5f796467 | a53985d2e4113b9d517aaf13252b49ebde251c72 | refs/heads/master | 2021-01-08T15:07:38.124000 | 2020-02-21T05:48:27 | 2020-02-21T05:48:27 | 242,062,738 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ApiPackage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class ApiTagH5Class {
private final CloseableHttpClient httpClient = HttpClients.createDefault();
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ApiTagH5Class obj = new ApiTagH5Class();
try {
// System.out.println("Testing 1 - Send Http GET request");
// obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
} finally {
obj.close();
}
}
private void close() throws IOException {
httpClient.close();
}
private void sendPost() throws Exception {
Properties Apiobj = new Properties();
FileInputStream Apiobjfile = new FileInputStream(System.getProperty("user.dir")+"\\application.properties");
Apiobj.load(Apiobjfile);
String BaseUrlApi = Apiobj.getProperty("BASEURL");
//HttpPost post = new HttpPost("https://stgcalls.wechatify.com/api/TagManagement/SendTagDetailByOpenId?access_token=634b1d6f-5675-4925-be31-e282f247ebca&Version=v2");
HttpPost post = new HttpPost(BaseUrlApi);
//Excel Read Function.
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("TagId", "2df1415f-d08d-4e3c-8e0b-cb79ded0d432"));
urlParameters.add(new BasicNameValuePair("OpenId", "oo0EUvyzsTKwC3pQoF4tTfIHQ8z8"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
| UTF-8 | Java | 2,197 | java | ApiTagH5Class.java | Java | [
{
"context": "/TagManagement/SendTagDetailByOpenId?access_token=634b1d6f-5675-4925-be31-e282f247ebca&Version=v2\");\n\n\t\tHttpPost post = new HttpPost(Bas",
"end": 1539,
"score": 0.9644125699996948,
"start": 1503,
"tag": "KEY",
"value": "634b1d6f-5675-4925-be31-e282f247ebca"
}
] | null | [] | package ApiPackage;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class ApiTagH5Class {
private final CloseableHttpClient httpClient = HttpClients.createDefault();
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ApiTagH5Class obj = new ApiTagH5Class();
try {
// System.out.println("Testing 1 - Send Http GET request");
// obj.sendGet();
System.out.println("Testing 2 - Send Http POST request");
obj.sendPost();
} finally {
obj.close();
}
}
private void close() throws IOException {
httpClient.close();
}
private void sendPost() throws Exception {
Properties Apiobj = new Properties();
FileInputStream Apiobjfile = new FileInputStream(System.getProperty("user.dir")+"\\application.properties");
Apiobj.load(Apiobjfile);
String BaseUrlApi = Apiobj.getProperty("BASEURL");
//HttpPost post = new HttpPost("https://stgcalls.wechatify.com/api/TagManagement/SendTagDetailByOpenId?access_token=634b1d6f-5675-4925-be31-e282f247ebca&Version=v2");
HttpPost post = new HttpPost(BaseUrlApi);
//Excel Read Function.
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("TagId", "2df1415f-d08d-4e3c-8e0b-cb79ded0d432"));
urlParameters.add(new BasicNameValuePair("OpenId", "oo0EUvyzsTKwC3pQoF4tTfIHQ8z8"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
| 2,197 | 0.757396 | 0.735093 | 79 | 26.810127 | 31.420816 | 168 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.594937 | false | false | 9 |
6a24bb817d3edcdc41876bd80a42770286d9bdeb | 24,086,176,631,277 | 48fe69bb7fabb910711e311acb8390b9e9c3dec5 | /src/jpa/principal/principal.java | e0c697298196defb1c385006777a4a02eb2c7dff | [] | no_license | WandaRMaldo/EjemploEgg | https://github.com/WandaRMaldo/EjemploEgg | 17a86b9cc5ad7d15fa92adf8954176dc69c322a5 | a3f4fba6ee9abace0f8c23e0173fc7fb8f817f36 | refs/heads/main | 2023-07-30T20:43:59.657000 | 2021-09-28T23:42:45 | 2021-09-28T23:42:45 | 411,074,920 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package jpa.principal;
import jpa.excepcion.MiExcepcion;
import jpa.menu.Menu;
/**
*
* @author WANDA
*/
public class principal {
public static void main(String[] args) throws MiExcepcion{
Menu menu = new Menu();
menu.interfazPrincipal();
}
}
| UTF-8 | Java | 278 | java | principal.java | Java | [
{
"context": "xcepcion;\nimport jpa.menu.Menu;\n\n/**\n *\n * @author WANDA\n */\npublic class principal {\n\n public static v",
"end": 104,
"score": 0.9996390342712402,
"start": 99,
"tag": "NAME",
"value": "WANDA"
}
] | null | [] | package jpa.principal;
import jpa.excepcion.MiExcepcion;
import jpa.menu.Menu;
/**
*
* @author WANDA
*/
public class principal {
public static void main(String[] args) throws MiExcepcion{
Menu menu = new Menu();
menu.interfazPrincipal();
}
}
| 278 | 0.643885 | 0.643885 | 18 | 14.444445 | 16.747213 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.277778 | false | false | 9 |
dd00ba36138ef3621bbc5610424775391eeae4ee | 14,559,939,175,433 | 02c3502194234717ac12b17c776bcdb92eeef44a | /src/com/taskGWT/client/Entities/Person.java | 2f4a1f5554d8b03352ffac5a75dc74c5766905d3 | [] | no_license | AleksandrFomin/gwt | https://github.com/AleksandrFomin/gwt | eaf143f4a0b214fc88edf636acd0b8692c6e57bf | 78251c53910ed2481ed0fda5f85ee4440130ed1f | refs/heads/master | 2020-03-14T07:53:33.952000 | 2018-05-02T08:26:00 | 2018-05-02T08:26:00 | 131,445,904 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.taskGWT.client.Entities;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
public class Person {
public Person(String name, String lastName, Date birthDate, Time time) {
this.name = name;
this.lastName = lastName;
this.birthDate = birthDate;
this.time = time;
}
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
private String name;
private String lastName;
private Date birthDate;
private Time time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
}
| UTF-8 | Java | 1,133 | java | Person.java | Java | [] | null | [] | package com.taskGWT.client.Entities;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
public class Person {
public Person(String name, String lastName, Date birthDate, Time time) {
this.name = name;
this.lastName = lastName;
this.birthDate = birthDate;
this.time = time;
}
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
private String name;
private String lastName;
private Date birthDate;
private Time time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Time getTime() {
return time;
}
public void setTime(Time time) {
this.time = time;
}
}
| 1,133 | 0.606355 | 0.606355 | 60 | 17.883333 | 16.657423 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.433333 | false | false | 9 |
4c9f32e094d6f4997c104b9af59bee615e28dab3 | 29,635,274,386,059 | d04934902ca785560da2c0ec6c2cb60ab77d94d6 | /src/main/java/bean/EchartsResult.java | 0e48b22efcd7e295f6d2bebd5cae6d9de6e73a62 | [] | no_license | fanmcgrady/mini | https://github.com/fanmcgrady/mini | 3fca7259c7256da2d01e529ac0d90d8191eb458a | 6d4fc7687375718a4ae45c96bb067cf14147eac9 | refs/heads/master | 2023-01-22T14:02:43.032000 | 2020-11-20T00:15:56 | 2020-11-20T00:15:56 | 302,523,870 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bean;
import java.util.List;
public class EchartsResult {
private List<String> xData;
private List<Integer> yData;
public List<String> getxData() {
return xData;
}
public void setxData(List<String> xData) {
this.xData = xData;
}
public List<Integer> getyData() {
return yData;
}
public void setyData(List<Integer> yData) {
this.yData = yData;
}
}
| UTF-8 | Java | 433 | java | EchartsResult.java | Java | [] | null | [] | package bean;
import java.util.List;
public class EchartsResult {
private List<String> xData;
private List<Integer> yData;
public List<String> getxData() {
return xData;
}
public void setxData(List<String> xData) {
this.xData = xData;
}
public List<Integer> getyData() {
return yData;
}
public void setyData(List<Integer> yData) {
this.yData = yData;
}
}
| 433 | 0.6097 | 0.6097 | 24 | 17.041666 | 15.656413 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
0f2c5d2d1e36011f6dfef0938fc7df229543f6c0 | 3,178,275,846,420 | 4cb5c2d253c39d5fdff1af1e298c7e091be68873 | /College/Main.java | 699ab8397a7b81b4762bc84db6d2abfc4cb3c556 | [] | no_license | jagadishr9/Playground | https://github.com/jagadishr9/Playground | 8f22c142200acd45250a85deea5168907735a425 | 3c1e655f41ff731c02c703f52363a5cd1b6b349f | refs/heads/master | 2022-07-05T14:18:55.768000 | 2020-05-14T10:25:04 | 2020-05-14T10:25:04 | 257,422,969 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | #include<iostream>
using namespace std;
struct College { char name[100]; char city[100]; int establishmentYear; float passPercentage; };
int main()
{
//Type your code here.
struct College num[3];
cout<<"Enter the number of colleges\n";
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Enter the details of college "<<i<<"\n";
cout<<"Enter name";
cin>>num[i].name;
cout<<"\nEnter city";
cin>>num[i].city;
cout<<"\nEnter year of establishment";
cin>>num[i].establishmentYear;
cout<<"\nEnter pass percentage\n";
cin>>num[i].passPercentage;
}
cout<<"Details of colleges\n";
for(int i=1;i<=n;i++)
{
cout<<"College:"<<i<<"\n";
cout<<"Name:";
cout<<num[i].name;
cout<<"\nCity:";
cout<<num[i].city;
cout<<"\nYear of establishment:";
cout<<num[i].establishmentYear;
cout<<"\nPass percentage:";
cout<<num[i].passPercentage<<"\n";
}
} | UTF-8 | Java | 919 | java | Main.java | Java | [] | null | [] | #include<iostream>
using namespace std;
struct College { char name[100]; char city[100]; int establishmentYear; float passPercentage; };
int main()
{
//Type your code here.
struct College num[3];
cout<<"Enter the number of colleges\n";
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Enter the details of college "<<i<<"\n";
cout<<"Enter name";
cin>>num[i].name;
cout<<"\nEnter city";
cin>>num[i].city;
cout<<"\nEnter year of establishment";
cin>>num[i].establishmentYear;
cout<<"\nEnter pass percentage\n";
cin>>num[i].passPercentage;
}
cout<<"Details of colleges\n";
for(int i=1;i<=n;i++)
{
cout<<"College:"<<i<<"\n";
cout<<"Name:";
cout<<num[i].name;
cout<<"\nCity:";
cout<<num[i].city;
cout<<"\nYear of establishment:";
cout<<num[i].establishmentYear;
cout<<"\nPass percentage:";
cout<<num[i].passPercentage<<"\n";
}
} | 919 | 0.598477 | 0.588683 | 37 | 23.864864 | 17.735538 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.945946 | false | false | 9 |
1022eced4a640ff0f74b656063f32596431c213e | 8,194,797,648,278 | 02d3affdad8c5aff5af1ed49367338692c3f740d | /backEnd/src/test/java/com/pitang/projectPitang/PersonControllerTest.java | 31ac840f59be1d50d25c1058deb52f6612ba8fad | [] | no_license | lacerdanycolas/pitangProject | https://github.com/lacerdanycolas/pitangProject | 2313f7a0a57ba5ebd69ade62ca3db5e8cbad53aa | eaec2d6e68e225431848372c882107717065ffab | refs/heads/master | 2023-01-22T07:42:59.760000 | 2021-05-08T22:30:29 | 2021-05-08T22:30:29 | 186,035,575 | 1 | 0 | null | false | 2023-01-07T05:29:30 | 2019-05-10T18:18:16 | 2021-12-07T15:57:33 | 2023-01-07T05:29:29 | 1,099 | 1 | 0 | 31 | Java | false | false | package com.pitang.projectPitang;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pitang.projectPitang.controllers.PersonController;
import com.pitang.projectPitang.models.Person;
import com.pitang.projectPitang.models.dto.PersonEntityDTO;
import com.pitang.projectPitang.repository.PersonRepository;
import com.pitang.projectPitang.utils.Gender;
import com.pitang.projectPitang.utils.specifications.PersonSpecification;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.Is.is;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProjectPitangApplication.class)
@EnableWebMvc
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private PersonRepository personRepository;
@Autowired
private PersonController personController;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders.standaloneSetup(personController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
})
.build();
}
public Person returnPerson(){
Person person = new Person();
person.setName("Name Teste");
person.setGender(Gender.MALE);
person.setPlace_of_birth("Recife, Pernambuco, Brasil");
person.setId(1);
person.setProfile_path("/profileteste.jpg");
return person;
}
public List<Person> returnListPerson(){
Person person = new Person();
person.setName("Name Teste");
person.setGender(Gender.MALE);
person.setPlace_of_birth("Recife, Pernambuco, Brasil");
person.setId(1);
person.setProfile_path("/profileteste.jpg");
Person person2 = new Person();
person2.setName("Name Teste Dois");
person2.setGender(Gender.FEMALE);
person2.setPlace_of_birth("Sao Paulo, Sao Paulo, Brasil");
person2.setId(2);
person2.setProfile_path("/profiletesteDois.jpg");
List<Person> list = new ArrayList<>();
list.add(person);
list.add(person2);
return list;
}
@Test
public void givenPersons_whenGetPersons_thenReturnJsonArray() throws Exception{
//Person person = this.returnPerson();
List<Person> list = this.returnListPerson();
Page<Person> personPage = new PageImpl<Person>(list);
when(personRepository.findAll(ArgumentMatchers.isA(Pageable.class))).thenReturn(personPage);
mvc.perform(get("/persons")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", hasSize(2)))
.andExpect(jsonPath("$.content[0].name").value(list.get(0).getName()))
.andExpect(jsonPath("$.content[0].id").value(list.get(0).getId()))
.andExpect(jsonPath("$.content[0].profile_path").value(list.get(0).getProfile_path()))
.andExpect(jsonPath("$.content[0].place_of_birth").value(list.get(0).getPlace_of_birth()))
.andExpect(jsonPath("$.content[0].gender").value(list.get(0).getGender().toString()));
}
@Test
public void givenOnePerson_whenGetAPerson_thenReturnsJsonArray() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
when(personRepository.findById(anyInt())).thenReturn(optionalPerson);
mvc.perform(get("/persons/"+person.getId())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$.name").value(person.getName()))
.andExpect(jsonPath("$.id").value(person.getId()))
.andExpect(jsonPath("$.profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.gender").value(person.getGender().toString()));
}
@Test
public void getPersonByFilter_whenPassName_thenReturnPerson() throws Exception{
Person person = this.returnPerson();
Page<Person> personPage = new PageImpl<Person>(Arrays.asList(person));
when(this.personRepository.findAll(any(Specification.class),ArgumentMatchers.isA(Pageable.class))).thenReturn(personPage);
mvc.perform(get("/persons/filter/")
.param("name",person.getName())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").exists())
.andExpect(jsonPath("$.content[0].name").value(person.getName()))
.andExpect(jsonPath("$.content[0].id").value(person.getId()))
.andExpect(jsonPath("$.content[0].profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.content[0].place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.content[0].gender").value(person.getGender().toString()));
}
@Test
public void savePerson_whenPassBody_thenReturnCreated() throws Exception{
Person person = this.returnPerson();
ObjectMapper objectMapper = new ObjectMapper();
PersonEntityDTO personEntityDTO = objectMapper.convertValue(person, PersonEntityDTO.class);
String personString = objectMapper.writeValueAsString(personEntityDTO);
when(this.personRepository.save(any())).thenReturn(person);
mvc.perform(post("/persons")
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json")
.content(personString))
.andDo(print())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$.name").value(person.getName()))
.andExpect(jsonPath("$.profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.gender").value(person.getGender().toString()))
.andReturn();
}
@Test
public void updatePerson_whenPassUpdateObject_thenReturnOk() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
ObjectMapper objectMapper = new ObjectMapper();
PersonEntityDTO personEntityDTO = objectMapper.convertValue(person, PersonEntityDTO.class);
String personString = objectMapper.writeValueAsString(personEntityDTO);
when(this.personRepository.findById(anyInt())).thenReturn(optionalPerson);
when(this.personRepository.save(any())).thenReturn(person);
mvc.perform(put("/persons/"+person.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json")
.content(personString))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
@Test
public void deletePerson_whenPassId_thenReturnOk() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
when(this.personRepository.findById(anyInt())).thenReturn(optionalPerson);
mvc.perform(delete("/persons/"+person.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
verify(this.personRepository, times(1)).delete(any());
}
}
| UTF-8 | Java | 10,594 | java | PersonControllerTest.java | Java | [
{
"context": "erson person = new Person();\n person.setName(\"Name Teste\");\n person.setGender(Gender.MALE);\n perso",
"end": 3990,
"score": 0.9981472492218018,
"start": 3980,
"tag": "NAME",
"value": "Name Teste"
},
{
"context": "Person person = new Person();\n person... | null | [] | package com.pitang.projectPitang;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pitang.projectPitang.controllers.PersonController;
import com.pitang.projectPitang.models.Person;
import com.pitang.projectPitang.models.dto.PersonEntityDTO;
import com.pitang.projectPitang.repository.PersonRepository;
import com.pitang.projectPitang.utils.Gender;
import com.pitang.projectPitang.utils.specifications.PersonSpecification;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.core.Is.is;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProjectPitangApplication.class)
@EnableWebMvc
@AutoConfigureMockMvc
public class PersonControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private PersonRepository personRepository;
@Autowired
private PersonController personController;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders.standaloneSetup(personController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.setViewResolvers(new ViewResolver() {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return new MappingJackson2JsonView();
}
})
.build();
}
public Person returnPerson(){
Person person = new Person();
person.setName("<NAME>");
person.setGender(Gender.MALE);
person.setPlace_of_birth("Recife, Pernambuco, Brasil");
person.setId(1);
person.setProfile_path("/profileteste.jpg");
return person;
}
public List<Person> returnListPerson(){
Person person = new Person();
person.setName("<NAME>");
person.setGender(Gender.MALE);
person.setPlace_of_birth("Recife, Pernambuco, Brasil");
person.setId(1);
person.setProfile_path("/profileteste.jpg");
Person person2 = new Person();
person2.setName("<NAME>");
person2.setGender(Gender.FEMALE);
person2.setPlace_of_birth("Sao Paulo, Sao Paulo, Brasil");
person2.setId(2);
person2.setProfile_path("/profiletesteDois.jpg");
List<Person> list = new ArrayList<>();
list.add(person);
list.add(person2);
return list;
}
@Test
public void givenPersons_whenGetPersons_thenReturnJsonArray() throws Exception{
//Person person = this.returnPerson();
List<Person> list = this.returnListPerson();
Page<Person> personPage = new PageImpl<Person>(list);
when(personRepository.findAll(ArgumentMatchers.isA(Pageable.class))).thenReturn(personPage);
mvc.perform(get("/persons")
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.content", hasSize(2)))
.andExpect(jsonPath("$.content[0].name").value(list.get(0).getName()))
.andExpect(jsonPath("$.content[0].id").value(list.get(0).getId()))
.andExpect(jsonPath("$.content[0].profile_path").value(list.get(0).getProfile_path()))
.andExpect(jsonPath("$.content[0].place_of_birth").value(list.get(0).getPlace_of_birth()))
.andExpect(jsonPath("$.content[0].gender").value(list.get(0).getGender().toString()));
}
@Test
public void givenOnePerson_whenGetAPerson_thenReturnsJsonArray() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
when(personRepository.findById(anyInt())).thenReturn(optionalPerson);
mvc.perform(get("/persons/"+person.getId())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$.name").value(person.getName()))
.andExpect(jsonPath("$.id").value(person.getId()))
.andExpect(jsonPath("$.profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.gender").value(person.getGender().toString()));
}
@Test
public void getPersonByFilter_whenPassName_thenReturnPerson() throws Exception{
Person person = this.returnPerson();
Page<Person> personPage = new PageImpl<Person>(Arrays.asList(person));
when(this.personRepository.findAll(any(Specification.class),ArgumentMatchers.isA(Pageable.class))).thenReturn(personPage);
mvc.perform(get("/persons/filter/")
.param("name",person.getName())
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.content").exists())
.andExpect(jsonPath("$.content[0].name").value(person.getName()))
.andExpect(jsonPath("$.content[0].id").value(person.getId()))
.andExpect(jsonPath("$.content[0].profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.content[0].place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.content[0].gender").value(person.getGender().toString()));
}
@Test
public void savePerson_whenPassBody_thenReturnCreated() throws Exception{
Person person = this.returnPerson();
ObjectMapper objectMapper = new ObjectMapper();
PersonEntityDTO personEntityDTO = objectMapper.convertValue(person, PersonEntityDTO.class);
String personString = objectMapper.writeValueAsString(personEntityDTO);
when(this.personRepository.save(any())).thenReturn(person);
mvc.perform(post("/persons")
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json")
.content(personString))
.andDo(print())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$.name").value(person.getName()))
.andExpect(jsonPath("$.profile_path").value(person.getProfile_path()))
.andExpect(jsonPath("$.place_of_birth").value(person.getPlace_of_birth()))
.andExpect(jsonPath("$.gender").value(person.getGender().toString()))
.andReturn();
}
@Test
public void updatePerson_whenPassUpdateObject_thenReturnOk() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
ObjectMapper objectMapper = new ObjectMapper();
PersonEntityDTO personEntityDTO = objectMapper.convertValue(person, PersonEntityDTO.class);
String personString = objectMapper.writeValueAsString(personEntityDTO);
when(this.personRepository.findById(anyInt())).thenReturn(optionalPerson);
when(this.personRepository.save(any())).thenReturn(person);
mvc.perform(put("/persons/"+person.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json")
.content(personString))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
@Test
public void deletePerson_whenPassId_thenReturnOk() throws Exception{
Person person = this.returnPerson();
Optional<Person> optionalPerson = Optional.of(person);
when(this.personRepository.findById(anyInt())).thenReturn(optionalPerson);
mvc.perform(delete("/persons/"+person.getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
verify(this.personRepository, times(1)).delete(any());
}
}
| 10,577 | 0.702756 | 0.69983 | 272 | 37.948528 | 31.005768 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481618 | false | false | 9 |
7cd01979b601fd1ab826eb7ed87feeb64c84072d | 8,194,797,650,364 | 214c8b38d7eebfd534ecf28edf36a67896852c9a | /src/NonVeg.java | 14be4380bd89ea2facae02c6e19ce4ac64610bc1 | [] | no_license | AryanSankholkar/WeightLoss-Coach | https://github.com/AryanSankholkar/WeightLoss-Coach | f7a618c0948d397adbb8027fa80af5d7403ff709 | 35acd81c78662277331489b676cb4ee7109e2009 | refs/heads/main | 2023-08-16T14:40:39.482000 | 2021-10-13T18:58:33 | 2021-10-13T18:58:33 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
public class NonVeg {
private JFrame frame;
/**
* Launch the application.
*/
public static void NewScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NonVeg window = new NonVeg();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public NonVeg() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 204, 153));
frame.setBounds(100, 100, 288, 366);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Non-Veg Diet Plan");
lblNewLabel.setForeground(Color.DARK_GRAY);
lblNewLabel.setFont(new Font("Baskerville Old Face", Font.BOLD, 24));
lblNewLabel.setBounds(10, 11, 194, 24);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1_1 = new JLabel("Breakfast");
lblNewLabel_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1.setBounds(10, 46, 194, 24);
frame.getContentPane().add(lblNewLabel_1_1);
JLabel lblNewLabel_1 = new JLabel("Oats - 50gms");
lblNewLabel_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1.setBounds(10, 67, 83, 14);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_1_2 = new JLabel("Coffee/Tea - 1cup");
lblNewLabel_1_2.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2.setBounds(10, 81, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2);
JLabel lblNewLabel_1_1_1 = new JLabel("Lunch");
lblNewLabel_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1.setBounds(10, 106, 83, 24);
frame.getContentPane().add(lblNewLabel_1_1_1);
JLabel lblNewLabel_1_2_1 = new JLabel("2 Roti or 1 Serving of Rice ");
lblNewLabel_1_2_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_1.setBounds(10, 126, 166, 14);
frame.getContentPane().add(lblNewLabel_1_2_1);
JLabel lblNewLabel_1_2_2 = new JLabel("1 Cup of Dal");
lblNewLabel_1_2_2.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_2.setBounds(10, 155, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_2);
JLabel lblNewLabel_1_2_3 = new JLabel("Chicken Gravy ");
lblNewLabel_1_2_3.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_3.setBounds(10, 141, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_3);
JLabel lblNewLabel_1_2_4 = new JLabel("Cup of Curd ");
lblNewLabel_1_2_4.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_4.setBounds(10, 170, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_4);
JLabel lblNewLabel_1_2_5 = new JLabel("Bowl Of Salad");
lblNewLabel_1_2_5.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_5.setBounds(10, 183, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_5);
JLabel lblNewLabel_1_1_1_1 = new JLabel("Evening Snacks");
lblNewLabel_1_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1_1.setBounds(10, 208, 119, 24);
frame.getContentPane().add(lblNewLabel_1_1_1_1);
JLabel lblNewLabel_1_2_1_1 = new JLabel("2 Brown Bread + 1 tbps Peanut Butter");
lblNewLabel_1_2_1_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_1_1.setBounds(10, 229, 230, 14);
frame.getContentPane().add(lblNewLabel_1_2_1_1);
JLabel lblNewLabel_1_2_6 = new JLabel("Coffee/Tea - 1cup");
lblNewLabel_1_2_6.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_6.setBounds(10, 243, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_6);
JLabel lblNewLabel_1_1_1_1_1 = new JLabel("Dinner ");
lblNewLabel_1_1_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1_1_1.setBounds(10, 268, 119, 24);
frame.getContentPane().add(lblNewLabel_1_1_1_1_1);
JLabel lblNewLabel_1_2_7 = new JLabel("Roasted Chicken 200gms");
lblNewLabel_1_2_7.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_7.setBounds(10, 289, 194, 14);
frame.getContentPane().add(lblNewLabel_1_2_7);
JLabel lblNewLabel_1_2_8 = new JLabel("Mix Vegetable Salad");
lblNewLabel_1_2_8.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_8.setBounds(10, 303, 131, 14);
frame.getContentPane().add(lblNewLabel_1_2_8);
}
}
| UTF-8 | Java | 4,638 | java | NonVeg.java | Java | [] | null | [] | import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
public class NonVeg {
private JFrame frame;
/**
* Launch the application.
*/
public static void NewScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NonVeg window = new NonVeg();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public NonVeg() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 204, 153));
frame.setBounds(100, 100, 288, 366);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Non-Veg Diet Plan");
lblNewLabel.setForeground(Color.DARK_GRAY);
lblNewLabel.setFont(new Font("Baskerville Old Face", Font.BOLD, 24));
lblNewLabel.setBounds(10, 11, 194, 24);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1_1 = new JLabel("Breakfast");
lblNewLabel_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1.setBounds(10, 46, 194, 24);
frame.getContentPane().add(lblNewLabel_1_1);
JLabel lblNewLabel_1 = new JLabel("Oats - 50gms");
lblNewLabel_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1.setBounds(10, 67, 83, 14);
frame.getContentPane().add(lblNewLabel_1);
JLabel lblNewLabel_1_2 = new JLabel("Coffee/Tea - 1cup");
lblNewLabel_1_2.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2.setBounds(10, 81, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2);
JLabel lblNewLabel_1_1_1 = new JLabel("Lunch");
lblNewLabel_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1.setBounds(10, 106, 83, 24);
frame.getContentPane().add(lblNewLabel_1_1_1);
JLabel lblNewLabel_1_2_1 = new JLabel("2 Roti or 1 Serving of Rice ");
lblNewLabel_1_2_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_1.setBounds(10, 126, 166, 14);
frame.getContentPane().add(lblNewLabel_1_2_1);
JLabel lblNewLabel_1_2_2 = new JLabel("1 Cup of Dal");
lblNewLabel_1_2_2.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_2.setBounds(10, 155, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_2);
JLabel lblNewLabel_1_2_3 = new JLabel("Chicken Gravy ");
lblNewLabel_1_2_3.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_3.setBounds(10, 141, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_3);
JLabel lblNewLabel_1_2_4 = new JLabel("Cup of Curd ");
lblNewLabel_1_2_4.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_4.setBounds(10, 170, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_4);
JLabel lblNewLabel_1_2_5 = new JLabel("Bowl Of Salad");
lblNewLabel_1_2_5.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_5.setBounds(10, 183, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_5);
JLabel lblNewLabel_1_1_1_1 = new JLabel("Evening Snacks");
lblNewLabel_1_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1_1.setBounds(10, 208, 119, 24);
frame.getContentPane().add(lblNewLabel_1_1_1_1);
JLabel lblNewLabel_1_2_1_1 = new JLabel("2 Brown Bread + 1 tbps Peanut Butter");
lblNewLabel_1_2_1_1.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_1_1.setBounds(10, 229, 230, 14);
frame.getContentPane().add(lblNewLabel_1_2_1_1);
JLabel lblNewLabel_1_2_6 = new JLabel("Coffee/Tea - 1cup");
lblNewLabel_1_2_6.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_6.setBounds(10, 243, 119, 14);
frame.getContentPane().add(lblNewLabel_1_2_6);
JLabel lblNewLabel_1_1_1_1_1 = new JLabel("Dinner ");
lblNewLabel_1_1_1_1_1.setFont(new Font("Tahoma", Font.BOLD, 15));
lblNewLabel_1_1_1_1_1.setBounds(10, 268, 119, 24);
frame.getContentPane().add(lblNewLabel_1_1_1_1_1);
JLabel lblNewLabel_1_2_7 = new JLabel("Roasted Chicken 200gms");
lblNewLabel_1_2_7.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_7.setBounds(10, 289, 194, 14);
frame.getContentPane().add(lblNewLabel_1_2_7);
JLabel lblNewLabel_1_2_8 = new JLabel("Mix Vegetable Salad");
lblNewLabel_1_2_8.setFont(new Font("Microsoft JhengHei", Font.BOLD, 13));
lblNewLabel_1_2_8.setBounds(10, 303, 131, 14);
frame.getContentPane().add(lblNewLabel_1_2_8);
}
}
| 4,638 | 0.690168 | 0.60414 | 127 | 35.519684 | 25.302221 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.094488 | false | false | 9 |
7266025524c50253f712825956a436aa9c4558fd | 2,843,268,384,930 | 4072d92c288627910c42f8f549baa2b511bc638c | /app/src/main/java/com/example/asus/monisan/v/activity/MainActivity.java | f0bbce44a2698a079203b31c4e13253a0472c419 | [] | no_license | houzhengbang-houzhengbang/monisan | https://github.com/houzhengbang-houzhengbang/monisan | bb07114c55aaa98b1b0b449af6f97e965c82925a | a829806f257cc58f6f5cd093dc6dedd4cdb7aef8 | refs/heads/master | 2020-03-21T09:06:09.126000 | 2018-06-29T06:52:34 | 2018-06-29T06:52:34 | 138,382,997 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.asus.monisan.v.activity;
import android.graphics.Color;
import com.example.asus.monisan.R;
import com.example.asus.monisan.m.model.MainModel;
import com.example.asus.monisan.p.MainPresenter;
import com.example.asus.monisan.v.fragment.FragmentList;
import com.example.asus.monisan.v.fragment.Fragmentvideo;
import com.example.base.BaseActivity;
import com.example.base.mvp.BaseModel;
import com.hjm.bottomtabbar.BottomTabBar;
public class MainActivity extends BaseActivity<MainPresenter> {
private BottomTabBar bottombar;
@Override
protected BaseModel initModel() {
return new MainModel();
}
@Override
protected MainPresenter initPresenter() {
return new MainPresenter();
}
@Override
protected int bindLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
bottombar = findViewById(R.id.bottombar);
}
@Override
protected void initData() {
bottombar.init(getSupportFragmentManager())
.setImgSize(100,100)
.setFontSize(0)
.setChangeColor(Color.RED,Color.DKGRAY)
.addTabItem( "视频", R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,Fragmentvideo.class)
.addTabItem( "列表", R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,FragmentList.class)
.isShowDivider(false);
}
}
| UTF-8 | Java | 1,477 | java | MainActivity.java | Java | [] | null | [] | package com.example.asus.monisan.v.activity;
import android.graphics.Color;
import com.example.asus.monisan.R;
import com.example.asus.monisan.m.model.MainModel;
import com.example.asus.monisan.p.MainPresenter;
import com.example.asus.monisan.v.fragment.FragmentList;
import com.example.asus.monisan.v.fragment.Fragmentvideo;
import com.example.base.BaseActivity;
import com.example.base.mvp.BaseModel;
import com.hjm.bottomtabbar.BottomTabBar;
public class MainActivity extends BaseActivity<MainPresenter> {
private BottomTabBar bottombar;
@Override
protected BaseModel initModel() {
return new MainModel();
}
@Override
protected MainPresenter initPresenter() {
return new MainPresenter();
}
@Override
protected int bindLayoutId() {
return R.layout.activity_main;
}
@Override
protected void initView() {
bottombar = findViewById(R.id.bottombar);
}
@Override
protected void initData() {
bottombar.init(getSupportFragmentManager())
.setImgSize(100,100)
.setFontSize(0)
.setChangeColor(Color.RED,Color.DKGRAY)
.addTabItem( "视频", R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,Fragmentvideo.class)
.addTabItem( "列表", R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,FragmentList.class)
.isShowDivider(false);
}
}
| 1,477 | 0.688904 | 0.684139 | 57 | 24.771931 | 27.450125 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.421053 | false | false | 9 |
52d02ade60a9313d93855affa6411cf39d15a47a | 13,082,470,427,615 | dad0c141b7fbdb4583f569dbacf0ea32003110d4 | /src/main/java/com/aicvs/socket/ISocket.java | 03dc354cae7ec1aeeaf5bfaec916a2c4950918a8 | [] | no_license | 18679658563/WXInterface | https://github.com/18679658563/WXInterface | 208efdfededa28675e057125c782b86d92c5d822 | b09ea12db63853bf2a16b46a82b99365c0fc3639 | refs/heads/master | 2018-07-10T11:45:46.051000 | 2018-07-10T09:40:23 | 2018-07-10T09:40:23 | 135,676,219 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.aicvs.socket;
import java.util.List;
public interface ISocket {
List<GoodMessage> getCurrentGoods(String devId);
void unlock(String devId);
void lock(String devId);
String getType(String devId);
String getStatus(String devId);
}
| UTF-8 | Java | 266 | java | ISocket.java | Java | [] | null | [] | package com.aicvs.socket;
import java.util.List;
public interface ISocket {
List<GoodMessage> getCurrentGoods(String devId);
void unlock(String devId);
void lock(String devId);
String getType(String devId);
String getStatus(String devId);
}
| 266 | 0.721804 | 0.721804 | 14 | 18 | 16.801361 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 9 |
7b476d694e1a76a261b72420fc367799002637c7 | 18,597,208,440,960 | b9cb8b61bcd6aeb32124ecb39865d78080fcd329 | /module14/fourier/MakeMusic.java | d125ac9770ab65b026e1e4a0172ea7a6ddde8450 | [] | no_license | searri/CSCI-3212 | https://github.com/searri/CSCI-3212 | 601b53428bf8b1f589fad811bdc04bf9bc4f0213 | 712bf5b428df4a725b6fd5f77d9a72a7a8bbf31a | refs/heads/master | 2020-07-09T17:10:54.699000 | 2019-12-19T23:04:19 | 2019-12-19T23:04:19 | 204,029,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class MakeMusic {
public static void main (String[] argv)
{
int samplesPerSecond = 8000;
// Example:
byte[] samples = SignalProcUtil.makeMusic ("ABACADAFAGA", "DBDCDDDEDDG", samplesPerSecond);
// To make your own music, edit the two strings above. Use any letter among
// "A' through 'G' (in caps). Both strings have to be the same length.
// Can you tell the difference between the two strings?
// Now play the sound.
SignalProcUtil.playSoundBytes (samples, samplesPerSecond);
}
} | UTF-8 | Java | 515 | java | MakeMusic.java | Java | [] | null | [] |
public class MakeMusic {
public static void main (String[] argv)
{
int samplesPerSecond = 8000;
// Example:
byte[] samples = SignalProcUtil.makeMusic ("ABACADAFAGA", "DBDCDDDEDDG", samplesPerSecond);
// To make your own music, edit the two strings above. Use any letter among
// "A' through 'G' (in caps). Both strings have to be the same length.
// Can you tell the difference between the two strings?
// Now play the sound.
SignalProcUtil.playSoundBytes (samples, samplesPerSecond);
}
} | 515 | 0.708738 | 0.700971 | 18 | 27.611111 | 29.96876 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.888889 | false | false | 9 |
f67bc5b1f2a7f4ddb0b234a52e672811cab50c30 | 18,330,920,456,909 | d0cba41677f5defe05b0cf9ea4bf63e4f905a4ec | /SW/legacy/HEXIWEAR_android/app/src/main/java/com/mikroe/hexiwear_android/HexiwearService.java | edd77a50a1dd6dd7edcfe53bf7a5d80006cd4dff | [] | no_license | ErichStyger/HEXIWEAR | https://github.com/ErichStyger/HEXIWEAR | f1b5cc9e6f67c4779041374018447e616ad24e8c | 2e3724d40cd985f1feb16b807b7c33f707c9affd | refs/heads/master | 2021-01-21T00:56:48.436000 | 2017-02-12T10:49:16 | 2017-02-12T10:49:16 | 62,727,579 | 1 | 1 | null | true | 2016-07-06T14:31:20 | 2016-07-06T14:31:19 | 2016-07-06T14:31:10 | 2016-06-25T14:34:14 | 106,515 | 0 | 0 | 0 | null | null | null | package com.mikroe.hexiwear_android;
/**
* Created by djolic on 2015-11-24.
*/
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.MessageQueue;
import android.util.Log;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class HexiwearService {
private static final String TAG = "KWARP_Service";
public static final String HEXIWEAR_ADDRESS = "00:04:9F:00:00:01";
public static final String UUID_CHAR_AMBIENT_LIGHT = "00002011-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_TEMPERATURE = "00002012-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_HUMIDITY = "00002013-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_PRESSURE = "00002014-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_HEARTRATE = "00002021-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_BATTERY = "00002a19-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_ACCEL = "00002001-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_GYRO = "00002002-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_MAGNET = "00002003-0000-1000-8000-00805f9b34fb";
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private final ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
private int charCnt = 0;
private Timer myTimer;
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public HexiwearService(ArrayList<String> uuidArray) {
String uuidGat = null;
mGattCharacteristics = DeviceScanActivity.getGattCharacteristics();
mBluetoothLeService = DeviceScanActivity.getBluetoothLeService();
for(int cnt = 0; cnt < mGattCharacteristics.size(); cnt++) {
for(int cnt1 = 0; cnt1 < mGattCharacteristics.get(cnt).size(); cnt1++) {
BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(cnt).get(cnt1);
uuidGat = characteristic.getUuid().toString();
for (String uuid : uuidArray) {
if(uuid.equals(uuidGat)) {
charas.add(characteristic);
break;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
private class ReadCharTask extends TimerTask {
public void run() {
readCharacteristic(charas.get(charCnt++));
if (charCnt == charas.size()) {
charCnt = 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (characteristic != null) {
final int charaProp = characteristic.getProperties();
if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
while(mBluetoothLeService.readCharacteristic(characteristic) == false) {
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
Log.e(TAG, "InterruptedException");
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharStart(long interval) {
myTimer = new Timer();
ReadCharTask readCharTask = new ReadCharTask();
myTimer.schedule(readCharTask, 200, interval);
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharStop() {
myTimer.cancel();
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
}
| UTF-8 | Java | 5,629 | java | HexiwearService.java | Java | [
{
"context": "ge com.mikroe.hexiwear_android;\n\n/**\n * Created by djolic on 2015-11-24.\n */\nimport android.bluetooth.Bluet",
"end": 62,
"score": 0.9996871948242188,
"start": 56,
"tag": "USERNAME",
"value": "djolic"
}
] | null | [] | package com.mikroe.hexiwear_android;
/**
* Created by djolic on 2015-11-24.
*/
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.MessageQueue;
import android.util.Log;
import java.util.ArrayList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
public class HexiwearService {
private static final String TAG = "KWARP_Service";
public static final String HEXIWEAR_ADDRESS = "00:04:9F:00:00:01";
public static final String UUID_CHAR_AMBIENT_LIGHT = "00002011-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_TEMPERATURE = "00002012-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_HUMIDITY = "00002013-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_PRESSURE = "00002014-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_HEARTRATE = "00002021-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_BATTERY = "00002a19-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_ACCEL = "00002001-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_GYRO = "00002002-0000-1000-8000-00805f9b34fb";
public static final String UUID_CHAR_MAGNET = "00002003-0000-1000-8000-00805f9b34fb";
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private final ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();
private int charCnt = 0;
private Timer myTimer;
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public HexiwearService(ArrayList<String> uuidArray) {
String uuidGat = null;
mGattCharacteristics = DeviceScanActivity.getGattCharacteristics();
mBluetoothLeService = DeviceScanActivity.getBluetoothLeService();
for(int cnt = 0; cnt < mGattCharacteristics.size(); cnt++) {
for(int cnt1 = 0; cnt1 < mGattCharacteristics.get(cnt).size(); cnt1++) {
BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(cnt).get(cnt1);
uuidGat = characteristic.getUuid().toString();
for (String uuid : uuidArray) {
if(uuid.equals(uuidGat)) {
charas.add(characteristic);
break;
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
private class ReadCharTask extends TimerTask {
public void run() {
readCharacteristic(charas.get(charCnt++));
if (charCnt == charas.size()) {
charCnt = 0;
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (characteristic != null) {
final int charaProp = characteristic.getProperties();
if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
while(mBluetoothLeService.readCharacteristic(characteristic) == false) {
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
Log.e(TAG, "InterruptedException");
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharStart(long interval) {
myTimer = new Timer();
ReadCharTask readCharTask = new ReadCharTask();
myTimer.schedule(readCharTask, 200, interval);
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
public void readCharStop() {
myTimer.cancel();
}
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
}
| 5,629 | 0.440931 | 0.390478 | 123 | 44.764229 | 38.167171 | 141 | false | false | 0 | 0 | 0 | 0 | 98 | 0.311068 | 0.422764 | false | false | 9 |
7979c8acb3817f6db3ab958034c65ebc8aca5ad2 | 26,276,609,952,278 | d47caf4e1be5c02a38a413e02d29a652011e2689 | /ProyectoEstructuras/src/proyectoestructuras/GUIProject.java | 4bc6bfd53851db3d3b99fb93b25ab44263f2b265 | [] | no_license | MAndresSL/ProyectoEstructuras_MS_CE_AV | https://github.com/MAndresSL/ProyectoEstructuras_MS_CE_AV | e4059555c7639e72b7aabb7dc41dd406234f3ed6 | d80900f391f08d352b3e58d6aaaeee508db76aae | refs/heads/master | 2021-07-03T15:26:11.554000 | 2017-09-25T21:58:37 | 2017-09-25T21:58:37 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package proyectoestructuras;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author Maslz
*/
public class GUIProject extends javax.swing.JFrame {
/**
* Creates new form GUIProject
*/
public GUIProject() {
initComponents();
this.setLocationRelativeTo(null);
this.pack();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jd_desempeno = new javax.swing.JDialog();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jl_elegir1 = new javax.swing.JLabel();
tf_pathtree = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
ta_evaluacion = new javax.swing.JTextArea();
jd_resolucion = new javax.swing.JDialog();
jPanel3 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
tf_math = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jl_answer = new javax.swing.JLabel();
jd_bicoloreable = new javax.swing.JDialog();
jPanel11 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jt_gruporojo = new javax.swing.JTextArea();
jScrollPane5 = new javax.swing.JScrollPane();
jt_grupoazul = new javax.swing.JTextArea();
jl_bicolorResp = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jl_rojo = new javax.swing.JLabel();
jl_azul = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
jl_elegir3 = new javax.swing.JLabel();
jd_compresion = new javax.swing.JDialog();
jPanel4 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
ta_original = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
ta_binary = new javax.swing.JTextArea();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jp_comprimir = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jp_descomprimir = new javax.swing.JPanel();
jLabel29 = new javax.swing.JLabel();
jp_elegir2 = new javax.swing.JPanel();
jl_elegir2 = new javax.swing.JLabel();
jd_krusprim = new javax.swing.JDialog();
jPanel14 = new javax.swing.JPanel();
jLabel26 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel25 = new javax.swing.JLabel();
jPanel21 = new javax.swing.JPanel();
jLabel35 = new javax.swing.JLabel();
jScrollPane8 = new javax.swing.JScrollPane();
ta_prim = new javax.swing.JTextArea();
jd_floyd = new javax.swing.JDialog();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
floyd_ta = new javax.swing.JTextArea();
jPanel18 = new javax.swing.JPanel();
jLabel31 = new javax.swing.JLabel();
jd_dijkstra = new javax.swing.JDialog();
jPanel8 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jPanel20 = new javax.swing.JPanel();
jLabel34 = new javax.swing.JLabel();
jScrollPane7 = new javax.swing.JScrollPane();
jt_dijkstra = new javax.swing.JTextArea();
jc_origen = new javax.swing.JComboBox<>();
jb_dijkstra = new javax.swing.JButton();
panel_p = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jPanel2.setBackground(new java.awt.Color(207, 103, 102));
jLabel3.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("P O R D E S E M P E Ñ O");
jLabel2.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(207, 103, 102));
jLabel2.setText("C A L C U L O D E E V A L U A C I Ó N");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addContainerGap(17, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2))
);
jl_elegir1.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir1.setForeground(new java.awt.Color(207, 103, 102));
jl_elegir1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jl_elegir1.setText("E l e g i r a r c h i v o");
jl_elegir1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir1MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir1, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
tf_pathtree.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
ta_evaluacion.setColumns(20);
ta_evaluacion.setRows(5);
jScrollPane3.setViewportView(ta_evaluacion);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(182, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tf_pathtree, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(169, 169, 169))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addGap(48, 48, 48)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(tf_pathtree, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(96, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_desempenoLayout = new javax.swing.GroupLayout(jd_desempeno.getContentPane());
jd_desempeno.getContentPane().setLayout(jd_desempenoLayout);
jd_desempenoLayout.setHorizontalGroup(
jd_desempenoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_desempenoLayout.setVerticalGroup(
jd_desempenoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(48, 65, 93));
jLabel10.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("E X P R E S I O N E S M A T E M Á T I C A S");
jLabel9.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel9.setForeground(new java.awt.Color(48, 65, 93));
jLabel9.setText("R E S O L U C I Ó N");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addContainerGap(19, Short.MAX_VALUE)
.addComponent(jLabel9)
.addGap(18, 18, 18))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
);
tf_math.setFont(new java.awt.Font("Montserrat", 0, 14)); // NOI18N
tf_math.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tf_mathActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel16.setForeground(new java.awt.Color(255, 255, 255));
jLabel16.setText("E s c r i b i r e x p r e s i o n m a t e m á t i c a");
jLabel17.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel17.setForeground(new java.awt.Color(48, 65, 93));
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel17.setText("R E S O L V E R");
jLabel17.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLabel17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel17MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
);
jLabel18.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setText("R E S P U E S T A :");
jl_answer.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jl_answer.setForeground(new java.awt.Color(255, 255, 255));
jl_answer.setText("[ ]");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(243, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel16)
.addComponent(tf_math, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(16, 16, 16)
.addComponent(jl_answer))
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(236, 236, 236))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addGap(107, 107, 107)
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tf_math, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(72, 72, 72)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jl_answer))
.addContainerGap(109, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_resolucionLayout = new javax.swing.GroupLayout(jd_resolucion.getContentPane());
jd_resolucion.getContentPane().setLayout(jd_resolucionLayout);
jd_resolucionLayout.setHorizontalGroup(
jd_resolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_resolucionLayout.setVerticalGroup(
jd_resolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel11.setBackground(new java.awt.Color(148, 97, 142));
jPanel11.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jt_gruporojo.setColumns(20);
jt_gruporojo.setRows(5);
jScrollPane4.setViewportView(jt_gruporojo);
jPanel11.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(135, 272, 221, 158));
jt_grupoazul.setColumns(20);
jt_grupoazul.setRows(5);
jScrollPane5.setViewportView(jt_grupoazul);
jPanel11.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 270, 224, 158));
jl_bicolorResp.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N
jPanel11.add(jl_bicolorResp, new org.netbeans.lib.awtextra.AbsoluteConstraints(356, 201, 228, 58));
jPanel12.setBackground(new java.awt.Color(255, 255, 255));
jLabel19.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel19.setForeground(new java.awt.Color(148, 97, 142));
jLabel19.setText("G R A F O");
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel19)
.addGap(19, 19, 19))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19, javax.swing.GroupLayout.Alignment.TRAILING)
);
jPanel11.add(jPanel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(352, 58, -1, -1));
jLabel23.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel23.setForeground(new java.awt.Color(255, 255, 255));
jLabel23.setText("B I C O L O R E A B L E");
jLabel23.setToolTipText("");
jPanel11.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(295, 89, -1, -1));
jl_rojo.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jl_rojo.setForeground(new java.awt.Color(255, 255, 255));
jl_rojo.setText("C O L O R R O J O");
jPanel11.add(jl_rojo, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 240, -1, 23));
jl_azul.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jl_azul.setForeground(new java.awt.Color(255, 255, 255));
jl_azul.setText("C O L O R A Z U L");
jPanel11.add(jl_azul, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 240, -1, 23));
jPanel13.setBackground(new java.awt.Color(255, 255, 255));
jl_elegir3.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir3.setForeground(new java.awt.Color(148, 97, 142));
jl_elegir3.setText("E l e g i r a r c h i v o");
jl_elegir3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir3MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jl_elegir3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jl_elegir3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel11.add(jPanel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(347, 152, -1, 20));
javax.swing.GroupLayout jd_bicoloreableLayout = new javax.swing.GroupLayout(jd_bicoloreable.getContentPane());
jd_bicoloreable.getContentPane().setLayout(jd_bicoloreableLayout);
jd_bicoloreableLayout.setHorizontalGroup(
jd_bicoloreableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 869, Short.MAX_VALUE)
);
jd_bicoloreableLayout.setVerticalGroup(
jd_bicoloreableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
);
jPanel4.setBackground(new java.awt.Color(142, 174, 189));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel12.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText(" D E A R C H I V O S");
jPanel4.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(342, 100, -1, -1));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jLabel11.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel11.setForeground(new java.awt.Color(142, 174, 189));
jLabel11.setText("C O M P R E S I Ó N");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(24, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(19, 19, 19))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
);
jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(296, 69, -1, -1));
ta_original.setColumns(20);
ta_original.setFont(new java.awt.Font("Montserrat", 0, 15)); // NOI18N
ta_original.setLineWrap(true);
ta_original.setRows(5);
ta_original.setWrapStyleWord(true);
jScrollPane1.setViewportView(ta_original);
jPanel4.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 220, 270, 202));
ta_binary.setEditable(false);
ta_binary.setColumns(20);
ta_binary.setFont(new java.awt.Font("Montserrat", 0, 15)); // NOI18N
ta_binary.setLineWrap(true);
ta_binary.setRows(5);
ta_binary.setWrapStyleWord(true);
jScrollPane2.setViewportView(ta_binary);
jPanel4.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 210, 270, 202));
jLabel13.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("T E X T O O R I G I N A L");
jPanel4.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 190, -1, -1));
jLabel14.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 255, 255));
jLabel14.setText("T E X T O C O M P R I M I D O");
jPanel4.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(564, 188, -1, -1));
jp_comprimir.setBackground(new java.awt.Color(255, 255, 255));
jLabel15.setBackground(new java.awt.Color(6, 47, 79));
jLabel15.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel15.setForeground(new java.awt.Color(142, 174, 189));
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel15.setText("C O M P R I M I R");
jLabel15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel15MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_comprimirLayout = new javax.swing.GroupLayout(jp_comprimir);
jp_comprimir.setLayout(jp_comprimirLayout);
jp_comprimirLayout.setHorizontalGroup(
jp_comprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
);
jp_comprimirLayout.setVerticalGroup(
jp_comprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel4.add(jp_comprimir, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 460, -1, 20));
jp_descomprimir.setBackground(new java.awt.Color(255, 255, 255));
jLabel29.setBackground(new java.awt.Color(6, 47, 79));
jLabel29.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel29.setForeground(new java.awt.Color(142, 174, 189));
jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel29.setText("D E S C O M P R I M I R");
jLabel29.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel29MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_descomprimirLayout = new javax.swing.GroupLayout(jp_descomprimir);
jp_descomprimir.setLayout(jp_descomprimirLayout);
jp_descomprimirLayout.setHorizontalGroup(
jp_descomprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
);
jp_descomprimirLayout.setVerticalGroup(
jp_descomprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel4.add(jp_descomprimir, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 460, -1, 20));
jp_elegir2.setBackground(new java.awt.Color(255, 255, 255));
jl_elegir2.setBackground(new java.awt.Color(6, 47, 79));
jl_elegir2.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir2.setForeground(new java.awt.Color(142, 174, 189));
jl_elegir2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jl_elegir2.setText("E l e g i r a r c h i v o");
jl_elegir2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir2MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_elegir2Layout = new javax.swing.GroupLayout(jp_elegir2);
jp_elegir2.setLayout(jp_elegir2Layout);
jp_elegir2Layout.setHorizontalGroup(
jp_elegir2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
);
jp_elegir2Layout.setVerticalGroup(
jp_elegir2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_elegir2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jl_elegir2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4.add(jp_elegir2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 160, 170, -1));
javax.swing.GroupLayout jd_compresionLayout = new javax.swing.GroupLayout(jd_compresion.getContentPane());
jd_compresion.getContentPane().setLayout(jd_compresionLayout);
jd_compresionLayout.setHorizontalGroup(
jd_compresionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jd_compresionLayout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 858, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jd_compresionLayout.setVerticalGroup(
jd_compresionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jd_compresionLayout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel14.setBackground(new java.awt.Color(142, 174, 189));
jLabel26.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel26.setForeground(new java.awt.Color(240, 240, 240));
jLabel26.setText("K R U S K A L & P R I M");
jLabel26.setToolTipText("");
jLabel25.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel25.setForeground(new java.awt.Color(142, 174, 189));
jLabel25.setText("G R A F O");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel25)
.addGap(19, 19, 19))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel25, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel35.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel35.setForeground(new java.awt.Color(142, 174, 189));
jLabel35.setText("E l e g i r a r c h i v o");
jLabel35.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel35MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel35)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel35, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
);
ta_prim.setColumns(20);
ta_prim.setRows(5);
jScrollPane8.setViewportView(ta_prim);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(304, 304, 304)
.addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel26)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(250, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel14Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(221, 221, 221))
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel26)
.addGap(68, 68, 68)
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(134, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_krusprimLayout = new javax.swing.GroupLayout(jd_krusprim.getContentPane());
jd_krusprim.getContentPane().setLayout(jd_krusprimLayout);
jd_krusprimLayout.setHorizontalGroup(
jd_krusprimLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_krusprimLayout.setVerticalGroup(
jd_krusprimLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel16.setBackground(new java.awt.Color(207, 103, 102));
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jLabel27.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel27.setForeground(new java.awt.Color(207, 103, 102));
jLabel27.setText("G R A F O");
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel17Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel27)
.addGap(19, 19, 19))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel27, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel28.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel28.setForeground(new java.awt.Color(255, 255, 255));
jLabel28.setText("A L G O R I T M O F L O Y D");
jLabel28.setToolTipText("");
floyd_ta.setEditable(false);
floyd_ta.setColumns(20);
floyd_ta.setFont(new java.awt.Font("Montserrat", 1, 18)); // NOI18N
floyd_ta.setRows(5);
jScrollPane6.setViewportView(floyd_ta);
jPanel18.setBackground(new java.awt.Color(255, 255, 255));
jLabel31.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel31.setForeground(new java.awt.Color(207, 103, 102));
jLabel31.setText("E l e g i r a r c h i v o");
jLabel31.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel31MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel31)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.DEFAULT_SIZE, 19, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGap(172, 172, 172)
.addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel28)
.addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(182, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel28)
.addGap(58, 58, 58)
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(88, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_floydLayout = new javax.swing.GroupLayout(jd_floyd.getContentPane());
jd_floyd.getContentPane().setLayout(jd_floydLayout);
jd_floydLayout.setHorizontalGroup(
jd_floydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_floydLayout.setVerticalGroup(
jd_floydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel8.setBackground(new java.awt.Color(48, 65, 93));
jLabel32.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel32.setForeground(new java.awt.Color(48, 65, 93));
jLabel32.setText("G R A F O");
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel32)
.addGap(19, 19, 19))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel33.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel33.setForeground(new java.awt.Color(240, 240, 240));
jLabel33.setText("A L G O R I T M O D I J K S T R A");
jLabel33.setToolTipText("");
jLabel34.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel34.setForeground(new java.awt.Color(48, 65, 93));
jLabel34.setText("E l e g i r a r c h i v o");
jLabel34.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel34MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20);
jPanel20.setLayout(jPanel20Layout);
jPanel20Layout.setHorizontalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel20Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel34)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel20Layout.setVerticalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel34, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
);
jt_dijkstra.setColumns(20);
jt_dijkstra.setRows(5);
jScrollPane7.setViewportView(jt_dijkstra);
jc_origen.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Origen" }));
jb_dijkstra.setText("OK");
jb_dijkstra.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jb_dijkstraMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addContainerGap(181, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel33)
.addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(173, 173, 173))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(180, 180, 180)
.addComponent(jPanel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(154, 154, 154)
.addComponent(jc_origen, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jb_dijkstra, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel33)
.addGap(62, 62, 62)
.addComponent(jPanel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jc_origen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb_dijkstra)))
.addGap(27, 27, 27)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(88, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_dijkstraLayout = new javax.swing.GroupLayout(jd_dijkstra.getContentPane());
jd_dijkstra.getContentPane().setLayout(jd_dijkstraLayout);
jd_dijkstraLayout.setHorizontalGroup(
jd_dijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_dijkstraLayout.setVerticalGroup(
jd_dijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 153, 153));
setSize(new java.awt.Dimension(1000, 1000));
panel_p.setBackground(new java.awt.Color(0, 121, 107));
panel_p.setPreferredSize(new java.awt.Dimension(800, 800));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setBackground(new java.awt.Color(0, 153, 153));
jLabel1.setFont(new java.awt.Font("Montserrat", 1, 40)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 121, 107));
jLabel1.setText("T D A P R O J E C T");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(34, 34, 34))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
);
jLabel5.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("C A L C U L O D E E V A L U A C I Ó N");
jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel5MouseClicked(evt);
}
});
jLabel6.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("R E S O L U C I Ó N D E E X P R E S I O N E S M A T E M Á T I C A S");
jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel6MouseClicked(evt);
}
});
jLabel7.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("C O M P R E S I Ó N D E A R C H I V O S D E T E X T O");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
});
jLabel8.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("G R A F O B I - C O L O R E A B L E");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
});
jLabel20.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel20.setForeground(new java.awt.Color(255, 255, 255));
jLabel20.setText("A L G O R I T M O F L O Y D");
jLabel20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel20MouseClicked(evt);
}
});
jLabel21.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel21.setForeground(new java.awt.Color(255, 255, 255));
jLabel21.setText("A L G O R I T M O D I J K S T R A");
jLabel21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel21MouseClicked(evt);
}
});
jLabel22.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel22.setForeground(new java.awt.Color(255, 255, 255));
jLabel22.setText("K R U S K A L Y P R I M");
jLabel22.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel22MouseClicked(evt);
}
});
javax.swing.GroupLayout panel_pLayout = new javax.swing.GroupLayout(panel_p);
panel_p.setLayout(panel_pLayout);
panel_pLayout.setHorizontalGroup(
panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_pLayout.createSequentialGroup()
.addContainerGap(190, Short.MAX_VALUE)
.addGroup(panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel5)
.addComponent(jLabel8)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(jLabel22))
.addContainerGap(190, Short.MAX_VALUE))
);
panel_pLayout.setVerticalGroup(
panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_pLayout.createSequentialGroup()
.addGap(90, 90, 90)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(60, 60, 60)
.addComponent(jLabel5)
.addGap(40, 40, 40)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(jLabel7)
.addGap(40, 40, 40)
.addComponent(jLabel8)
.addGap(40, 40, 40)
.addComponent(jLabel20)
.addGap(40, 40, 40)
.addComponent(jLabel21)
.addGap(40, 40, 40)
.addComponent(jLabel22)
.addContainerGap(70, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_p, javax.swing.GroupLayout.DEFAULT_SIZE, 990, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_p, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bt_goActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_goActionPerformed
// TODO add your handling code here:
save();
}//GEN-LAST:event_bt_goActionPerformed
private void TF_compresionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TF_compresionKeyPressed
if (evt.getKeyCode() == 13) {
save();
}
}//GEN-LAST:event_TF_compresionKeyPressed
private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked
// TODO add your handling code here:
/*adminPerson ap = new adminPerson("./personas.txt");
ap.cargarArchivo();
Person p = new Person("Juan", 20);
ap.setPerson(p);
ap.escribirArchivo();
*/
ta_evaluacion.setText("");
jd_desempeno.pack();
jd_desempeno.setLocationRelativeTo(null);
jd_desempeno.setVisible(true);
/*for (int i = 0; i < ap.getListaPersonas().size(); i++) {
//cb_empleados.addItem(ap.getListaPersonas().get(i).getName());
}*/
}//GEN-LAST:event_jLabel5MouseClicked
private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
jd_compresion.pack();
jd_compresion.setLocationRelativeTo(null);
jd_compresion.setVisible(true);
}//GEN-LAST:event_jLabel7MouseClicked
private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked
// TODO add your handling code here:
jd_resolucion.pack();
jd_resolucion.setLocationRelativeTo(null);
jd_resolucion.setVisible(true);
}//GEN-LAST:event_jLabel6MouseClicked
private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
// TODO add your handling code here:
JDialog dialog = new JDialog();
if (ta_original.getText() == "") {
JLabel label1 = new JLabel("Por favor escribir en el text area");
dialog.add(label1);
} else {
Huffman huff = new Huffman();
String texto = ta_original.getText();
System.out.println(texto);
huff.HuffCompress(texto);
ta_original.setText("");
JLabel label2 = new JLabel("Archivo de texto comprimido exitosamente");
dialog.add(label2);
}
dialog.setLocationRelativeTo(null);
dialog.setTitle("Importante");
dialog.pack();
}//GEN-LAST:event_jLabel15MouseClicked
private void tf_mathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_mathActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tf_mathActionPerformed
private void jl_elegir1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir1MouseClicked
// TODO add your handling code here:
/*
Person p = new Person("Andre");
TreeNode root = new TreeNode(p);
TreeNode n = new TreeNode(new Person("Mario"));
TreeNode n2 = new TreeNode(new Person("Calvin", 5));
root.addTreeNode(n);
root.addTreeNode(n2);
root.addTreeNode(new TreeNode(new Person("Jorge", 8)));
TreeNode tn2 = new TreeNode(new Person("Carlos", 5));
TreeNode tn3 = new TreeNode(new Person("Jose"));
n.addTreeNode(tn2);
n.addTreeNode(tn3);
tn3.addTreeNode(new TreeNode(new Person("Karl", 10)));
tn3.addTreeNode(new TreeNode(new Person("Bart", 20)));
tn3.addTreeNode(new TreeNode(new Person("James", 6)));
*/
pathTree = load();
tf_pathtree.setText(pathTree);
TreeNode root;
try {
this.ta_evaluacion.setText("");
root = createTree(pathTree);
this.ta_evaluacion.setText("Evaluacion: " + root.evaluarTree(root));
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
/*
try {
node = createTree(pathTree);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
*/
//root.evaluarPOrden(root);
/*ArrayList<TreeNode> postorder = root.getPostOrder(root);
for (int i = 0; i < postorder.size(); i++) {
ta_evaluacion.append(i + ". " + postorder.get(i).getPersona().getName() + ": " + postorder.get(i).getPersona().getEvaluation() + "\n");
}*/
}//GEN-LAST:event_jl_elegir1MouseClicked
private void jLabel17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel17MouseClicked
// TODO add your handling code here:
String str = tf_math.getText();
if(!tf_math.getText().isEmpty()/* || isDigit(tf_math.getText())*/){
//String s = " (4/2* 3*4) +(10/5)^2";
//String infix = "5-5";
String s2 = str.replaceAll(" ", "");
String format = "";
StringTokenizer st = new StringTokenizer(s2, "+*/-()^", true);
while (st.hasMoreTokens()) {
format += st.nextToken() + " ";
}
System.out.println("");
System.out.println("Format: " + format);
System.out.println("");
String[] finalinfix = infixtoPostfix(format.split(" "));
System.out.println("Infix to Postfix: " + Arrays.toString(finalinfix) + "\n");
BinTree bt = postf_toTree(finalinfix);
Double respuesta = bt.evaluar(bt);
bt.inorden(bt);
System.out.print(" = " + respuesta);
System.out.println("");
jl_answer.setText(Double.toString(respuesta));
}else{
JOptionPane.showMessageDialog(this.jd_resolucion, "Error");
}
}//GEN-LAST:event_jLabel17MouseClicked
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
jt_gruporojo.setVisible(false);
jt_grupoazul.setVisible(false);
jl_rojo.setVisible(false);
jl_azul.setVisible(false);
jd_bicoloreable.pack();
jd_bicoloreable.setLocationRelativeTo(null);
jd_bicoloreable.setVisible(true);
}//GEN-LAST:event_jLabel8MouseClicked
private void jl_elegir3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir3MouseClicked
this.jt_gruporojo.setText("");
this.jt_grupoazul.setText("");
pathGrafo = load();
//tf_pathtree.setText(pathTree);
GrafoMatriz g;
try {
g = createMatriz(pathGrafo, true);
System.out.println("Nodos adyacentes: \n");
for (int i = 0; i < g.getMatrizAdy().length; i++) {
g.imprimirNodosAdy(i);
}
System.out.println("");
System.out.println("Matriz de adyacencia: \n");
g.imprimirMatrizAdy();
System.out.println("");
boolean bipartito = false;
/*para ver si es bipartito desde cualquier origen
for (int i = 0; i < g.getMatrizAdy().length; i++) {
this.jt_grupoazul.setText("");
this.jt_gruporojo.setText("");
ArrayList<String> colores = g.DFSbipartito(i);
if(g.isBicoloreable()){
System.out.println("es bicoloreable en " + i);
for (int j = 0; j < colores.size(); j++) {
if (colores.get(j).equals("azul")) {
jt_grupoazul.append(Integer.toString(j) + "\n");
} else {
jt_gruporojo.append(Integer.toString(j) + "\n");
}
}
bipartito = true;
break;
}
System.out.println("");
}*/
ArrayList<String> colores = g.DFSbipartito(0);
if (g.isBicoloreable()) {
bipartito = true;
for (int j = 0; j < colores.size(); j++) {
if (colores.get(j).equals("azul")) {
jt_grupoazul.append(Integer.toString(j) + "\n");
} else {
jt_gruporojo.append(Integer.toString(j) + "\n");
}
}
}
//ArrayList<String> coloress = g.DFSbipartito(0);//es bicoloreable desde origen 0?
/*if (g.isBicoloreable()) {
for (int i = 0; i < coloress.size(); i++) {
if (coloress.get(i).equals("azul")) {
jt_grupoazul.append(Integer.toString(i) + "\n");
} else {
jt_gruporojo.append(Integer.toString(i) + "\n");
}
}
}*/
//ArrayList<String> colores = g.Bicoloreable(0);
//System.out.println("Size: " + colores.size());
jl_bicolorResp.setText(bipartito == true ? ("Bi-coloreable!") : ("No es bi-coloreable desde el origen"));
jt_gruporojo.setVisible(true);
jt_grupoazul.setVisible(true);
jl_rojo.setVisible(true);
jl_azul.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jl_elegir3MouseClicked
private void jLabel29MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel29MouseClicked
// TODO add your handling code here:
String bin = binary.get(0).toString() + "0";
System.out.println("");
System.out.println(bin);
BinTree raiz = huff.HuffDecompress(binary);
String tex = DecomText(raiz, raiz, bin, "", 0);
ta_original.setText(this.text);
}//GEN-LAST:event_jLabel29MouseClicked
private void jl_elegir2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir2MouseClicked
// TODO add your handling code here:
String path = load();
binary = huff.read(path);
this.text = "";
this.decompressed = false;
ta_binary.setText(binary.get(0).toString());
}//GEN-LAST:event_jl_elegir2MouseClicked
private void jLabel31MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel31MouseClicked
// TODO add your handling code here:
String path = load();
FloydMayweather fm = new FloydMayweather();
floyd_ta.setText("");
try {
String texto = fm.Floyd(path);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
floyd_ta.setText(fm.getText());
// floyd_ta.setText("");
floyd_ta.updateUI();
// String path = load();
/* GrafoMatriz grafo;
try {
grafo = createMatriz(path, false);
Floyd floyd = new Floyd(grafo);
double[][] distancias = floyd.distanciaTodosLosDestinos();
for (int i = 0; i < distancias.length; i++) {
for (int j = 0; j < distancias.length; j++) {
if (j < distancias.length - 1) {
floyd_ta.append(distancias[i][j] + "\t");
} else {
floyd_ta.append(distancias[i][j] + "");
}
}
floyd_ta.append("\n");
}
//floyd_ta.updateUI();
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}*/
}//GEN-LAST:event_jLabel31MouseClicked
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked
// TODO add your handling code here:
jd_floyd.pack();
jd_floyd.setLocationRelativeTo(null);
jd_floyd.setVisible(true);
}//GEN-LAST:event_jLabel20MouseClicked
private void jLabel21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel21MouseClicked
// TODO add your handling code here:
jd_dijkstra.pack();
jd_dijkstra.setLocationRelativeTo(null);
jd_dijkstra.setVisible(true);
}//GEN-LAST:event_jLabel21MouseClicked
private void jLabel22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel22MouseClicked
// TODO add your handling code here:
jd_krusprim.pack();
jd_krusprim.setLocationRelativeTo(null);
jd_krusprim.setVisible(true);
// prim = new PrimTest2();
}//GEN-LAST:event_jLabel22MouseClicked
private void jLabel34MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel34MouseClicked
jt_dijkstra.setText("");
pathGrafo = load();
jc_origen.removeAllItems();
try {
Grafo g = createGrafoAdj(pathGrafo);
actual = g;
Object[] origen = new Object[g.getNodos().size()];
for (int i = 0; i < origen.length; i++) {
jc_origen.addItem(Integer.toString(i));
//posibilities[i-1] = i;
}
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
//tf_pathtree.setText(pathTree);
}//GEN-LAST:event_jLabel34MouseClicked
private void jLabel35MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel35MouseClicked
// TODO add your handling code here:
String path = load();
//PrimTest2 prim = new PrimTest2();
try {
ta_prim.setText("");
GrafoMatriz mat = createMatriz(path, false);
Prim prim = new Prim(mat.getMatrizAdy());
ArrayList<int[]> aristas = prim.prim(0);
Double cost = 0.0;
for (int i = 0; i < aristas.size(); i++) {
ta_prim.append(aristas.get(i)[0] + " -> " + aristas.get(i)[1] + " : " + aristas.get(i)[2] + "\n");
cost += aristas.get(i)[2];
}
ta_prim.append("\ncosto: " + cost);
//PrimTest2.Prim(path);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
//KruskalTest kruskal = new KruskalTest();
KruskalTest.Krusky(path);
/*
path = load();
Grafo g;
try {
g = createGrafoAdj(path);
Prim krusk = new Prim(g);
krusk.kruskal();
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}*/
}//GEN-LAST:event_jLabel35MouseClicked
private void jb_dijkstraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jb_dijkstraMouseClicked
Grafo g;
this.jt_dijkstra.setText("");
try {
g = actual;
//System.out.println("cant nodos: " + g.getNodos().size());
for (int i = 0; i < g.getNodos().size(); i++) {
System.out.println(g.getNodos().get(i).printNodosAdy());
}
Grafo copia = g;
Dijkstra dijkstra = new Dijkstra(copia, g.getNodos().get(jc_origen.getSelectedIndex()));
//Map<Nodo, Double> distanciass = dijkstra.DijkstraFinal();
Map<Nodo, Double> dist = dijkstra.dijkstra();
//System.out.println("dinstancia final\n");
for (Entry<Nodo, Double> distancia : dist.entrySet()) {
Nodo n = distancia.getKey();
double d = distancia.getValue();
this.jt_dijkstra.append(dijkstra.origen.getId() + " -> " + n.getId() + ": " + d + "\n");
//System.out.println(dijkstra.origen.getId() + " -> " + n.getId() + ": " + d);
}
/*System.out.println("SIZE: " +dist.size());
for (int i = 0; i < dist.size(); i++) {
System.out.println("distancia: " + dist.get(i));
}*/
} catch (Exception ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jb_dijkstraMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUIProject().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea floyd_ta;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JButton jb_dijkstra;
private javax.swing.JComboBox<String> jc_origen;
private javax.swing.JDialog jd_bicoloreable;
private javax.swing.JDialog jd_compresion;
private javax.swing.JDialog jd_desempeno;
private javax.swing.JDialog jd_dijkstra;
private javax.swing.JDialog jd_floyd;
private javax.swing.JDialog jd_krusprim;
private javax.swing.JDialog jd_resolucion;
private javax.swing.JLabel jl_answer;
private javax.swing.JLabel jl_azul;
private javax.swing.JLabel jl_bicolorResp;
private javax.swing.JLabel jl_elegir1;
private javax.swing.JLabel jl_elegir2;
private javax.swing.JLabel jl_elegir3;
private javax.swing.JLabel jl_rojo;
private javax.swing.JPanel jp_comprimir;
private javax.swing.JPanel jp_descomprimir;
private javax.swing.JPanel jp_elegir2;
private javax.swing.JTextArea jt_dijkstra;
private javax.swing.JTextArea jt_grupoazul;
private javax.swing.JTextArea jt_gruporojo;
private javax.swing.JPanel panel_p;
private javax.swing.JTextArea ta_binary;
private javax.swing.JTextArea ta_evaluacion;
private javax.swing.JTextArea ta_original;
private javax.swing.JTextArea ta_prim;
private javax.swing.JTextField tf_math;
private javax.swing.JTextField tf_pathtree;
// End of variables declaration//GEN-END:variables
private String pathTree;
private String pathGrafo;
private ArrayList binary;
private Huffman huff = new Huffman();
private boolean decompressed;
private String text;
private TreeNode foundTree = null;
Grafo actual = null;
public void save() {
// String texto = TF_compresion.getText();
File archiv = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
archiv = new File("./compresion.txt");
fw = new FileWriter(archiv, true);
//si el archivo no existe lo crea y si ya existe los sobreescribe (al menos que append
bw = new BufferedWriter(fw);
// bw.write(texto);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}
try {
//primero se borra el buffer
bw.close();
fw.close();
} catch (Exception e) {
}
}
public String load() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos .txt", "txt");
fileChooser.setFileFilter(filtro);
int seleccion = fileChooser.showOpenDialog(this);
if (seleccion == JFileChooser.APPROVE_OPTION) {
File dir = fileChooser.getSelectedFile();
System.out.println(dir.getPath());
return dir.getPath();
} else {
return null;
}
}
public TreeNode treeExists(int n, TreeNode nodo) {
if (nodo != null) {
for (int i = 0; i < nodo.getChildren().size(); i++) {
treeExists(n, nodo.getChildren().get(i));
}
if (nodo.getNumNodo() == n) {
return nodo;
} else {
return null;
}
}
return null;
}
public static String[] infixtoPostfix(String[] infix) {
Stack<String> s = new Stack();
StringBuilder sb = new StringBuilder();
for (String infix1 : infix) {
if (infix1.equals(" ")) {//si hay un espacio no hace nada
} else if (isDigit(infix1)) {//si infix[i] o infix1 es un digito, se agrega directamente al stringbuilder
//System.out.println("agregando " + infix1 + " al strigbuilder");
sb.append(infix1).append(" ");
} else if (isOperator(infix1)) {//si es operador verifica que el stack no este vacio y la precedencia mas alta
while (!s.isEmpty() && !s.peek().equals("(") && precedenciaMasAlta(s.peek(), infix1)) {
//String operador = s.pop();
sb.append(s.pop()/*operador*/).append(" ");
//System.out.println("agregando operador: " + operador + "al string builder");
}
s.push(infix1);
} else if (infix1.equals("(")) {//si encuentra un "(" se agrega al stack
//System.out.println("agregando ( al stack");
s.push(infix1);
} else if (infix1.equals(")")) {//no se agrega al stack pero elimina el primer parentesis "(" encontrado y agrega los operadores al string final
//System.out.println("encontro )");
while (!s.empty() && !s.peek().equals("(")) {
//String operador = s.pop();
//System.out.println("agregando operador: " + operador + "al stringbuilder");
sb.append(s.pop()/*operador*/).append(" ");
}
s.pop();//se saca el parentesis "("
//System.out.println("sacando ( del stack");
}
}
while (!s.isEmpty()) {
//String remaining = s.pop();
//System.out.println("agregando del while " + remaining);
sb.append(s.pop()/*remaining*/).append(" ");
}
String[] sFinal = sb.toString().split(" ");
return sFinal;
}
public static BinTree postf_toTree(String[] s/*recibe un arreglo de la expresion en postfix*/) {
Stack<BinTree> stackTree = new Stack();//aqui se van armando los arboles, el ultimo nodo que quede (stackTree.pop()) va a ser el arbol final
for (int i = 0; i < s.length; i++) {
if (isDigit(s[i])) {
stackTree.push(new BinTree(s[i]));
} else {//si no es un digito se crea un nuevo arbol, la raiz es el operados y los hijos (hojas) son los numeros o un arbol operador ya armado
BinTree nodoOperador = new BinTree(s[i]);
BinTree nodoR = stackTree.pop();
BinTree nodoL = stackTree.pop();
nodoOperador.insertRNode(nodoR);
nodoOperador.insertLNode(nodoL);
stackTree.push(nodoOperador);
System.out.println("Padre: " + nodoOperador.getInfo());
System.out.println("Left node: " + nodoOperador.getLNode().getInfo());
System.out.println("Right node: " + nodoOperador.getRNode().getInfo());
System.out.println("");
}
//b.postfixTree(s[i], stackTree);
}
return stackTree.pop();//el ultimo nodo que quede en el stack es el arbol completo
}
public static boolean isDigit(String s) {
return Character.isDigit(s.charAt(0));
}
public static boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("^") || s.equals("!");
}
public static int Precedencia(String s) {
int pre = 0;
if (s.equals("+") || s.equals("-")) {
pre = 1;
}
if (s.equals("*") || s.equals("/")) {
pre = 2;
}
if (s.equals("^")) {
pre = 3;
}
return pre;
}
public static boolean precedenciaMasAlta(String s, String s2) {
int prec = Precedencia(s);
int prec2 = Precedencia(s2);
if (prec == prec2) {
if (s.equals("^")) {//if(Associative(s))
return false;
} else {
return true;
}
} else {
if (prec > prec2) {
return true;
}
}
return false;
}
public GrafoMatriz createMatriz(String path, boolean dirigido) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
GrafoMatriz g;
ArrayList<String[]> info = new ArrayList();
try {
String line = br.readLine();
//int[][] matriz = new int[5][5];
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
//System.out.println(Arrays.toString(s.split(",")));
line = br.readLine();
}
for (int i = 0; i < info.size(); i++) {
System.out.println(Arrays.toString(info.get(i)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
g = new GrafoMatriz(info.size(), dirigido);
double[][] matriz = new double[info.size()][info.size()];
for (int i = 0; i < info.size(); i++) {
for (int j = 0; j < info.size(); j++) {
matriz[i][j] = Double.parseDouble(info.get(i)[j]);
System.out.print(info.get(i)[j] + " ");
}
System.out.println("");
}
g.setMatrizAdy(matriz);
//System.out.println(g.isBicoloreable());
return g;
}
public String DecomText(BinTree raiz, BinTree node, String binary, String text, int x) {
System.out.println("");
System.out.println("x: " + x);
System.out.println("length: " + binary.length());
System.out.println("TEXT: " + text);
this.text = text;
if (x >= binary.length()) {
//text = text.concat(node.getInfo());
decompressed = true;
return text;
}
if (!decompressed && x < binary.length()) {
if (binary.charAt(x) == '0' && !node.isLeaf(node)) {
DecomText(raiz, node.getLNode(), binary, text, x + 1);
} else if (binary.charAt(x) == '0' && node.isLeaf(node)) {
text = text.concat(node.getInfo());
DecomText(raiz, raiz, binary, text, x);
}
if (binary.charAt(x) == '1' && !node.isLeaf(node)) {
DecomText(raiz, node.getRNode(), binary, text, x + 1);
} else if (binary.charAt(x) == '1' && node.isLeaf(node)) {
text = text.concat(node.getInfo());
DecomText(raiz, raiz, binary, text, x);
}
}
return text;
}
public TreeNode createTree(String path) throws IOException {
TreeNode rootTree = new TreeNode();
BufferedReader br = new BufferedReader(new FileReader(path));
try {
String line = br.readLine();
ArrayList<String[]> info = new ArrayList();
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
System.out.println(Arrays.toString(line.split(",")));
line = br.readLine();
}
ArrayList<Integer> nodosUnicos = new ArrayList();
rootTree = null;
ArrayList<TreeNode> padreNotFoundNodo = new ArrayList();
ArrayList<Integer> padreNotFoundPadre = new ArrayList();
ArrayList<Integer> padres = new ArrayList();
for (int i = 0; i < info.size(); i++) {
int numeroNodo = Integer.parseInt(info.get(i)[0]);
int padre = Integer.parseInt(info.get(i)[1]);
double evaluacion = Integer.parseInt(info.get(i)[2]);
if (padre == -1) {
rootTree = new TreeNode(numeroNodo, evaluacion);
}
}
for (int i = 0; i < info.size(); i++) {
int numeroNodo = Integer.parseInt(info.get(i)[0]);
//System.out.println("Num Nodo: " + numeroNodo);
if (!nodosUnicos.contains(numeroNodo)) {
nodosUnicos.add(numeroNodo);
int padre = Integer.parseInt(info.get(i)[1]);
//System.out.println("Padre: " + padre);
double evaluacion = Integer.parseInt(info.get(i)[2]);
if (padre != -1) {
TreeNode p = findPadre(rootTree, padre);
p = foundTree;
if (foundTree != null/*!existe.contains(padre)*/) {
TreeNode hijo = new TreeNode(numeroNodo, evaluacion);
//System.out.println("n padre: " + foundTree.getNumNodo() + "\n");
p.addTreeNode(hijo);
//mapaarbol.put(hijo, new ArrayList());
} else {
//padreNotFound.put(new TreeNode(numeroNodo, evaluacion), padre);
padreNotFoundNodo.add(new TreeNode(numeroNodo, evaluacion));
padreNotFoundPadre.add(padre);
/*for (Entry<TreeNode, ArrayList<TreeNode>> mapa : mapaarbol.entrySet()) {
if (mapa.getKey().getNumNodo() == padre) {
mapa.getValue().add(new TreeNode(numeroNodo, evaluacion));
}
}*/
}
}
if (!padres.contains(padre)) {
padres.add(padre);
}
}
foundTree = null;
//if(treeExists)
/*if (treeExists(hijo, rootTree) == null) {
System.out.println("no existe nodo");
//TreeNode nuevoNodo = new TreeNode(numeroNodo)
}*/
}
/*/for (Entry<TreeNode, ArrayList<TreeNode>> map : mapaarbol.entrySet()) {
System.out.println(map.getKey().getNumNodo() + ": ");
StringBuilder sb = new StringBuilder();
System.out.println("size: " + map.getValue().size());
for (TreeNode nodo : map.getValue()) {
sb.append(nodo.getNumNodo()).append(", ");
}
System.out.print(sb.toString());
}*/
for (int i = 0; i < padreNotFoundNodo.size(); i++) {
if (!nodosUnicos.contains(padreNotFoundPadre.get(i))) {
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
}
}
while (!padreNotFoundNodo.isEmpty()) {
for (int i = 0; i < padreNotFoundNodo.size(); i++) {
TreeNode nodo = padreNotFoundNodo.get(i);
TreeNode padre = findPadre(rootTree, padreNotFoundPadre.get(i));
padre = foundTree;
if (!padres.contains(padreNotFoundPadre.get(i))) {
System.out.println("No se encontro padre de nodo" + nodo.getNumNodo());
//padreNotFound.remove(nodo, notFound.getValue());
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
} else if (padre != null) {
//System.out.println("padre de " + nodo.getNumNodo() + ": " + padreNotFoundPadre.get(i));
padre.addTreeNode(nodo);
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
//padreNotFound.remove(nodo, notFound.getValue());
}
foundTree = null;
}
}
//cont++;
//rootTree.Evaluar();
System.out.println("Evaluacion: " + rootTree.evaluarTree(rootTree));
} catch (IOException e) {
} finally {
br.close();
}
return rootTree;
}
public TreeNode findPadre(TreeNode raiz, int n) {
TreeNode find = null;
for (int i = 0; i < raiz.getChildren().size(); i++) {
find = findPadre(raiz.getChildren().get(i), n);
}
if (n == raiz.getNumNodo()) {
find = raiz;
//System.out.println("returned " + raiz.getNumNodo());
foundTree = raiz;
return find;
}
if (foundTree == null) {
return null;
} else {
return find;
}
}
public Grafo createGrafoAdj(String path) throws FileNotFoundException, IOException {
Grafo g = new Grafo();
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<String[]> info = new ArrayList();
try {
String line = br.readLine();
//int[][] matriz = new int[5][5];
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
// System.out.println(Arrays.toString(s.split(",")));
line = br.readLine();
}
for (int i = 0; i < info.size(); i++) {
System.out.println(Arrays.toString(info.get(i)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
System.out.println("");
ArrayList<Nodo> nodos = new ArrayList();
for (int i = 0; i < info.size(); i++) {
nodos.add(new Nodo(Integer.toString(i)));
}
for (int i = 0; i < info.size(); i++) {
for (int j = 0; j < info.size(); j++) {
if (Integer.parseInt(info.get(i)[j]) != 0) {
nodos.get(i).agregarArista(nodos.get(j), Double.parseDouble(info.get(i)[j]));
//n.getNodosAdyacentes().add(new Nodo(Integer.toString(j)));
//n.getPesoAdyacente().add(Double.parseDouble(info.get(i)[j]));
}
}
g.agregarNodo(nodos.get(i));
}
return g;
}
}
| UTF-8 | Java | 95,454 | java | GUIProject.java | Java | [
{
"context": "hooser.FileNameExtensionFilter;\n\n/**\n *\n * @author Maslz\n */\npublic class GUIProject extends javax.swing.J",
"end": 870,
"score": 0.9994667768478394,
"start": 865,
"tag": "USERNAME",
"value": "Maslz"
},
{
"context": ".Color(142, 174, 189));\n jLabel11.setTe... | 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 proyectoestructuras;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
*
* @author Maslz
*/
public class GUIProject extends javax.swing.JFrame {
/**
* Creates new form GUIProject
*/
public GUIProject() {
initComponents();
this.setLocationRelativeTo(null);
this.pack();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jd_desempeno = new javax.swing.JDialog();
jPanel2 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel10 = new javax.swing.JPanel();
jl_elegir1 = new javax.swing.JLabel();
tf_pathtree = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
ta_evaluacion = new javax.swing.JTextArea();
jd_resolucion = new javax.swing.JDialog();
jPanel3 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jPanel7 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
tf_math = new javax.swing.JTextField();
jLabel16 = new javax.swing.JLabel();
jPanel9 = new javax.swing.JPanel();
jLabel17 = new javax.swing.JLabel();
jLabel18 = new javax.swing.JLabel();
jl_answer = new javax.swing.JLabel();
jd_bicoloreable = new javax.swing.JDialog();
jPanel11 = new javax.swing.JPanel();
jScrollPane4 = new javax.swing.JScrollPane();
jt_gruporojo = new javax.swing.JTextArea();
jScrollPane5 = new javax.swing.JScrollPane();
jt_grupoazul = new javax.swing.JTextArea();
jl_bicolorResp = new javax.swing.JLabel();
jPanel12 = new javax.swing.JPanel();
jLabel19 = new javax.swing.JLabel();
jLabel23 = new javax.swing.JLabel();
jl_rojo = new javax.swing.JLabel();
jl_azul = new javax.swing.JLabel();
jPanel13 = new javax.swing.JPanel();
jl_elegir3 = new javax.swing.JLabel();
jd_compresion = new javax.swing.JDialog();
jPanel4 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jLabel11 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
ta_original = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
ta_binary = new javax.swing.JTextArea();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jp_comprimir = new javax.swing.JPanel();
jLabel15 = new javax.swing.JLabel();
jp_descomprimir = new javax.swing.JPanel();
jLabel29 = new javax.swing.JLabel();
jp_elegir2 = new javax.swing.JPanel();
jl_elegir2 = new javax.swing.JLabel();
jd_krusprim = new javax.swing.JDialog();
jPanel14 = new javax.swing.JPanel();
jLabel26 = new javax.swing.JLabel();
jPanel15 = new javax.swing.JPanel();
jLabel25 = new javax.swing.JLabel();
jPanel21 = new javax.swing.JPanel();
jLabel35 = new javax.swing.JLabel();
jScrollPane8 = new javax.swing.JScrollPane();
ta_prim = new javax.swing.JTextArea();
jd_floyd = new javax.swing.JDialog();
jPanel16 = new javax.swing.JPanel();
jPanel17 = new javax.swing.JPanel();
jLabel27 = new javax.swing.JLabel();
jLabel28 = new javax.swing.JLabel();
jScrollPane6 = new javax.swing.JScrollPane();
floyd_ta = new javax.swing.JTextArea();
jPanel18 = new javax.swing.JPanel();
jLabel31 = new javax.swing.JLabel();
jd_dijkstra = new javax.swing.JDialog();
jPanel8 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jLabel32 = new javax.swing.JLabel();
jLabel33 = new javax.swing.JLabel();
jPanel20 = new javax.swing.JPanel();
jLabel34 = new javax.swing.JLabel();
jScrollPane7 = new javax.swing.JScrollPane();
jt_dijkstra = new javax.swing.JTextArea();
jc_origen = new javax.swing.JComboBox<>();
jb_dijkstra = new javax.swing.JButton();
panel_p = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel20 = new javax.swing.JLabel();
jLabel21 = new javax.swing.JLabel();
jLabel22 = new javax.swing.JLabel();
jPanel2.setBackground(new java.awt.Color(207, 103, 102));
jLabel3.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("P O R D E S E M P E Ñ O");
jLabel2.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(207, 103, 102));
jLabel2.setText("C A L C U L O D E E V A L U A C I Ó N");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addContainerGap(17, Short.MAX_VALUE))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel2))
);
jl_elegir1.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir1.setForeground(new java.awt.Color(207, 103, 102));
jl_elegir1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jl_elegir1.setText("E l e g i r a r c h i v o");
jl_elegir1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir1MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10);
jPanel10.setLayout(jPanel10Layout);
jPanel10Layout.setHorizontalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE)
);
jPanel10Layout.setVerticalGroup(
jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir1, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
tf_pathtree.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
ta_evaluacion.setColumns(20);
ta_evaluacion.setRows(5);
jScrollPane3.setViewportView(ta_evaluacion);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(182, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 428, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tf_pathtree, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(169, 169, 169))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel3)
.addGap(48, 48, 48)
.addComponent(jPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(tf_pathtree, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(96, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_desempenoLayout = new javax.swing.GroupLayout(jd_desempeno.getContentPane());
jd_desempeno.getContentPane().setLayout(jd_desempenoLayout);
jd_desempenoLayout.setHorizontalGroup(
jd_desempenoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_desempenoLayout.setVerticalGroup(
jd_desempenoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel3.setBackground(new java.awt.Color(48, 65, 93));
jLabel10.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setText("E X P R E S I O N E S M A T E M Á T I C A S");
jLabel9.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel9.setForeground(new java.awt.Color(48, 65, 93));
jLabel9.setText("R E S O L U C I Ó N");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup()
.addContainerGap(19, Short.MAX_VALUE)
.addComponent(jLabel9)
.addGap(18, 18, 18))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING)
);
tf_math.setFont(new java.awt.Font("Montserrat", 0, 14)); // NOI18N
tf_math.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tf_mathActionPerformed(evt);
}
});
jLabel16.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel16.setForeground(new java.awt.Color(255, 255, 255));
jLabel16.setText("E s c r i b i r e x p r e s i o n m a t e m á t i c a");
jLabel17.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel17.setForeground(new java.awt.Color(48, 65, 93));
jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel17.setText("R E S O L V E R");
jLabel17.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
jLabel17.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel17MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
jPanel9.setLayout(jPanel9Layout);
jPanel9Layout.setHorizontalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)
);
jPanel9Layout.setVerticalGroup(
jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
);
jLabel18.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel18.setForeground(new java.awt.Color(255, 255, 255));
jLabel18.setText("R E S P U E S T A :");
jl_answer.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jl_answer.setForeground(new java.awt.Color(255, 255, 255));
jl_answer.setText("[ ]");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(243, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel16)
.addComponent(tf_math, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(16, 16, 16)
.addComponent(jl_answer))
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(236, 236, 236))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addGap(107, 107, 107)
.addComponent(jLabel16)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tf_math, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(72, 72, 72)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel18)
.addComponent(jl_answer))
.addContainerGap(109, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_resolucionLayout = new javax.swing.GroupLayout(jd_resolucion.getContentPane());
jd_resolucion.getContentPane().setLayout(jd_resolucionLayout);
jd_resolucionLayout.setHorizontalGroup(
jd_resolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_resolucionLayout.setVerticalGroup(
jd_resolucionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel11.setBackground(new java.awt.Color(148, 97, 142));
jPanel11.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jt_gruporojo.setColumns(20);
jt_gruporojo.setRows(5);
jScrollPane4.setViewportView(jt_gruporojo);
jPanel11.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(135, 272, 221, 158));
jt_grupoazul.setColumns(20);
jt_grupoazul.setRows(5);
jScrollPane5.setViewportView(jt_grupoazul);
jPanel11.add(jScrollPane5, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 270, 224, 158));
jl_bicolorResp.setFont(new java.awt.Font("Dialog", 0, 24)); // NOI18N
jPanel11.add(jl_bicolorResp, new org.netbeans.lib.awtextra.AbsoluteConstraints(356, 201, 228, 58));
jPanel12.setBackground(new java.awt.Color(255, 255, 255));
jLabel19.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel19.setForeground(new java.awt.Color(148, 97, 142));
jLabel19.setText("G R A F O");
javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);
jPanel12.setLayout(jPanel12Layout);
jPanel12Layout.setHorizontalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel12Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel19)
.addGap(19, 19, 19))
);
jPanel12Layout.setVerticalGroup(
jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel19, javax.swing.GroupLayout.Alignment.TRAILING)
);
jPanel11.add(jPanel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(352, 58, -1, -1));
jLabel23.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel23.setForeground(new java.awt.Color(255, 255, 255));
jLabel23.setText("B I C O L O R E A B L E");
jLabel23.setToolTipText("");
jPanel11.add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(295, 89, -1, -1));
jl_rojo.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jl_rojo.setForeground(new java.awt.Color(255, 255, 255));
jl_rojo.setText("C O L O R R O J O");
jPanel11.add(jl_rojo, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 240, -1, 23));
jl_azul.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jl_azul.setForeground(new java.awt.Color(255, 255, 255));
jl_azul.setText("C O L O R A Z U L");
jPanel11.add(jl_azul, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 240, -1, 23));
jPanel13.setBackground(new java.awt.Color(255, 255, 255));
jl_elegir3.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir3.setForeground(new java.awt.Color(148, 97, 142));
jl_elegir3.setText("E l e g i r a r c h i v o");
jl_elegir3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir3MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel13Layout = new javax.swing.GroupLayout(jPanel13);
jPanel13.setLayout(jPanel13Layout);
jPanel13Layout.setHorizontalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel13Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jl_elegir3)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel13Layout.setVerticalGroup(
jPanel13Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel13Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jl_elegir3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel11.add(jPanel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(347, 152, -1, 20));
javax.swing.GroupLayout jd_bicoloreableLayout = new javax.swing.GroupLayout(jd_bicoloreable.getContentPane());
jd_bicoloreable.getContentPane().setLayout(jd_bicoloreableLayout);
jd_bicoloreableLayout.setHorizontalGroup(
jd_bicoloreableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 869, Short.MAX_VALUE)
);
jd_bicoloreableLayout.setVerticalGroup(
jd_bicoloreableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)
);
jPanel4.setBackground(new java.awt.Color(142, 174, 189));
jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel12.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel12.setForeground(new java.awt.Color(255, 255, 255));
jLabel12.setText(" D E A R C H I V O S");
jPanel4.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(342, 100, -1, -1));
jPanel5.setBackground(new java.awt.Color(255, 255, 255));
jLabel11.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel11.setForeground(new java.awt.Color(142, 174, 189));
jLabel11.setText("<NAME>");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(24, Short.MAX_VALUE)
.addComponent(jLabel11)
.addGap(19, 19, 19))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
);
jPanel4.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(296, 69, -1, -1));
ta_original.setColumns(20);
ta_original.setFont(new java.awt.Font("Montserrat", 0, 15)); // NOI18N
ta_original.setLineWrap(true);
ta_original.setRows(5);
ta_original.setWrapStyleWord(true);
jScrollPane1.setViewportView(ta_original);
jPanel4.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 220, 270, 202));
ta_binary.setEditable(false);
ta_binary.setColumns(20);
ta_binary.setFont(new java.awt.Font("Montserrat", 0, 15)); // NOI18N
ta_binary.setLineWrap(true);
ta_binary.setRows(5);
ta_binary.setWrapStyleWord(true);
jScrollPane2.setViewportView(ta_binary);
jPanel4.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 210, 270, 202));
jLabel13.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel13.setForeground(new java.awt.Color(255, 255, 255));
jLabel13.setText("T E X T O O R I G I N A L");
jPanel4.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 190, -1, -1));
jLabel14.setFont(new java.awt.Font("Montserrat", 0, 13)); // NOI18N
jLabel14.setForeground(new java.awt.Color(255, 255, 255));
jLabel14.setText("T E X T O C O M P R I M I D O");
jPanel4.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(564, 188, -1, -1));
jp_comprimir.setBackground(new java.awt.Color(255, 255, 255));
jLabel15.setBackground(new java.awt.Color(6, 47, 79));
jLabel15.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel15.setForeground(new java.awt.Color(142, 174, 189));
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel15.setText("C O M P R I M I R");
jLabel15.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel15MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_comprimirLayout = new javax.swing.GroupLayout(jp_comprimir);
jp_comprimir.setLayout(jp_comprimirLayout);
jp_comprimirLayout.setHorizontalGroup(
jp_comprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)
);
jp_comprimirLayout.setVerticalGroup(
jp_comprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel4.add(jp_comprimir, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 460, -1, 20));
jp_descomprimir.setBackground(new java.awt.Color(255, 255, 255));
jLabel29.setBackground(new java.awt.Color(6, 47, 79));
jLabel29.setFont(new java.awt.Font("Montserrat", 1, 14)); // NOI18N
jLabel29.setForeground(new java.awt.Color(142, 174, 189));
jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel29.setText("D E S C O M P R I M I R");
jLabel29.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel29MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_descomprimirLayout = new javax.swing.GroupLayout(jp_descomprimir);
jp_descomprimir.setLayout(jp_descomprimirLayout);
jp_descomprimirLayout.setHorizontalGroup(
jp_descomprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
);
jp_descomprimirLayout.setVerticalGroup(
jp_descomprimirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel29, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
);
jPanel4.add(jp_descomprimir, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 460, -1, 20));
jp_elegir2.setBackground(new java.awt.Color(255, 255, 255));
jl_elegir2.setBackground(new java.awt.Color(6, 47, 79));
jl_elegir2.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jl_elegir2.setForeground(new java.awt.Color(142, 174, 189));
jl_elegir2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jl_elegir2.setText("E l e g i r a r c h i v o");
jl_elegir2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jl_elegir2MouseClicked(evt);
}
});
javax.swing.GroupLayout jp_elegir2Layout = new javax.swing.GroupLayout(jp_elegir2);
jp_elegir2.setLayout(jp_elegir2Layout);
jp_elegir2Layout.setHorizontalGroup(
jp_elegir2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jl_elegir2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
);
jp_elegir2Layout.setVerticalGroup(
jp_elegir2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_elegir2Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jl_elegir2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel4.add(jp_elegir2, new org.netbeans.lib.awtextra.AbsoluteConstraints(350, 160, 170, -1));
javax.swing.GroupLayout jd_compresionLayout = new javax.swing.GroupLayout(jd_compresion.getContentPane());
jd_compresion.getContentPane().setLayout(jd_compresionLayout);
jd_compresionLayout.setHorizontalGroup(
jd_compresionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jd_compresionLayout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 858, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jd_compresionLayout.setVerticalGroup(
jd_compresionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jd_compresionLayout.createSequentialGroup()
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel14.setBackground(new java.awt.Color(142, 174, 189));
jLabel26.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel26.setForeground(new java.awt.Color(240, 240, 240));
jLabel26.setText("K R U S K A L & P R I M");
jLabel26.setToolTipText("");
jLabel25.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel25.setForeground(new java.awt.Color(142, 174, 189));
jLabel25.setText("G R A F O");
javax.swing.GroupLayout jPanel15Layout = new javax.swing.GroupLayout(jPanel15);
jPanel15.setLayout(jPanel15Layout);
jPanel15Layout.setHorizontalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel15Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel25)
.addGap(19, 19, 19))
);
jPanel15Layout.setVerticalGroup(
jPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel25, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel35.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel35.setForeground(new java.awt.Color(142, 174, 189));
jLabel35.setText("E l e g i r a r c h i v o");
jLabel35.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel35MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel21Layout = new javax.swing.GroupLayout(jPanel21);
jPanel21.setLayout(jPanel21Layout);
jPanel21Layout.setHorizontalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel21Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel35)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel21Layout.setVerticalGroup(
jPanel21Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel35, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
);
ta_prim.setColumns(20);
ta_prim.setRows(5);
jScrollPane8.setViewportView(ta_prim);
javax.swing.GroupLayout jPanel14Layout = new javax.swing.GroupLayout(jPanel14);
jPanel14.setLayout(jPanel14Layout);
jPanel14Layout.setHorizontalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(304, 304, 304)
.addGroup(jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel26)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(250, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel14Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(221, 221, 221))
);
jPanel14Layout.setVerticalGroup(
jPanel14Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel14Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(jPanel15, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel26)
.addGap(68, 68, 68)
.addComponent(jPanel21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(134, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_krusprimLayout = new javax.swing.GroupLayout(jd_krusprim.getContentPane());
jd_krusprim.getContentPane().setLayout(jd_krusprimLayout);
jd_krusprimLayout.setHorizontalGroup(
jd_krusprimLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_krusprimLayout.setVerticalGroup(
jd_krusprimLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel16.setBackground(new java.awt.Color(207, 103, 102));
jPanel17.setBackground(new java.awt.Color(255, 255, 255));
jLabel27.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel27.setForeground(new java.awt.Color(207, 103, 102));
jLabel27.setText("G R A F O");
javax.swing.GroupLayout jPanel17Layout = new javax.swing.GroupLayout(jPanel17);
jPanel17.setLayout(jPanel17Layout);
jPanel17Layout.setHorizontalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel17Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel27)
.addGap(19, 19, 19))
);
jPanel17Layout.setVerticalGroup(
jPanel17Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel27, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel28.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel28.setForeground(new java.awt.Color(255, 255, 255));
jLabel28.setText("A L G O R I T M O F L O Y D");
jLabel28.setToolTipText("");
floyd_ta.setEditable(false);
floyd_ta.setColumns(20);
floyd_ta.setFont(new java.awt.Font("Montserrat", 1, 18)); // NOI18N
floyd_ta.setRows(5);
jScrollPane6.setViewportView(floyd_ta);
jPanel18.setBackground(new java.awt.Color(255, 255, 255));
jLabel31.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel31.setForeground(new java.awt.Color(207, 103, 102));
jLabel31.setText("E l e g i r a r c h i v o");
jLabel31.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel31MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel18Layout = new javax.swing.GroupLayout(jPanel18);
jPanel18.setLayout(jPanel18Layout);
jPanel18Layout.setHorizontalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel18Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel31)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel18Layout.setVerticalGroup(
jPanel18Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel31, javax.swing.GroupLayout.DEFAULT_SIZE, 19, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
jPanel16.setLayout(jPanel16Layout);
jPanel16Layout.setHorizontalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGap(172, 172, 172)
.addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel28)
.addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(182, Short.MAX_VALUE))
);
jPanel16Layout.setVerticalGroup(
jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel16Layout.createSequentialGroup()
.addGap(63, 63, 63)
.addComponent(jPanel17, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel28)
.addGap(58, 58, 58)
.addComponent(jPanel18, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(88, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_floydLayout = new javax.swing.GroupLayout(jd_floyd.getContentPane());
jd_floyd.getContentPane().setLayout(jd_floydLayout);
jd_floydLayout.setHorizontalGroup(
jd_floydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_floydLayout.setVerticalGroup(
jd_floydLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel16, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel8.setBackground(new java.awt.Color(48, 65, 93));
jLabel32.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel32.setForeground(new java.awt.Color(48, 65, 93));
jLabel32.setText("G R A F O");
javax.swing.GroupLayout jPanel19Layout = new javax.swing.GroupLayout(jPanel19);
jPanel19.setLayout(jPanel19Layout);
jPanel19Layout.setHorizontalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel19Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel32)
.addGap(19, 19, 19))
);
jPanel19Layout.setVerticalGroup(
jPanel19Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel32, javax.swing.GroupLayout.Alignment.TRAILING)
);
jLabel33.setFont(new java.awt.Font("Montserrat", 1, 24)); // NOI18N
jLabel33.setForeground(new java.awt.Color(240, 240, 240));
jLabel33.setText("A L G O R I T M O D I J K S T R A");
jLabel33.setToolTipText("");
jLabel34.setFont(new java.awt.Font("Montserrat", 1, 13)); // NOI18N
jLabel34.setForeground(new java.awt.Color(48, 65, 93));
jLabel34.setText("E l e g i r a r c h i v o");
jLabel34.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel34MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel20Layout = new javax.swing.GroupLayout(jPanel20);
jPanel20.setLayout(jPanel20Layout);
jPanel20Layout.setHorizontalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel20Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel34)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel20Layout.setVerticalGroup(
jPanel20Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel34, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
);
jt_dijkstra.setColumns(20);
jt_dijkstra.setRows(5);
jScrollPane7.setViewportView(jt_dijkstra);
jc_origen.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Origen" }));
jb_dijkstra.setText("OK");
jb_dijkstra.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jb_dijkstraMouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);
jPanel8.setLayout(jPanel8Layout);
jPanel8Layout.setHorizontalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel8Layout.createSequentialGroup()
.addContainerGap(181, Short.MAX_VALUE)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel33)
.addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(173, 173, 173))
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(180, 180, 180)
.addComponent(jPanel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(154, 154, 154)
.addComponent(jc_origen, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jb_dijkstra, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel8Layout.setVerticalGroup(
jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jPanel19, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel8Layout.createSequentialGroup()
.addComponent(jLabel33)
.addGap(62, 62, 62)
.addComponent(jPanel20, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jc_origen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jb_dijkstra)))
.addGap(27, 27, 27)
.addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(88, Short.MAX_VALUE))
);
javax.swing.GroupLayout jd_dijkstraLayout = new javax.swing.GroupLayout(jd_dijkstra.getContentPane());
jd_dijkstra.getContentPane().setLayout(jd_dijkstraLayout);
jd_dijkstraLayout.setHorizontalGroup(
jd_dijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jd_dijkstraLayout.setVerticalGroup(
jd_dijkstraLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(0, 153, 153));
setSize(new java.awt.Dimension(1000, 1000));
panel_p.setBackground(new java.awt.Color(0, 121, 107));
panel_p.setPreferredSize(new java.awt.Dimension(800, 800));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setBackground(new java.awt.Color(0, 153, 153));
jLabel1.setFont(new java.awt.Font("Montserrat", 1, 40)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 121, 107));
jLabel1.setText("T D A P R O J E C T");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(34, 34, 34))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
);
jLabel5.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("C A L C U L O D E E V A L U A C I Ó N");
jLabel5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel5MouseClicked(evt);
}
});
jLabel6.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("R E S O L U C I Ó N D E E X P R E S I O N E S M A T E M Á T I C A S");
jLabel6.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel6MouseClicked(evt);
}
});
jLabel7.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("C O M P R E S I Ó N D E A R C H I V O S D E T E X T O");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
});
jLabel8.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("G R A F O B I - C O L O R E A B L E");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
});
jLabel20.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel20.setForeground(new java.awt.Color(255, 255, 255));
jLabel20.setText("A L G O R I T M O F L O Y D");
jLabel20.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel20MouseClicked(evt);
}
});
jLabel21.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel21.setForeground(new java.awt.Color(255, 255, 255));
jLabel21.setText("A L G O R I T M O D I J K S T R A");
jLabel21.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel21MouseClicked(evt);
}
});
jLabel22.setFont(new java.awt.Font("Montserrat", 0, 18)); // NOI18N
jLabel22.setForeground(new java.awt.Color(255, 255, 255));
jLabel22.setText("<NAME> Y P R I M");
jLabel22.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel22MouseClicked(evt);
}
});
javax.swing.GroupLayout panel_pLayout = new javax.swing.GroupLayout(panel_p);
panel_p.setLayout(panel_pLayout);
panel_pLayout.setHorizontalGroup(
panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_pLayout.createSequentialGroup()
.addContainerGap(190, Short.MAX_VALUE)
.addGroup(panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel5)
.addComponent(jLabel8)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel20)
.addComponent(jLabel21)
.addComponent(jLabel22))
.addContainerGap(190, Short.MAX_VALUE))
);
panel_pLayout.setVerticalGroup(
panel_pLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_pLayout.createSequentialGroup()
.addGap(90, 90, 90)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(60, 60, 60)
.addComponent(jLabel5)
.addGap(40, 40, 40)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(40, 40, 40)
.addComponent(jLabel7)
.addGap(40, 40, 40)
.addComponent(jLabel8)
.addGap(40, 40, 40)
.addComponent(jLabel20)
.addGap(40, 40, 40)
.addComponent(jLabel21)
.addGap(40, 40, 40)
.addComponent(jLabel22)
.addContainerGap(70, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_p, javax.swing.GroupLayout.DEFAULT_SIZE, 990, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_p, javax.swing.GroupLayout.DEFAULT_SIZE, 650, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void bt_goActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_goActionPerformed
// TODO add your handling code here:
save();
}//GEN-LAST:event_bt_goActionPerformed
private void TF_compresionKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TF_compresionKeyPressed
if (evt.getKeyCode() == 13) {
save();
}
}//GEN-LAST:event_TF_compresionKeyPressed
private void jLabel5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel5MouseClicked
// TODO add your handling code here:
/*adminPerson ap = new adminPerson("./personas.txt");
ap.cargarArchivo();
Person p = new Person("Juan", 20);
ap.setPerson(p);
ap.escribirArchivo();
*/
ta_evaluacion.setText("");
jd_desempeno.pack();
jd_desempeno.setLocationRelativeTo(null);
jd_desempeno.setVisible(true);
/*for (int i = 0; i < ap.getListaPersonas().size(); i++) {
//cb_empleados.addItem(ap.getListaPersonas().get(i).getName());
}*/
}//GEN-LAST:event_jLabel5MouseClicked
private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
jd_compresion.pack();
jd_compresion.setLocationRelativeTo(null);
jd_compresion.setVisible(true);
}//GEN-LAST:event_jLabel7MouseClicked
private void jLabel6MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel6MouseClicked
// TODO add your handling code here:
jd_resolucion.pack();
jd_resolucion.setLocationRelativeTo(null);
jd_resolucion.setVisible(true);
}//GEN-LAST:event_jLabel6MouseClicked
private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
// TODO add your handling code here:
JDialog dialog = new JDialog();
if (ta_original.getText() == "") {
JLabel label1 = new JLabel("Por favor escribir en el text area");
dialog.add(label1);
} else {
Huffman huff = new Huffman();
String texto = ta_original.getText();
System.out.println(texto);
huff.HuffCompress(texto);
ta_original.setText("");
JLabel label2 = new JLabel("Archivo de texto comprimido exitosamente");
dialog.add(label2);
}
dialog.setLocationRelativeTo(null);
dialog.setTitle("Importante");
dialog.pack();
}//GEN-LAST:event_jLabel15MouseClicked
private void tf_mathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_mathActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tf_mathActionPerformed
private void jl_elegir1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir1MouseClicked
// TODO add your handling code here:
/*
Person p = new Person("Andre");
TreeNode root = new TreeNode(p);
TreeNode n = new TreeNode(new Person("Mario"));
TreeNode n2 = new TreeNode(new Person("Calvin", 5));
root.addTreeNode(n);
root.addTreeNode(n2);
root.addTreeNode(new TreeNode(new Person("Jorge", 8)));
TreeNode tn2 = new TreeNode(new Person("Carlos", 5));
TreeNode tn3 = new TreeNode(new Person("Jose"));
n.addTreeNode(tn2);
n.addTreeNode(tn3);
tn3.addTreeNode(new TreeNode(new Person("Karl", 10)));
tn3.addTreeNode(new TreeNode(new Person("Bart", 20)));
tn3.addTreeNode(new TreeNode(new Person("James", 6)));
*/
pathTree = load();
tf_pathtree.setText(pathTree);
TreeNode root;
try {
this.ta_evaluacion.setText("");
root = createTree(pathTree);
this.ta_evaluacion.setText("Evaluacion: " + root.evaluarTree(root));
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
/*
try {
node = createTree(pathTree);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
*/
//root.evaluarPOrden(root);
/*ArrayList<TreeNode> postorder = root.getPostOrder(root);
for (int i = 0; i < postorder.size(); i++) {
ta_evaluacion.append(i + ". " + postorder.get(i).getPersona().getName() + ": " + postorder.get(i).getPersona().getEvaluation() + "\n");
}*/
}//GEN-LAST:event_jl_elegir1MouseClicked
private void jLabel17MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel17MouseClicked
// TODO add your handling code here:
String str = tf_math.getText();
if(!tf_math.getText().isEmpty()/* || isDigit(tf_math.getText())*/){
//String s = " (4/2* 3*4) +(10/5)^2";
//String infix = "5-5";
String s2 = str.replaceAll(" ", "");
String format = "";
StringTokenizer st = new StringTokenizer(s2, "+*/-()^", true);
while (st.hasMoreTokens()) {
format += st.nextToken() + " ";
}
System.out.println("");
System.out.println("Format: " + format);
System.out.println("");
String[] finalinfix = infixtoPostfix(format.split(" "));
System.out.println("Infix to Postfix: " + Arrays.toString(finalinfix) + "\n");
BinTree bt = postf_toTree(finalinfix);
Double respuesta = bt.evaluar(bt);
bt.inorden(bt);
System.out.print(" = " + respuesta);
System.out.println("");
jl_answer.setText(Double.toString(respuesta));
}else{
JOptionPane.showMessageDialog(this.jd_resolucion, "Error");
}
}//GEN-LAST:event_jLabel17MouseClicked
private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
jt_gruporojo.setVisible(false);
jt_grupoazul.setVisible(false);
jl_rojo.setVisible(false);
jl_azul.setVisible(false);
jd_bicoloreable.pack();
jd_bicoloreable.setLocationRelativeTo(null);
jd_bicoloreable.setVisible(true);
}//GEN-LAST:event_jLabel8MouseClicked
private void jl_elegir3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir3MouseClicked
this.jt_gruporojo.setText("");
this.jt_grupoazul.setText("");
pathGrafo = load();
//tf_pathtree.setText(pathTree);
GrafoMatriz g;
try {
g = createMatriz(pathGrafo, true);
System.out.println("Nodos adyacentes: \n");
for (int i = 0; i < g.getMatrizAdy().length; i++) {
g.imprimirNodosAdy(i);
}
System.out.println("");
System.out.println("Matriz de adyacencia: \n");
g.imprimirMatrizAdy();
System.out.println("");
boolean bipartito = false;
/*para ver si es bipartito desde cualquier origen
for (int i = 0; i < g.getMatrizAdy().length; i++) {
this.jt_grupoazul.setText("");
this.jt_gruporojo.setText("");
ArrayList<String> colores = g.DFSbipartito(i);
if(g.isBicoloreable()){
System.out.println("es bicoloreable en " + i);
for (int j = 0; j < colores.size(); j++) {
if (colores.get(j).equals("azul")) {
jt_grupoazul.append(Integer.toString(j) + "\n");
} else {
jt_gruporojo.append(Integer.toString(j) + "\n");
}
}
bipartito = true;
break;
}
System.out.println("");
}*/
ArrayList<String> colores = g.DFSbipartito(0);
if (g.isBicoloreable()) {
bipartito = true;
for (int j = 0; j < colores.size(); j++) {
if (colores.get(j).equals("azul")) {
jt_grupoazul.append(Integer.toString(j) + "\n");
} else {
jt_gruporojo.append(Integer.toString(j) + "\n");
}
}
}
//ArrayList<String> coloress = g.DFSbipartito(0);//es bicoloreable desde origen 0?
/*if (g.isBicoloreable()) {
for (int i = 0; i < coloress.size(); i++) {
if (coloress.get(i).equals("azul")) {
jt_grupoazul.append(Integer.toString(i) + "\n");
} else {
jt_gruporojo.append(Integer.toString(i) + "\n");
}
}
}*/
//ArrayList<String> colores = g.Bicoloreable(0);
//System.out.println("Size: " + colores.size());
jl_bicolorResp.setText(bipartito == true ? ("Bi-coloreable!") : ("No es bi-coloreable desde el origen"));
jt_gruporojo.setVisible(true);
jt_grupoazul.setVisible(true);
jl_rojo.setVisible(true);
jl_azul.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jl_elegir3MouseClicked
private void jLabel29MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel29MouseClicked
// TODO add your handling code here:
String bin = binary.get(0).toString() + "0";
System.out.println("");
System.out.println(bin);
BinTree raiz = huff.HuffDecompress(binary);
String tex = DecomText(raiz, raiz, bin, "", 0);
ta_original.setText(this.text);
}//GEN-LAST:event_jLabel29MouseClicked
private void jl_elegir2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jl_elegir2MouseClicked
// TODO add your handling code here:
String path = load();
binary = huff.read(path);
this.text = "";
this.decompressed = false;
ta_binary.setText(binary.get(0).toString());
}//GEN-LAST:event_jl_elegir2MouseClicked
private void jLabel31MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel31MouseClicked
// TODO add your handling code here:
String path = load();
FloydMayweather fm = new FloydMayweather();
floyd_ta.setText("");
try {
String texto = fm.Floyd(path);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
floyd_ta.setText(fm.getText());
// floyd_ta.setText("");
floyd_ta.updateUI();
// String path = load();
/* GrafoMatriz grafo;
try {
grafo = createMatriz(path, false);
Floyd floyd = new Floyd(grafo);
double[][] distancias = floyd.distanciaTodosLosDestinos();
for (int i = 0; i < distancias.length; i++) {
for (int j = 0; j < distancias.length; j++) {
if (j < distancias.length - 1) {
floyd_ta.append(distancias[i][j] + "\t");
} else {
floyd_ta.append(distancias[i][j] + "");
}
}
floyd_ta.append("\n");
}
//floyd_ta.updateUI();
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}*/
}//GEN-LAST:event_jLabel31MouseClicked
private void jLabel20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel20MouseClicked
// TODO add your handling code here:
jd_floyd.pack();
jd_floyd.setLocationRelativeTo(null);
jd_floyd.setVisible(true);
}//GEN-LAST:event_jLabel20MouseClicked
private void jLabel21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel21MouseClicked
// TODO add your handling code here:
jd_dijkstra.pack();
jd_dijkstra.setLocationRelativeTo(null);
jd_dijkstra.setVisible(true);
}//GEN-LAST:event_jLabel21MouseClicked
private void jLabel22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel22MouseClicked
// TODO add your handling code here:
jd_krusprim.pack();
jd_krusprim.setLocationRelativeTo(null);
jd_krusprim.setVisible(true);
// prim = new PrimTest2();
}//GEN-LAST:event_jLabel22MouseClicked
private void jLabel34MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel34MouseClicked
jt_dijkstra.setText("");
pathGrafo = load();
jc_origen.removeAllItems();
try {
Grafo g = createGrafoAdj(pathGrafo);
actual = g;
Object[] origen = new Object[g.getNodos().size()];
for (int i = 0; i < origen.length; i++) {
jc_origen.addItem(Integer.toString(i));
//posibilities[i-1] = i;
}
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
//tf_pathtree.setText(pathTree);
}//GEN-LAST:event_jLabel34MouseClicked
private void jLabel35MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel35MouseClicked
// TODO add your handling code here:
String path = load();
//PrimTest2 prim = new PrimTest2();
try {
ta_prim.setText("");
GrafoMatriz mat = createMatriz(path, false);
Prim prim = new Prim(mat.getMatrizAdy());
ArrayList<int[]> aristas = prim.prim(0);
Double cost = 0.0;
for (int i = 0; i < aristas.size(); i++) {
ta_prim.append(aristas.get(i)[0] + " -> " + aristas.get(i)[1] + " : " + aristas.get(i)[2] + "\n");
cost += aristas.get(i)[2];
}
ta_prim.append("\ncosto: " + cost);
//PrimTest2.Prim(path);
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
//KruskalTest kruskal = new KruskalTest();
KruskalTest.Krusky(path);
/*
path = load();
Grafo g;
try {
g = createGrafoAdj(path);
Prim krusk = new Prim(g);
krusk.kruskal();
} catch (IOException ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}*/
}//GEN-LAST:event_jLabel35MouseClicked
private void jb_dijkstraMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jb_dijkstraMouseClicked
Grafo g;
this.jt_dijkstra.setText("");
try {
g = actual;
//System.out.println("cant nodos: " + g.getNodos().size());
for (int i = 0; i < g.getNodos().size(); i++) {
System.out.println(g.getNodos().get(i).printNodosAdy());
}
Grafo copia = g;
Dijkstra dijkstra = new Dijkstra(copia, g.getNodos().get(jc_origen.getSelectedIndex()));
//Map<Nodo, Double> distanciass = dijkstra.DijkstraFinal();
Map<Nodo, Double> dist = dijkstra.dijkstra();
//System.out.println("dinstancia final\n");
for (Entry<Nodo, Double> distancia : dist.entrySet()) {
Nodo n = distancia.getKey();
double d = distancia.getValue();
this.jt_dijkstra.append(dijkstra.origen.getId() + " -> " + n.getId() + ": " + d + "\n");
//System.out.println(dijkstra.origen.getId() + " -> " + n.getId() + ": " + d);
}
/*System.out.println("SIZE: " +dist.size());
for (int i = 0; i < dist.size(); i++) {
System.out.println("distancia: " + dist.get(i));
}*/
} catch (Exception ex) {
Logger.getLogger(GUIProject.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jb_dijkstraMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUIProject.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUIProject().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea floyd_ta;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
private javax.swing.JLabel jLabel27;
private javax.swing.JLabel jLabel28;
private javax.swing.JLabel jLabel29;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel31;
private javax.swing.JLabel jLabel32;
private javax.swing.JLabel jLabel33;
private javax.swing.JLabel jLabel34;
private javax.swing.JLabel jLabel35;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel20;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JButton jb_dijkstra;
private javax.swing.JComboBox<String> jc_origen;
private javax.swing.JDialog jd_bicoloreable;
private javax.swing.JDialog jd_compresion;
private javax.swing.JDialog jd_desempeno;
private javax.swing.JDialog jd_dijkstra;
private javax.swing.JDialog jd_floyd;
private javax.swing.JDialog jd_krusprim;
private javax.swing.JDialog jd_resolucion;
private javax.swing.JLabel jl_answer;
private javax.swing.JLabel jl_azul;
private javax.swing.JLabel jl_bicolorResp;
private javax.swing.JLabel jl_elegir1;
private javax.swing.JLabel jl_elegir2;
private javax.swing.JLabel jl_elegir3;
private javax.swing.JLabel jl_rojo;
private javax.swing.JPanel jp_comprimir;
private javax.swing.JPanel jp_descomprimir;
private javax.swing.JPanel jp_elegir2;
private javax.swing.JTextArea jt_dijkstra;
private javax.swing.JTextArea jt_grupoazul;
private javax.swing.JTextArea jt_gruporojo;
private javax.swing.JPanel panel_p;
private javax.swing.JTextArea ta_binary;
private javax.swing.JTextArea ta_evaluacion;
private javax.swing.JTextArea ta_original;
private javax.swing.JTextArea ta_prim;
private javax.swing.JTextField tf_math;
private javax.swing.JTextField tf_pathtree;
// End of variables declaration//GEN-END:variables
private String pathTree;
private String pathGrafo;
private ArrayList binary;
private Huffman huff = new Huffman();
private boolean decompressed;
private String text;
private TreeNode foundTree = null;
Grafo actual = null;
public void save() {
// String texto = TF_compresion.getText();
File archiv = null;
FileWriter fw = null;
BufferedWriter bw = null;
try {
archiv = new File("./compresion.txt");
fw = new FileWriter(archiv, true);
//si el archivo no existe lo crea y si ya existe los sobreescribe (al menos que append
bw = new BufferedWriter(fw);
// bw.write(texto);
bw.flush();
} catch (Exception e) {
e.printStackTrace();
}
try {
//primero se borra el buffer
bw.close();
fw.close();
} catch (Exception e) {
}
}
public String load() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos .txt", "txt");
fileChooser.setFileFilter(filtro);
int seleccion = fileChooser.showOpenDialog(this);
if (seleccion == JFileChooser.APPROVE_OPTION) {
File dir = fileChooser.getSelectedFile();
System.out.println(dir.getPath());
return dir.getPath();
} else {
return null;
}
}
public TreeNode treeExists(int n, TreeNode nodo) {
if (nodo != null) {
for (int i = 0; i < nodo.getChildren().size(); i++) {
treeExists(n, nodo.getChildren().get(i));
}
if (nodo.getNumNodo() == n) {
return nodo;
} else {
return null;
}
}
return null;
}
public static String[] infixtoPostfix(String[] infix) {
Stack<String> s = new Stack();
StringBuilder sb = new StringBuilder();
for (String infix1 : infix) {
if (infix1.equals(" ")) {//si hay un espacio no hace nada
} else if (isDigit(infix1)) {//si infix[i] o infix1 es un digito, se agrega directamente al stringbuilder
//System.out.println("agregando " + infix1 + " al strigbuilder");
sb.append(infix1).append(" ");
} else if (isOperator(infix1)) {//si es operador verifica que el stack no este vacio y la precedencia mas alta
while (!s.isEmpty() && !s.peek().equals("(") && precedenciaMasAlta(s.peek(), infix1)) {
//String operador = s.pop();
sb.append(s.pop()/*operador*/).append(" ");
//System.out.println("agregando operador: " + operador + "al string builder");
}
s.push(infix1);
} else if (infix1.equals("(")) {//si encuentra un "(" se agrega al stack
//System.out.println("agregando ( al stack");
s.push(infix1);
} else if (infix1.equals(")")) {//no se agrega al stack pero elimina el primer parentesis "(" encontrado y agrega los operadores al string final
//System.out.println("encontro )");
while (!s.empty() && !s.peek().equals("(")) {
//String operador = s.pop();
//System.out.println("agregando operador: " + operador + "al stringbuilder");
sb.append(s.pop()/*operador*/).append(" ");
}
s.pop();//se saca el parentesis "("
//System.out.println("sacando ( del stack");
}
}
while (!s.isEmpty()) {
//String remaining = s.pop();
//System.out.println("agregando del while " + remaining);
sb.append(s.pop()/*remaining*/).append(" ");
}
String[] sFinal = sb.toString().split(" ");
return sFinal;
}
public static BinTree postf_toTree(String[] s/*recibe un arreglo de la expresion en postfix*/) {
Stack<BinTree> stackTree = new Stack();//aqui se van armando los arboles, el ultimo nodo que quede (stackTree.pop()) va a ser el arbol final
for (int i = 0; i < s.length; i++) {
if (isDigit(s[i])) {
stackTree.push(new BinTree(s[i]));
} else {//si no es un digito se crea un nuevo arbol, la raiz es el operados y los hijos (hojas) son los numeros o un arbol operador ya armado
BinTree nodoOperador = new BinTree(s[i]);
BinTree nodoR = stackTree.pop();
BinTree nodoL = stackTree.pop();
nodoOperador.insertRNode(nodoR);
nodoOperador.insertLNode(nodoL);
stackTree.push(nodoOperador);
System.out.println("Padre: " + nodoOperador.getInfo());
System.out.println("Left node: " + nodoOperador.getLNode().getInfo());
System.out.println("Right node: " + nodoOperador.getRNode().getInfo());
System.out.println("");
}
//b.postfixTree(s[i], stackTree);
}
return stackTree.pop();//el ultimo nodo que quede en el stack es el arbol completo
}
public static boolean isDigit(String s) {
return Character.isDigit(s.charAt(0));
}
public static boolean isOperator(String s) {
return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/") || s.equals("^") || s.equals("!");
}
public static int Precedencia(String s) {
int pre = 0;
if (s.equals("+") || s.equals("-")) {
pre = 1;
}
if (s.equals("*") || s.equals("/")) {
pre = 2;
}
if (s.equals("^")) {
pre = 3;
}
return pre;
}
public static boolean precedenciaMasAlta(String s, String s2) {
int prec = Precedencia(s);
int prec2 = Precedencia(s2);
if (prec == prec2) {
if (s.equals("^")) {//if(Associative(s))
return false;
} else {
return true;
}
} else {
if (prec > prec2) {
return true;
}
}
return false;
}
public GrafoMatriz createMatriz(String path, boolean dirigido) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
GrafoMatriz g;
ArrayList<String[]> info = new ArrayList();
try {
String line = br.readLine();
//int[][] matriz = new int[5][5];
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
//System.out.println(Arrays.toString(s.split(",")));
line = br.readLine();
}
for (int i = 0; i < info.size(); i++) {
System.out.println(Arrays.toString(info.get(i)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
g = new GrafoMatriz(info.size(), dirigido);
double[][] matriz = new double[info.size()][info.size()];
for (int i = 0; i < info.size(); i++) {
for (int j = 0; j < info.size(); j++) {
matriz[i][j] = Double.parseDouble(info.get(i)[j]);
System.out.print(info.get(i)[j] + " ");
}
System.out.println("");
}
g.setMatrizAdy(matriz);
//System.out.println(g.isBicoloreable());
return g;
}
public String DecomText(BinTree raiz, BinTree node, String binary, String text, int x) {
System.out.println("");
System.out.println("x: " + x);
System.out.println("length: " + binary.length());
System.out.println("TEXT: " + text);
this.text = text;
if (x >= binary.length()) {
//text = text.concat(node.getInfo());
decompressed = true;
return text;
}
if (!decompressed && x < binary.length()) {
if (binary.charAt(x) == '0' && !node.isLeaf(node)) {
DecomText(raiz, node.getLNode(), binary, text, x + 1);
} else if (binary.charAt(x) == '0' && node.isLeaf(node)) {
text = text.concat(node.getInfo());
DecomText(raiz, raiz, binary, text, x);
}
if (binary.charAt(x) == '1' && !node.isLeaf(node)) {
DecomText(raiz, node.getRNode(), binary, text, x + 1);
} else if (binary.charAt(x) == '1' && node.isLeaf(node)) {
text = text.concat(node.getInfo());
DecomText(raiz, raiz, binary, text, x);
}
}
return text;
}
public TreeNode createTree(String path) throws IOException {
TreeNode rootTree = new TreeNode();
BufferedReader br = new BufferedReader(new FileReader(path));
try {
String line = br.readLine();
ArrayList<String[]> info = new ArrayList();
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
System.out.println(Arrays.toString(line.split(",")));
line = br.readLine();
}
ArrayList<Integer> nodosUnicos = new ArrayList();
rootTree = null;
ArrayList<TreeNode> padreNotFoundNodo = new ArrayList();
ArrayList<Integer> padreNotFoundPadre = new ArrayList();
ArrayList<Integer> padres = new ArrayList();
for (int i = 0; i < info.size(); i++) {
int numeroNodo = Integer.parseInt(info.get(i)[0]);
int padre = Integer.parseInt(info.get(i)[1]);
double evaluacion = Integer.parseInt(info.get(i)[2]);
if (padre == -1) {
rootTree = new TreeNode(numeroNodo, evaluacion);
}
}
for (int i = 0; i < info.size(); i++) {
int numeroNodo = Integer.parseInt(info.get(i)[0]);
//System.out.println("Num Nodo: " + numeroNodo);
if (!nodosUnicos.contains(numeroNodo)) {
nodosUnicos.add(numeroNodo);
int padre = Integer.parseInt(info.get(i)[1]);
//System.out.println("Padre: " + padre);
double evaluacion = Integer.parseInt(info.get(i)[2]);
if (padre != -1) {
TreeNode p = findPadre(rootTree, padre);
p = foundTree;
if (foundTree != null/*!existe.contains(padre)*/) {
TreeNode hijo = new TreeNode(numeroNodo, evaluacion);
//System.out.println("n padre: " + foundTree.getNumNodo() + "\n");
p.addTreeNode(hijo);
//mapaarbol.put(hijo, new ArrayList());
} else {
//padreNotFound.put(new TreeNode(numeroNodo, evaluacion), padre);
padreNotFoundNodo.add(new TreeNode(numeroNodo, evaluacion));
padreNotFoundPadre.add(padre);
/*for (Entry<TreeNode, ArrayList<TreeNode>> mapa : mapaarbol.entrySet()) {
if (mapa.getKey().getNumNodo() == padre) {
mapa.getValue().add(new TreeNode(numeroNodo, evaluacion));
}
}*/
}
}
if (!padres.contains(padre)) {
padres.add(padre);
}
}
foundTree = null;
//if(treeExists)
/*if (treeExists(hijo, rootTree) == null) {
System.out.println("no existe nodo");
//TreeNode nuevoNodo = new TreeNode(numeroNodo)
}*/
}
/*/for (Entry<TreeNode, ArrayList<TreeNode>> map : mapaarbol.entrySet()) {
System.out.println(map.getKey().getNumNodo() + ": ");
StringBuilder sb = new StringBuilder();
System.out.println("size: " + map.getValue().size());
for (TreeNode nodo : map.getValue()) {
sb.append(nodo.getNumNodo()).append(", ");
}
System.out.print(sb.toString());
}*/
for (int i = 0; i < padreNotFoundNodo.size(); i++) {
if (!nodosUnicos.contains(padreNotFoundPadre.get(i))) {
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
}
}
while (!padreNotFoundNodo.isEmpty()) {
for (int i = 0; i < padreNotFoundNodo.size(); i++) {
TreeNode nodo = padreNotFoundNodo.get(i);
TreeNode padre = findPadre(rootTree, padreNotFoundPadre.get(i));
padre = foundTree;
if (!padres.contains(padreNotFoundPadre.get(i))) {
System.out.println("No se encontro padre de nodo" + nodo.getNumNodo());
//padreNotFound.remove(nodo, notFound.getValue());
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
} else if (padre != null) {
//System.out.println("padre de " + nodo.getNumNodo() + ": " + padreNotFoundPadre.get(i));
padre.addTreeNode(nodo);
padreNotFoundNodo.remove(i);
padreNotFoundPadre.remove(i);
//padreNotFound.remove(nodo, notFound.getValue());
}
foundTree = null;
}
}
//cont++;
//rootTree.Evaluar();
System.out.println("Evaluacion: " + rootTree.evaluarTree(rootTree));
} catch (IOException e) {
} finally {
br.close();
}
return rootTree;
}
public TreeNode findPadre(TreeNode raiz, int n) {
TreeNode find = null;
for (int i = 0; i < raiz.getChildren().size(); i++) {
find = findPadre(raiz.getChildren().get(i), n);
}
if (n == raiz.getNumNodo()) {
find = raiz;
//System.out.println("returned " + raiz.getNumNodo());
foundTree = raiz;
return find;
}
if (foundTree == null) {
return null;
} else {
return find;
}
}
public Grafo createGrafoAdj(String path) throws FileNotFoundException, IOException {
Grafo g = new Grafo();
BufferedReader br = new BufferedReader(new FileReader(path));
ArrayList<String[]> info = new ArrayList();
try {
String line = br.readLine();
//int[][] matriz = new int[5][5];
while (line != null) {
String s = line.replaceAll(" ", "");
info.add(s.split(","));
//String[] x = info.get(info.size()-1);
/*for(String s : x){
s = s.replaceAll(" ", "");
}*/
// System.out.println(Arrays.toString(s.split(",")));
line = br.readLine();
}
for (int i = 0; i < info.size(); i++) {
System.out.println(Arrays.toString(info.get(i)));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
br.close();
}
System.out.println("");
ArrayList<Nodo> nodos = new ArrayList();
for (int i = 0; i < info.size(); i++) {
nodos.add(new Nodo(Integer.toString(i)));
}
for (int i = 0; i < info.size(); i++) {
for (int j = 0; j < info.size(); j++) {
if (Integer.parseInt(info.get(i)[j]) != 0) {
nodos.get(i).agregarArista(nodos.get(j), Double.parseDouble(info.get(i)[j]));
//n.getNodosAdyacentes().add(new Nodo(Integer.toString(j)));
//n.getPesoAdyacente().add(Double.parseDouble(info.get(i)[j]));
}
}
g.agregarNodo(nodos.get(i));
}
return g;
}
}
| 95,433 | 0.612673 | 0.585904 | 2,074 | 45.019287 | 33.622566 | 166 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.878496 | false | false | 9 |
281522730cf2be4734942aac6dd5e4e0b8ecab5c | 32,908,039,451,224 | 7aa9e8dedc121f1a35f514f01c73c0c152f4d90d | /app/src/main/java/com/kershaw/springboot/controller/DealSetupController.java | c739e5f8048ddc9899cb1c7535e1a6b594d8680e | [] | no_license | lovepreet007/karshaw | https://github.com/lovepreet007/karshaw | e6ab054e07a6986249dcf49e0039bc45e1d8e5a8 | 670b696ffe8c3588948d4ebf61fd02af452a725e | refs/heads/master | 2020-12-03T01:56:53.242000 | 2017-06-30T12:15:03 | 2017-06-30T12:15:03 | 95,884,944 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.kershaw.springboot.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.kershaw.springboot.constant.ConstantValue;
import com.kershaw.springboot.model.Deal;
import com.kershaw.springboot.model.Loan;
import com.kershaw.springboot.model.PriorityType;
import com.kershaw.springboot.model.Review;
import com.kershaw.springboot.service.DealService;
import com.kershaw.springboot.util.CustomErrorType;
import com.kershaw.springboot.vo.LoanVO;
import com.kershaw.springboot.vo.TaskDetailsVO;
@RestController
@RequestMapping("/deal")
public class DealSetupController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private DealService dealService;
@Autowired
private RuntimeService runtimeService;
@Autowired
private ProcessEngineConfiguration processEngine;
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/createDeal", method = RequestMethod.POST, consumes="application/json")
public ResponseEntity<?> createDeal(@RequestBody Deal deal) {
List<Review> list = new ArrayList<>();
if (deal.getReviewDeal() == null || deal.getReviewDeal().size() == 0) {
logger.error("Review Type should not be empty or null");
return new ResponseEntity(new CustomErrorType("Review deal should not be empty or null"),
HttpStatus.BAD_REQUEST);
}
for (int i = 0; i < deal.getReviewDeal().size(); i++) {
list.addAll(this.dealService.getReviewType(deal.getReviewDeal().get(i).getReviewType()));
}
if(deal.getStatus() == null) {
deal.setStatus(ConstantValue.statusNew);
}
deal.setReviewDeal(list);
deal.setStatus(ConstantValue.statusPending);
Deal deals = null;
try {
deals = this.dealService.saveDealSetUp(deal);
} catch (Exception e) {
logger.error("Failed to create deal");
return new ResponseEntity(new CustomErrorType("Unable to create deal " + e.getMessage()),
HttpStatus.BAD_REQUEST);
}
Deal currentDeal = new Deal();
currentDeal.setDealId(deals.getDealId());
currentDeal.setClientName(deals.getClientName());
currentDeal.setDealName(deals.getDealName());
return new ResponseEntity<Deal>(currentDeal, HttpStatus.OK);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/reviewType", method = RequestMethod.GET)
public ResponseEntity<List<String>> getAllReviewType() {
List<Review> reviews = dealService.findAllReviews();
if (CollectionUtils.isEmpty(reviews)) {
logger.error("not found review type");
return new ResponseEntity(new CustomErrorType("not found review type"), HttpStatus.NO_CONTENT);
}
List<String> reviewTypes = reviews.stream().map(x -> x.getReviewType()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(reviewTypes)) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<String>>(reviewTypes, HttpStatus.OK);
}
@RequestMapping(value = "/priorityType", method = RequestMethod.GET)
public ResponseEntity<List<PriorityType>> getPriorityType() {
List<PriorityType> lists = new ArrayList<PriorityType>();
for (PriorityType status : PriorityType.values()) {
lists.add(status);
}
return new ResponseEntity<List<PriorityType>>(lists, HttpStatus.OK);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/createLoan", method = RequestMethod.POST)
public ResponseEntity<String> createLoan(@RequestBody List<LoanVO> loanVos) {
List<Loan> loans = new ArrayList<>();
for (LoanVO loanvo : loanVos) {
Loan loan = new Loan();
loan.setLoanId(loanvo.getLoanId());
loan.setBorrowerName(loanvo.getBorrowerName());
loan.setLoanAmount(loanvo.getLoanAmount());
loan.setLoanType(loanvo.getLoanType());
loan.setSsn(loanvo.getSsn());
Deal deal =dealService.findDealByDealId(loanvo.getDealId());
deal.setDealId(loanvo.getDealId());
loan.setDeal(deal);
loans.add(loan);
}
if (this.dealService.isLoanExist(loans)) {
logger.error("Unable to create. A Loan with id already exist.");
return new ResponseEntity(new CustomErrorType("Unable to create. A Loan with id already exist."),
HttpStatus.CONFLICT);
}
for (int i = 0; i < loanVos.size(); i++) {
List<String> list = this.dealService.getReviewType(loanVos.get(i).getDealId());
Map<String, Object> vars = Collections.<String, Object>singletonMap("loan", loans.get(i));
ProcessInstance pi = runtimeService.startProcessInstanceByKey("userAssign", vars);
loans.get(i).setProcess_inst_id(pi.getId());
}
try {
this.dealService.saveLoan(loans);
} catch (Exception e) {
logger.error("Unable to create loan.");
return new ResponseEntity(new CustomErrorType("Unable to create loan."), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<String>("Saved Loans", HttpStatus.OK);
}
@RequestMapping(value = "/getTaskDashboard", method = RequestMethod.GET)
public ResponseEntity<List<TaskDetailsVO>> getAllTaskDashboard() {
List<TaskDetailsVO> listTaskDetails = this.dealService.getAllTaskDashboard();
return new ResponseEntity<List<TaskDetailsVO>>(listTaskDetails, HttpStatus.OK);
}
@RequestMapping(value = "/getTaskDetails", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<List<TaskDetailsVO>> getTaskDtailsById(@RequestBody TaskDetailsVO taskDetailsVO) {
List<TaskDetailsVO> listTaskDetails = this.dealService.getTaskDtailsById(taskDetailsVO.getLoanId(),
taskDetailsVO.getTaskName());
String currentTaskName = listTaskDetails.get(0).getTaskName();
String[] task = currentTaskName.split("_");
String description = task[1] + " Loan#" + listTaskDetails.get(0).getLoanId() + " of Deal ID CLY00"
+ listTaskDetails.get(0).getDealId() + " for Review Type " + task[0];
listTaskDetails.get(0).setTaskName(task[1]);
listTaskDetails.get(0).setDescription(description);
return new ResponseEntity<List<TaskDetailsVO>>(listTaskDetails, HttpStatus.OK);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/completeTask", method = RequestMethod.POST)
public ResponseEntity<?> completeTask(@RequestBody TaskDetailsVO taskDetailsVO) {
TaskService taskService = processEngine.getTaskService();
if (this.dealService.isTaskExist(taskDetailsVO.getTaskId())) {
taskService.complete(taskDetailsVO.getTaskId());
return new ResponseEntity<TaskDetailsVO>(taskDetailsVO, HttpStatus.OK);
} else {
logger.error("Task id :- "+taskDetailsVO.getTaskId()+ "already completeed found");
return new ResponseEntity(
new CustomErrorType(
"Unable to Complete Task with id " + taskDetailsVO.getTaskId() + "Found completed."),
HttpStatus.NOT_FOUND);
}
}
}
| UTF-8 | Java | 7,469 | java | DealSetupController.java | Java | [] | null | [] | package com.kershaw.springboot.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.kershaw.springboot.constant.ConstantValue;
import com.kershaw.springboot.model.Deal;
import com.kershaw.springboot.model.Loan;
import com.kershaw.springboot.model.PriorityType;
import com.kershaw.springboot.model.Review;
import com.kershaw.springboot.service.DealService;
import com.kershaw.springboot.util.CustomErrorType;
import com.kershaw.springboot.vo.LoanVO;
import com.kershaw.springboot.vo.TaskDetailsVO;
@RestController
@RequestMapping("/deal")
public class DealSetupController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private DealService dealService;
@Autowired
private RuntimeService runtimeService;
@Autowired
private ProcessEngineConfiguration processEngine;
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/createDeal", method = RequestMethod.POST, consumes="application/json")
public ResponseEntity<?> createDeal(@RequestBody Deal deal) {
List<Review> list = new ArrayList<>();
if (deal.getReviewDeal() == null || deal.getReviewDeal().size() == 0) {
logger.error("Review Type should not be empty or null");
return new ResponseEntity(new CustomErrorType("Review deal should not be empty or null"),
HttpStatus.BAD_REQUEST);
}
for (int i = 0; i < deal.getReviewDeal().size(); i++) {
list.addAll(this.dealService.getReviewType(deal.getReviewDeal().get(i).getReviewType()));
}
if(deal.getStatus() == null) {
deal.setStatus(ConstantValue.statusNew);
}
deal.setReviewDeal(list);
deal.setStatus(ConstantValue.statusPending);
Deal deals = null;
try {
deals = this.dealService.saveDealSetUp(deal);
} catch (Exception e) {
logger.error("Failed to create deal");
return new ResponseEntity(new CustomErrorType("Unable to create deal " + e.getMessage()),
HttpStatus.BAD_REQUEST);
}
Deal currentDeal = new Deal();
currentDeal.setDealId(deals.getDealId());
currentDeal.setClientName(deals.getClientName());
currentDeal.setDealName(deals.getDealName());
return new ResponseEntity<Deal>(currentDeal, HttpStatus.OK);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/reviewType", method = RequestMethod.GET)
public ResponseEntity<List<String>> getAllReviewType() {
List<Review> reviews = dealService.findAllReviews();
if (CollectionUtils.isEmpty(reviews)) {
logger.error("not found review type");
return new ResponseEntity(new CustomErrorType("not found review type"), HttpStatus.NO_CONTENT);
}
List<String> reviewTypes = reviews.stream().map(x -> x.getReviewType()).collect(Collectors.toList());
if (CollectionUtils.isEmpty(reviewTypes)) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<String>>(reviewTypes, HttpStatus.OK);
}
@RequestMapping(value = "/priorityType", method = RequestMethod.GET)
public ResponseEntity<List<PriorityType>> getPriorityType() {
List<PriorityType> lists = new ArrayList<PriorityType>();
for (PriorityType status : PriorityType.values()) {
lists.add(status);
}
return new ResponseEntity<List<PriorityType>>(lists, HttpStatus.OK);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/createLoan", method = RequestMethod.POST)
public ResponseEntity<String> createLoan(@RequestBody List<LoanVO> loanVos) {
List<Loan> loans = new ArrayList<>();
for (LoanVO loanvo : loanVos) {
Loan loan = new Loan();
loan.setLoanId(loanvo.getLoanId());
loan.setBorrowerName(loanvo.getBorrowerName());
loan.setLoanAmount(loanvo.getLoanAmount());
loan.setLoanType(loanvo.getLoanType());
loan.setSsn(loanvo.getSsn());
Deal deal =dealService.findDealByDealId(loanvo.getDealId());
deal.setDealId(loanvo.getDealId());
loan.setDeal(deal);
loans.add(loan);
}
if (this.dealService.isLoanExist(loans)) {
logger.error("Unable to create. A Loan with id already exist.");
return new ResponseEntity(new CustomErrorType("Unable to create. A Loan with id already exist."),
HttpStatus.CONFLICT);
}
for (int i = 0; i < loanVos.size(); i++) {
List<String> list = this.dealService.getReviewType(loanVos.get(i).getDealId());
Map<String, Object> vars = Collections.<String, Object>singletonMap("loan", loans.get(i));
ProcessInstance pi = runtimeService.startProcessInstanceByKey("userAssign", vars);
loans.get(i).setProcess_inst_id(pi.getId());
}
try {
this.dealService.saveLoan(loans);
} catch (Exception e) {
logger.error("Unable to create loan.");
return new ResponseEntity(new CustomErrorType("Unable to create loan."), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<String>("Saved Loans", HttpStatus.OK);
}
@RequestMapping(value = "/getTaskDashboard", method = RequestMethod.GET)
public ResponseEntity<List<TaskDetailsVO>> getAllTaskDashboard() {
List<TaskDetailsVO> listTaskDetails = this.dealService.getAllTaskDashboard();
return new ResponseEntity<List<TaskDetailsVO>>(listTaskDetails, HttpStatus.OK);
}
@RequestMapping(value = "/getTaskDetails", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<List<TaskDetailsVO>> getTaskDtailsById(@RequestBody TaskDetailsVO taskDetailsVO) {
List<TaskDetailsVO> listTaskDetails = this.dealService.getTaskDtailsById(taskDetailsVO.getLoanId(),
taskDetailsVO.getTaskName());
String currentTaskName = listTaskDetails.get(0).getTaskName();
String[] task = currentTaskName.split("_");
String description = task[1] + " Loan#" + listTaskDetails.get(0).getLoanId() + " of Deal ID CLY00"
+ listTaskDetails.get(0).getDealId() + " for Review Type " + task[0];
listTaskDetails.get(0).setTaskName(task[1]);
listTaskDetails.get(0).setDescription(description);
return new ResponseEntity<List<TaskDetailsVO>>(listTaskDetails, HttpStatus.OK);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/completeTask", method = RequestMethod.POST)
public ResponseEntity<?> completeTask(@RequestBody TaskDetailsVO taskDetailsVO) {
TaskService taskService = processEngine.getTaskService();
if (this.dealService.isTaskExist(taskDetailsVO.getTaskId())) {
taskService.complete(taskDetailsVO.getTaskId());
return new ResponseEntity<TaskDetailsVO>(taskDetailsVO, HttpStatus.OK);
} else {
logger.error("Task id :- "+taskDetailsVO.getTaskId()+ "already completeed found");
return new ResponseEntity(
new CustomErrorType(
"Unable to Complete Task with id " + taskDetailsVO.getTaskId() + "Found completed."),
HttpStatus.NOT_FOUND);
}
}
}
| 7,469 | 0.754987 | 0.752979 | 189 | 38.51852 | 29.74612 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.195767 | false | false | 9 |
34f7afe76f88d14e3d5d55d3978fa669f98f814c | 30,039,001,284,156 | 66788f713d110e77839b4a3483eb150edc8af3e1 | /com/jasonalexllc/tower/PickaxeTower.java | 4e17d90ee26dec895918bc2d369710f68e7fda7e | [] | no_license | inser7Name/CoreDestruction | https://github.com/inser7Name/CoreDestruction | 8378a76f8b6c25842a6557af2aa196047b820c97 | a5c4214de37efe3964e57539792683c3af86811b | refs/heads/master | 2016-09-06T16:50:56.609000 | 2014-06-21T01:09:53 | 2014-06-21T01:09:53 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jasonalexllc.tower;
/**
*
* @author Jason Carrete
* @since Jun 19, 2014
*/
public class PickaxeTower extends Tower
{
private static final long serialVersionUID = -5222779550089892274L;
public PickaxeTower()
{
super(2, 5, .01, 250, "assets/pickaxeTower_idle.png");
}
public void attack(int x, int y)
{
}
}
| UTF-8 | Java | 338 | java | PickaxeTower.java | Java | [
{
"context": "ackage com.jasonalexllc.tower;\n\n/**\n * \n * @author Jason Carrete\n * @since Jun 19, 2014\n */\npublic class PickaxeTo",
"end": 65,
"score": 0.9998742938041687,
"start": 52,
"tag": "NAME",
"value": "Jason Carrete"
}
] | null | [] | package com.jasonalexllc.tower;
/**
*
* @author <NAME>
* @since Jun 19, 2014
*/
public class PickaxeTower extends Tower
{
private static final long serialVersionUID = -5222779550089892274L;
public PickaxeTower()
{
super(2, 5, .01, 250, "assets/pickaxeTower_idle.png");
}
public void attack(int x, int y)
{
}
}
| 331 | 0.683432 | 0.588757 | 21 | 15.095238 | 19.687813 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 9 |
5e2ad2134e7600d80e596bcc7aad3c0184a290dc | 12,652,973,692,668 | 7e92032b9d6e72a1ab0a035f4da41f6a2ddf4552 | /src/cn.jrexe.learn/factory/AbstractCoffee.java | 6315330a2910c100656554d4f350ab0dc346e687 | [] | no_license | Jrexexe/DesignPattern-java | https://github.com/Jrexexe/DesignPattern-java | ffee88afdee18907bf45ce06cede9776cb03f4ae | 88971887d83c11d628b82999c5645aa62b11b944 | refs/heads/master | 2020-08-29T09:46:24.474000 | 2019-11-05T10:13:29 | 2019-11-05T10:13:29 | 217,997,249 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.jrexe.learn.factory;
/***
* @author Jrexe
*/
public abstract class AbstractCoffee {
protected String name;
public void prepare() {
System.out.println("打开机器 。。加热");
}
public void grind() {
System.out.println("研磨磨咖啡豆");
}
public void milk() {
System.out.println("加入牛奶 ");
}
public void stram() {
System.out.println("蒸汽搅拌 ");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| UTF-8 | Java | 592 | java | AbstractCoffee.java | Java | [
{
"context": "package cn.jrexe.learn.factory;\n\n/***\n * @author Jrexe\n */\npublic abstract class AbstractCoffee {\n pr",
"end": 54,
"score": 0.9995884299278259,
"start": 49,
"tag": "USERNAME",
"value": "Jrexe"
}
] | null | [] | package cn.jrexe.learn.factory;
/***
* @author Jrexe
*/
public abstract class AbstractCoffee {
protected String name;
public void prepare() {
System.out.println("打开机器 。。加热");
}
public void grind() {
System.out.println("研磨磨咖啡豆");
}
public void milk() {
System.out.println("加入牛奶 ");
}
public void stram() {
System.out.println("蒸汽搅拌 ");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| 592 | 0.551095 | 0.551095 | 36 | 14.222222 | 14.653614 | 40 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | false | false | 9 |
240e6703505fe1970d6d7d9532963a93fe36fb05 | 8,839,042,709,883 | ebe3950a8643d2ea93a23b214d15e531b7f8182a | /State.java | c08c912e8e3eeab90301a4b8e6ddda83cbab62d9 | [] | no_license | szaialt/JHneftafl | https://github.com/szaialt/JHneftafl | 49d61fdea20216c1c67b383edfad59d2b1b3853c | f8ae2629fd17e8b6aad132452a7c7423e300c3f2 | refs/heads/master | 2021-01-20T18:21:19.450000 | 2016-07-18T12:22:58 | 2016-07-18T12:22:58 | 63,600,839 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Vector;
public class State {
private Gamer next; // = Gamer.ATTACKER;
private Figure movedLast;
private Vector<Figure> defender; //a védő katonái
private Vector<Figure> attacker; //a támadó katonái
private Size size;
private GameType type;
private Figure king;
private Gamer winner;
State(Gamer next, Size size, GameType type){
this.next = next;
this.size = size;
this.type = type;
this.movedLast = null;
this.defender = new Vector<Figure>();
this.attacker = new Vector<Figure>();
this.king = new Figure((size.getValue()-1)/2, (size.getValue()-1)/2, Gamer.DEFENDER);
this.winner = null;
if (size.getValue() == 9){
//A védő bábui: a király és 12 katona
defender.add(new Figure(4, 3, Gamer.DEFENDER));
defender.add(new Figure(4, 2, Gamer.DEFENDER));
defender.add(new Figure(4, 1, Gamer.DEFENDER));
defender.add(new Figure(3, 4, Gamer.DEFENDER));
defender.add(new Figure(2, 4, Gamer.DEFENDER));
defender.add(new Figure(1, 4, Gamer.DEFENDER));
defender.add(new Figure(4, 5, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 7, Gamer.DEFENDER));
defender.add(new Figure(5, 4, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(7, 4, Gamer.DEFENDER));
//A támadó bábui: 12 katona
attacker.add(new Figure(0, 3, Gamer.ATTACKER));
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 0, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(8, 3, Gamer.ATTACKER));
attacker.add(new Figure(8, 4, Gamer.ATTACKER));
attacker.add(new Figure(8, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 8, Gamer.ATTACKER));
attacker.add(new Figure(4, 8, Gamer.ATTACKER));
attacker.add(new Figure(5, 8, Gamer.ATTACKER));
}
else if (size.getValue() == 11){
//A védő bábui: a király és 12 katona
defender.add(new Figure(5, 4, Gamer.DEFENDER));
defender.add(new Figure(5, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(6, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 4, Gamer.DEFENDER));
defender.add(new Figure(3, 5, Gamer.DEFENDER));
defender.add(new Figure(5, 3, Gamer.DEFENDER));
defender.add(new Figure(5, 7, Gamer.DEFENDER));
defender.add(new Figure(7, 5, Gamer.DEFENDER));
//A támadó bábui: 24 katona
attacker.add(new Figure(0, 3, Gamer.ATTACKER));
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(0, 6, Gamer.ATTACKER));
attacker.add(new Figure(0, 7, Gamer.ATTACKER));
attacker.add(new Figure(1, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 0, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 0, Gamer.ATTACKER));
attacker.add(new Figure(7, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 1, Gamer.ATTACKER));
attacker.add(new Figure(10, 3, Gamer.ATTACKER));
attacker.add(new Figure(10, 4, Gamer.ATTACKER));
attacker.add(new Figure(10, 5, Gamer.ATTACKER));
attacker.add(new Figure(10, 6, Gamer.ATTACKER));
attacker.add(new Figure(10, 7, Gamer.ATTACKER));
attacker.add(new Figure(9, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 10, Gamer.ATTACKER));
attacker.add(new Figure(4, 10, Gamer.ATTACKER));
attacker.add(new Figure(5, 10, Gamer.ATTACKER));
attacker.add(new Figure(6, 10, Gamer.ATTACKER));
attacker.add(new Figure(7, 10, Gamer.ATTACKER));
attacker.add(new Figure(5, 9, Gamer.ATTACKER));
}
else if (size.getValue() == 13){
//A védő bábui: a király és 12 katona
defender.add(new Figure(6, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(6, 3, Gamer.DEFENDER));
defender.add(new Figure(5, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(3, 6, Gamer.DEFENDER));
defender.add(new Figure(6, 7, Gamer.DEFENDER));
defender.add(new Figure(6, 8, Gamer.DEFENDER));
defender.add(new Figure(6, 9, Gamer.DEFENDER));
defender.add(new Figure(7, 6, Gamer.DEFENDER));
defender.add(new Figure(8, 6, Gamer.DEFENDER));
defender.add(new Figure(9, 6, Gamer.DEFENDER));
//A támadó bábui: 24 katona
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(0, 6, Gamer.ATTACKER));
attacker.add(new Figure(0, 7, Gamer.ATTACKER));
attacker.add(new Figure(0, 8, Gamer.ATTACKER));
attacker.add(new Figure(1, 6, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 0, Gamer.ATTACKER));
attacker.add(new Figure(7, 0, Gamer.ATTACKER));
attacker.add(new Figure(8, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 1, Gamer.ATTACKER));
attacker.add(new Figure(12, 4, Gamer.ATTACKER));
attacker.add(new Figure(12, 5, Gamer.ATTACKER));
attacker.add(new Figure(12, 6, Gamer.ATTACKER));
attacker.add(new Figure(12, 7, Gamer.ATTACKER));
attacker.add(new Figure(12, 8, Gamer.ATTACKER));
attacker.add(new Figure(11, 6, Gamer.ATTACKER));
attacker.add(new Figure(4, 12, Gamer.ATTACKER));
attacker.add(new Figure(5, 12, Gamer.ATTACKER));
attacker.add(new Figure(6, 12, Gamer.ATTACKER));
attacker.add(new Figure(7, 12, Gamer.ATTACKER));
attacker.add(new Figure(8, 12, Gamer.ATTACKER));
attacker.add(new Figure(6, 11, Gamer.ATTACKER));
}
}
public Gamer getNext(){
return this.next;
}
public Figure getMovedLast(){
return this.movedLast;
}
public Vector<Figure> getDefender(){
return this.defender;
}
public Vector<Figure> getAttacker(){
return this.attacker;
}
public Size getSize(){
return this.size;
}
public GameType getType(){
return this.type;
}
public Figure getKing(){
return this.king;
}
public Gamer getWinner(){
return this.winner;
}
public void setMovedLast(Figure figure){
this.movedLast = figure;
}
public void setNext(Gamer gamer){
this.next = gamer;
}
public void setWinner(Gamer gamer){
this.winner = gamer;
}
public static boolean isNeighbour(Figure b1, Figure b2){
int x1 = b1.getX();
int y1 = b1.getY();
int x2 = b2.getX();
int y2 = b2.getY();
if(x1 == x2){
if(y1 == y2-1)
return true;
else if(y1 == y2+1)
return true;
}
else if(x1 == x2-1){
if (y1 == y2)
return true;
}
else if(x1 == x2+1){
if (y1 == y2)
return true;
}
return false;
}
public void remove(int i){
if (next.equals(Gamer.ATTACKER)){
defender.remove(i);
}
else {
attacker.remove(i);
}
}
} | UTF-8 | Java | 7,745 | java | State.java | Java | [] | null | [] | import java.util.Vector;
public class State {
private Gamer next; // = Gamer.ATTACKER;
private Figure movedLast;
private Vector<Figure> defender; //a védő katonái
private Vector<Figure> attacker; //a támadó katonái
private Size size;
private GameType type;
private Figure king;
private Gamer winner;
State(Gamer next, Size size, GameType type){
this.next = next;
this.size = size;
this.type = type;
this.movedLast = null;
this.defender = new Vector<Figure>();
this.attacker = new Vector<Figure>();
this.king = new Figure((size.getValue()-1)/2, (size.getValue()-1)/2, Gamer.DEFENDER);
this.winner = null;
if (size.getValue() == 9){
//A védő bábui: a király és 12 katona
defender.add(new Figure(4, 3, Gamer.DEFENDER));
defender.add(new Figure(4, 2, Gamer.DEFENDER));
defender.add(new Figure(4, 1, Gamer.DEFENDER));
defender.add(new Figure(3, 4, Gamer.DEFENDER));
defender.add(new Figure(2, 4, Gamer.DEFENDER));
defender.add(new Figure(1, 4, Gamer.DEFENDER));
defender.add(new Figure(4, 5, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 7, Gamer.DEFENDER));
defender.add(new Figure(5, 4, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(7, 4, Gamer.DEFENDER));
//A támadó bábui: 12 katona
attacker.add(new Figure(0, 3, Gamer.ATTACKER));
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 0, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(8, 3, Gamer.ATTACKER));
attacker.add(new Figure(8, 4, Gamer.ATTACKER));
attacker.add(new Figure(8, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 8, Gamer.ATTACKER));
attacker.add(new Figure(4, 8, Gamer.ATTACKER));
attacker.add(new Figure(5, 8, Gamer.ATTACKER));
}
else if (size.getValue() == 11){
//A védő bábui: a király és 12 katona
defender.add(new Figure(5, 4, Gamer.DEFENDER));
defender.add(new Figure(5, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(6, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 4, Gamer.DEFENDER));
defender.add(new Figure(3, 5, Gamer.DEFENDER));
defender.add(new Figure(5, 3, Gamer.DEFENDER));
defender.add(new Figure(5, 7, Gamer.DEFENDER));
defender.add(new Figure(7, 5, Gamer.DEFENDER));
//A támadó bábui: 24 katona
attacker.add(new Figure(0, 3, Gamer.ATTACKER));
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(0, 6, Gamer.ATTACKER));
attacker.add(new Figure(0, 7, Gamer.ATTACKER));
attacker.add(new Figure(1, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 0, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 0, Gamer.ATTACKER));
attacker.add(new Figure(7, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 1, Gamer.ATTACKER));
attacker.add(new Figure(10, 3, Gamer.ATTACKER));
attacker.add(new Figure(10, 4, Gamer.ATTACKER));
attacker.add(new Figure(10, 5, Gamer.ATTACKER));
attacker.add(new Figure(10, 6, Gamer.ATTACKER));
attacker.add(new Figure(10, 7, Gamer.ATTACKER));
attacker.add(new Figure(9, 5, Gamer.ATTACKER));
attacker.add(new Figure(3, 10, Gamer.ATTACKER));
attacker.add(new Figure(4, 10, Gamer.ATTACKER));
attacker.add(new Figure(5, 10, Gamer.ATTACKER));
attacker.add(new Figure(6, 10, Gamer.ATTACKER));
attacker.add(new Figure(7, 10, Gamer.ATTACKER));
attacker.add(new Figure(5, 9, Gamer.ATTACKER));
}
else if (size.getValue() == 13){
//A védő bábui: a király és 12 katona
defender.add(new Figure(6, 5, Gamer.DEFENDER));
defender.add(new Figure(6, 4, Gamer.DEFENDER));
defender.add(new Figure(6, 3, Gamer.DEFENDER));
defender.add(new Figure(5, 6, Gamer.DEFENDER));
defender.add(new Figure(4, 6, Gamer.DEFENDER));
defender.add(new Figure(3, 6, Gamer.DEFENDER));
defender.add(new Figure(6, 7, Gamer.DEFENDER));
defender.add(new Figure(6, 8, Gamer.DEFENDER));
defender.add(new Figure(6, 9, Gamer.DEFENDER));
defender.add(new Figure(7, 6, Gamer.DEFENDER));
defender.add(new Figure(8, 6, Gamer.DEFENDER));
defender.add(new Figure(9, 6, Gamer.DEFENDER));
//A támadó bábui: 24 katona
attacker.add(new Figure(0, 4, Gamer.ATTACKER));
attacker.add(new Figure(0, 5, Gamer.ATTACKER));
attacker.add(new Figure(0, 6, Gamer.ATTACKER));
attacker.add(new Figure(0, 7, Gamer.ATTACKER));
attacker.add(new Figure(0, 8, Gamer.ATTACKER));
attacker.add(new Figure(1, 6, Gamer.ATTACKER));
attacker.add(new Figure(4, 0, Gamer.ATTACKER));
attacker.add(new Figure(5, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 0, Gamer.ATTACKER));
attacker.add(new Figure(7, 0, Gamer.ATTACKER));
attacker.add(new Figure(8, 0, Gamer.ATTACKER));
attacker.add(new Figure(6, 1, Gamer.ATTACKER));
attacker.add(new Figure(12, 4, Gamer.ATTACKER));
attacker.add(new Figure(12, 5, Gamer.ATTACKER));
attacker.add(new Figure(12, 6, Gamer.ATTACKER));
attacker.add(new Figure(12, 7, Gamer.ATTACKER));
attacker.add(new Figure(12, 8, Gamer.ATTACKER));
attacker.add(new Figure(11, 6, Gamer.ATTACKER));
attacker.add(new Figure(4, 12, Gamer.ATTACKER));
attacker.add(new Figure(5, 12, Gamer.ATTACKER));
attacker.add(new Figure(6, 12, Gamer.ATTACKER));
attacker.add(new Figure(7, 12, Gamer.ATTACKER));
attacker.add(new Figure(8, 12, Gamer.ATTACKER));
attacker.add(new Figure(6, 11, Gamer.ATTACKER));
}
}
public Gamer getNext(){
return this.next;
}
public Figure getMovedLast(){
return this.movedLast;
}
public Vector<Figure> getDefender(){
return this.defender;
}
public Vector<Figure> getAttacker(){
return this.attacker;
}
public Size getSize(){
return this.size;
}
public GameType getType(){
return this.type;
}
public Figure getKing(){
return this.king;
}
public Gamer getWinner(){
return this.winner;
}
public void setMovedLast(Figure figure){
this.movedLast = figure;
}
public void setNext(Gamer gamer){
this.next = gamer;
}
public void setWinner(Gamer gamer){
this.winner = gamer;
}
public static boolean isNeighbour(Figure b1, Figure b2){
int x1 = b1.getX();
int y1 = b1.getY();
int x2 = b2.getX();
int y2 = b2.getY();
if(x1 == x2){
if(y1 == y2-1)
return true;
else if(y1 == y2+1)
return true;
}
else if(x1 == x2-1){
if (y1 == y2)
return true;
}
else if(x1 == x2+1){
if (y1 == y2)
return true;
}
return false;
}
public void remove(int i){
if (next.equals(Gamer.ATTACKER)){
defender.remove(i);
}
else {
attacker.remove(i);
}
}
} | 7,745 | 0.615165 | 0.581076 | 230 | 32.547825 | 21.531673 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.447826 | false | false | 9 |
9668f9a115ac4ce2578e5cb4dbd1014c8a4bbfe8 | 32,753,420,611,502 | 89d18edb2396abb8a43649a11c3df96701bc90ff | /ClearVision/src/com/clearvision/controller/DisplayVisualizationController.java | 9cd2c534837bd0a236e8fd0cb4e94012ecd8409b | [] | no_license | cwinnard/ClearVision | https://github.com/cwinnard/ClearVision | 69b6f33552e0a7e4e30f0f1274099f19c940b64e | 4a83e96f9ca359ecdf4b4ea09d3e59f9cbfb5e14 | refs/heads/master | 2021-01-10T12:44:14.715000 | 2015-11-20T18:27:59 | 2015-11-20T18:27:59 | 45,937,828 | 6 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.clearvision.controller;
import java.io.IOException;
import java.util.ArrayList;
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.json.JSONException;
import com.clearvision.database.DatabaseJoiner;
import com.clearvision.database.JsonParser;
import com.clearvision.database.LeafDB;
import com.clearvision.model.Leaf;
/**
* Servlet implementation class DisplayVisualizationController
*/
@WebServlet("/DisplayVisualizationController")
public class DisplayVisualizationController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DisplayVisualizationController() {
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 {
DatabaseJoiner joiner = new DatabaseJoiner();
joiner.joinUserAndBookmarkTables("presentation@test.com");
joiner.joinUserBookmarkAndTagTables();
LeafDB leafDB = new LeafDB();
ArrayList<Leaf> leaves = new ArrayList<Leaf>();
leaves = leafDB.pullLeavesFromDatabase();
JsonParser jsonParser = new JsonParser();
try {
jsonParser.generateJSON(leaves);
} catch (JSONException e) {
e.printStackTrace();
}
request.getRequestDispatcher("/accountPage.jsp").forward(request, response);
}
}
| UTF-8 | Java | 1,979 | java | DisplayVisualizationController.java | Java | [
{
"context": "baseJoiner();\n\t\tjoiner.joinUserAndBookmarkTables(\"presentation@test.com\");\n\t\tjoiner.joinUserBookmarkAndTagTables();\n\n\t\tLe",
"end": 1572,
"score": 0.9999082684516907,
"start": 1551,
"tag": "EMAIL",
"value": "presentation@test.com"
}
] | null | [] | package com.clearvision.controller;
import java.io.IOException;
import java.util.ArrayList;
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.json.JSONException;
import com.clearvision.database.DatabaseJoiner;
import com.clearvision.database.JsonParser;
import com.clearvision.database.LeafDB;
import com.clearvision.model.Leaf;
/**
* Servlet implementation class DisplayVisualizationController
*/
@WebServlet("/DisplayVisualizationController")
public class DisplayVisualizationController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DisplayVisualizationController() {
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 {
DatabaseJoiner joiner = new DatabaseJoiner();
joiner.joinUserAndBookmarkTables("<EMAIL>");
joiner.joinUserBookmarkAndTagTables();
LeafDB leafDB = new LeafDB();
ArrayList<Leaf> leaves = new ArrayList<Leaf>();
leaves = leafDB.pullLeavesFromDatabase();
JsonParser jsonParser = new JsonParser();
try {
jsonParser.generateJSON(leaves);
} catch (JSONException e) {
e.printStackTrace();
}
request.getRequestDispatcher("/accountPage.jsp").forward(request, response);
}
}
| 1,965 | 0.774634 | 0.774128 | 69 | 27.68116 | 24.696707 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.405797 | false | false | 9 |
85a9fb77ef8d7e1b955e7d1e274f0aeceee05f78 | 23,416,161,709,804 | dbef0090ad3c69f318175dc36a3279da898e85d6 | /estudiantescreenplay/src/main/java/co/com/bancolombia/certificacion/lineabasescreenplay/userinterface/CapturaDatosUserInterface.java | 4793cb2fa39a3aaea169be460cff5ecf39953d62 | [] | no_license | lalisvc/estudiantescreenplay | https://github.com/lalisvc/estudiantescreenplay | ef60e772e1fe20b950f4685792be409872cefc4d | 3763e6af0ef285ddad26ee0ae26c2986f3fdfc1d | refs/heads/master | 2020-04-10T18:04:38.206000 | 2018-12-10T15:19:47 | 2018-12-10T15:19:47 | 161,193,215 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.com.bancolombia.certificacion.lineabasescreenplay.userinterface;
import net.serenitybdd.core.annotations.findby.By;
import net.serenitybdd.screenplay.targets.Target;
public class CapturaDatosUserInterface {
public static final Target TEXT_CAPTURADATOS =Target.the("captura primer nombre")
.located(By.id(("dojox_mvc_Element_3")));
}
| UTF-8 | Java | 364 | java | CapturaDatosUserInterface.java | Java | [] | null | [] | package co.com.bancolombia.certificacion.lineabasescreenplay.userinterface;
import net.serenitybdd.core.annotations.findby.By;
import net.serenitybdd.screenplay.targets.Target;
public class CapturaDatosUserInterface {
public static final Target TEXT_CAPTURADATOS =Target.the("captura primer nombre")
.located(By.id(("dojox_mvc_Element_3")));
}
| 364 | 0.78022 | 0.777473 | 11 | 32.090908 | 31.381681 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 9 |
113dce202a71533cae581805887afd3e30c8fb48 | 19,310,172,982,103 | d3c9ca65595b85c3adf620c98cc31daa369c9f14 | /src/main/java/com/qianyuan/entity/reportserver$sqlexpress/Users.java | e24c70efafc301b80bdaf6297f1811406ef2e055 | [] | no_license | ChenXiaoHui8/lc | https://github.com/ChenXiaoHui8/lc | 1d1f06d73098110f60bf0cbeb524b5aad8b42276 | ea3011f978cbceabcc46331361d10032313f57c5 | refs/heads/master | 2020-04-19T23:39:24.815000 | 2019-03-27T02:07:06 | 2019-03-27T02:07:06 | 168,501,656 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.qianyuan.entity.reportserver$sqlexpress;
public class Users {
private String userId;
private String sid;
private long userType;
private long authType;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public long getUserType() {
return userType;
}
public void setUserType(long userType) {
this.userType = userType;
}
public long getAuthType() {
return authType;
}
public void setAuthType(long authType) {
this.authType = authType;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
| UTF-8 | Java | 849 | java | Users.java | Java | [
{
"context": ";\n }\n\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) ",
"end": 760,
"score": 0.8927273750305176,
"start": 752,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "setUserName(String userName) {\n thi... | null | [] | package com.qianyuan.entity.reportserver$sqlexpress;
public class Users {
private String userId;
private String sid;
private long userType;
private long authType;
private String userName;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public long getUserType() {
return userType;
}
public void setUserType(long userType) {
this.userType = userType;
}
public long getAuthType() {
return authType;
}
public void setAuthType(long authType) {
this.authType = authType;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
| 849 | 0.666667 | 0.666667 | 57 | 13.894737 | 14.911063 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.280702 | false | false | 9 |
1a861d86043629666e9e5357f9fc5be16bd02bfa | 5,995,774,359,793 | aca54608fe4edf87812f268828f685e74ac40395 | /poc/src/webapp/src/test/java/pl/openpkw/poc/webapp/velocityengine/When_processing_template.java | 61878861fc77094016501c34314fa58d387c817f | [] | no_license | michalgra/openpkw | https://github.com/michalgra/openpkw | a0ca1b6f0cd4e684cec952613188df827a409c54 | 439f0c1b12e643eff5ddf6e9258e1902ef8be95e | refs/heads/master | 2016-10-13T21:43:50.831000 | 2015-03-13T22:19:58 | 2015-03-13T22:19:58 | 31,559,050 | 0 | 0 | null | true | 2015-03-02T19:38:29 | 2015-03-02T19:38:27 | 2015-03-02T19:38:28 | 2015-03-02T18:28:46 | 3,962 | 0 | 0 | 0 | HTML | null | null | package pl.openpkw.poc.webapp.velocityengine;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import junit.framework.Assert;
import org.apache.velocity.VelocityContext;
import org.junit.Test;
import pl.openpkw.poc.webapp.VelocityEngine;
public class When_processing_template {
private VelocityEngine cut = new VelocityEngine();
@Test
public void should_preserve_character_encoding_UTF_8_with_BOM() {
tryFile("velocity/pdf_template_UTF-8_with_BOM.html");
}
@Test
public void should_preserve_character_encoding_UTF_8_without_BOM() {
tryFile("velocity/pdf_template_UTF-8_without_BOM.html");
}
@Test
public void should_preserve_character_encoding_in_real_HTML_template() {
tryFile("velocity/pdf_template.html");
}
private void tryFile(String templateFile) {
cut.initialize();
String expectedOutput = loadFile("/"+templateFile);
String actualOutput = cut.process(templateFile, new VelocityContext());
System.out.println("Expected output: "+expectedOutput);
System.out.println("Actual output: "+actualOutput);
Assert.assertEquals(expectedOutput, actualOutput);
}
private String loadFile(String fileName) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = this.getClass().getResourceAsStream(fileName);
byte[] buffer = new byte[1024];
int readBytes = 0;
do {
readBytes = in.read(buffer);
if (readBytes > 0) {
out.write(buffer, 0, readBytes);
}
} while (readBytes > 0);
in.close();
out.close();
String result = new String(out.toByteArray(), "UTF-8");
System.out.println("Input file: "+result);
return result;
} catch (Exception ex) {
throw new RuntimeException("Failed to load file " + fileName + ": " + ex.getMessage(), ex);
}
}
} | UTF-8 | Java | 1,808 | java | When_processing_template.java | Java | [] | null | [] | package pl.openpkw.poc.webapp.velocityengine;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import junit.framework.Assert;
import org.apache.velocity.VelocityContext;
import org.junit.Test;
import pl.openpkw.poc.webapp.VelocityEngine;
public class When_processing_template {
private VelocityEngine cut = new VelocityEngine();
@Test
public void should_preserve_character_encoding_UTF_8_with_BOM() {
tryFile("velocity/pdf_template_UTF-8_with_BOM.html");
}
@Test
public void should_preserve_character_encoding_UTF_8_without_BOM() {
tryFile("velocity/pdf_template_UTF-8_without_BOM.html");
}
@Test
public void should_preserve_character_encoding_in_real_HTML_template() {
tryFile("velocity/pdf_template.html");
}
private void tryFile(String templateFile) {
cut.initialize();
String expectedOutput = loadFile("/"+templateFile);
String actualOutput = cut.process(templateFile, new VelocityContext());
System.out.println("Expected output: "+expectedOutput);
System.out.println("Actual output: "+actualOutput);
Assert.assertEquals(expectedOutput, actualOutput);
}
private String loadFile(String fileName) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = this.getClass().getResourceAsStream(fileName);
byte[] buffer = new byte[1024];
int readBytes = 0;
do {
readBytes = in.read(buffer);
if (readBytes > 0) {
out.write(buffer, 0, readBytes);
}
} while (readBytes > 0);
in.close();
out.close();
String result = new String(out.toByteArray(), "UTF-8");
System.out.println("Input file: "+result);
return result;
} catch (Exception ex) {
throw new RuntimeException("Failed to load file " + fileName + ": " + ex.getMessage(), ex);
}
}
} | 1,808 | 0.721792 | 0.714602 | 64 | 27.265625 | 24.774761 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.015625 | false | false | 9 |
992aa47f8fa6f00ee99346597779691c29a68f63 | 13,804,024,906,402 | eed56ab9fecd924b95e43f9d260064448efc5056 | /practica9/ArbolDeExpansion.java | b8a1e51100e9c1206638573dbfd9401a0e3db096 | [] | no_license | ucabrera/AyED | https://github.com/ucabrera/AyED | 2bec69d4ee3fbefc4649e98b84660bdafd58d563 | d9bfcf06516ffa04dacdc3563e563f73a590f08a | refs/heads/master | 2016-09-19T02:16:16.323000 | 2016-09-14T16:53:45 | 2016-09-14T16:53:45 | 67,653,343 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package practica9;
import practica3.ListaEnlazadaGenerica;
import practica7.MinHeap;
public class ArbolDeExpansion<T> {
private CostoParaHeap [] prim(Grafo<T> grafo, Vertice<T> origen){
CostoParaHeap [] costo= new CostoParaHeap [grafo.getVertices().tamanio()];
CostoParaHeap min;
Arista<T> w;
int conocidos= 1;
MinHeap<CostoParaHeap> heap= new MinHeap<CostoParaHeap>();
for(int i= 0; i< costo.length; i++)
costo[i]= new CostoParaHeap(Integer.MAX_VALUE, i, Integer.MAX_VALUE, false);
costo[origen.getPosicion()]= new CostoParaHeap(0, origen.getPosicion(), origen.getPosicion(), false);
heap.agregar(costo[origen.getPosicion()]);
while(conocidos< grafo.getVertices().tamanio()){
min= heap.eliminar();
if(!costo[min.getVerticeOrigen()].isConocido()){
costo[min.getVerticeOrigen()].setConocido(true);
conocidos++;
ListaEnlazadaGenerica<Arista<T>> ady= grafo.getVertices().elemento(min.getVerticeOrigen()).getAdyacentes();
for(int j= 0; j< ady.tamanio(); j++){
w= ady.elemento(j);
if(!costo[w.getDestino().getPosicion()].isConocido() && (costo[w.getDestino().getPosicion()].getCosto() > w.getPeso())){
costo[w.getDestino().getPosicion()].setCosto(w.getPeso());
costo[w.getDestino().getPosicion()].setPasarPorVertice(min.getVerticeOrigen());
heap.agregar(new CostoParaHeap(w.getPeso(), w.getDestino().getPosicion(), min.getVerticeOrigen(), false));
}
}
}
}
System.out.println(heap.toString());
return costo;
}
public static void main(String[] args) {
Grafo<String> grafo;
ArbolDeExpansion<String> ade= new ArbolDeExpansion<String>();
grafo= new Grafo<String>();
grafo.agregarVertice(new Vertice<String>("1"));
grafo.agregarVertice(new Vertice<String>("2"));
grafo.agregarVertice(new Vertice<String>("3"));
grafo.agregarVertice(new Vertice<String>("4"));
grafo.agregarVertice(new Vertice<String>("5"));
grafo.agregarVertice(new Vertice<String>("6"));
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(1), 6);
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(2), 1);
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(3), 5);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(0), 6);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(2), 5);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(4), 3);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(0), 1);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(1), 5);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(3), 5);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(4), 6);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(5), 4);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(0), 5);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(2), 5);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(5), 2);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(1), 3);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(2), 6);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(5), 6);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(2), 4);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(3), 2);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(4), 6);
CostoParaHeap [] c= ade.prim(grafo, grafo.getVertices().elemento(0));
c.toString();
for(int i= 0; i< c.length; i++)
System.out.println("Origen: "+ grafo.getVertices().elemento(c[i].getVerticeOrigen()) + " costo: "+ c[i].getCosto() + " pasa por: "+ grafo.getVertices().elemento(c[i].getPasarPorVertice()));
}
}
| UTF-8 | Java | 4,098 | java | ArbolDeExpansion.java | Java | [] | null | [] | package practica9;
import practica3.ListaEnlazadaGenerica;
import practica7.MinHeap;
public class ArbolDeExpansion<T> {
private CostoParaHeap [] prim(Grafo<T> grafo, Vertice<T> origen){
CostoParaHeap [] costo= new CostoParaHeap [grafo.getVertices().tamanio()];
CostoParaHeap min;
Arista<T> w;
int conocidos= 1;
MinHeap<CostoParaHeap> heap= new MinHeap<CostoParaHeap>();
for(int i= 0; i< costo.length; i++)
costo[i]= new CostoParaHeap(Integer.MAX_VALUE, i, Integer.MAX_VALUE, false);
costo[origen.getPosicion()]= new CostoParaHeap(0, origen.getPosicion(), origen.getPosicion(), false);
heap.agregar(costo[origen.getPosicion()]);
while(conocidos< grafo.getVertices().tamanio()){
min= heap.eliminar();
if(!costo[min.getVerticeOrigen()].isConocido()){
costo[min.getVerticeOrigen()].setConocido(true);
conocidos++;
ListaEnlazadaGenerica<Arista<T>> ady= grafo.getVertices().elemento(min.getVerticeOrigen()).getAdyacentes();
for(int j= 0; j< ady.tamanio(); j++){
w= ady.elemento(j);
if(!costo[w.getDestino().getPosicion()].isConocido() && (costo[w.getDestino().getPosicion()].getCosto() > w.getPeso())){
costo[w.getDestino().getPosicion()].setCosto(w.getPeso());
costo[w.getDestino().getPosicion()].setPasarPorVertice(min.getVerticeOrigen());
heap.agregar(new CostoParaHeap(w.getPeso(), w.getDestino().getPosicion(), min.getVerticeOrigen(), false));
}
}
}
}
System.out.println(heap.toString());
return costo;
}
public static void main(String[] args) {
Grafo<String> grafo;
ArbolDeExpansion<String> ade= new ArbolDeExpansion<String>();
grafo= new Grafo<String>();
grafo.agregarVertice(new Vertice<String>("1"));
grafo.agregarVertice(new Vertice<String>("2"));
grafo.agregarVertice(new Vertice<String>("3"));
grafo.agregarVertice(new Vertice<String>("4"));
grafo.agregarVertice(new Vertice<String>("5"));
grafo.agregarVertice(new Vertice<String>("6"));
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(1), 6);
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(2), 1);
grafo.conectar(grafo.getVertices().elemento(0), grafo.getVertices().elemento(3), 5);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(0), 6);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(2), 5);
grafo.conectar(grafo.getVertices().elemento(1), grafo.getVertices().elemento(4), 3);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(0), 1);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(1), 5);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(3), 5);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(4), 6);
grafo.conectar(grafo.getVertices().elemento(2), grafo.getVertices().elemento(5), 4);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(0), 5);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(2), 5);
grafo.conectar(grafo.getVertices().elemento(3), grafo.getVertices().elemento(5), 2);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(1), 3);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(2), 6);
grafo.conectar(grafo.getVertices().elemento(4), grafo.getVertices().elemento(5), 6);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(2), 4);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(3), 2);
grafo.conectar(grafo.getVertices().elemento(5), grafo.getVertices().elemento(4), 6);
CostoParaHeap [] c= ade.prim(grafo, grafo.getVertices().elemento(0));
c.toString();
for(int i= 0; i< c.length; i++)
System.out.println("Origen: "+ grafo.getVertices().elemento(c[i].getVerticeOrigen()) + " costo: "+ c[i].getCosto() + " pasa por: "+ grafo.getVertices().elemento(c[i].getPasarPorVertice()));
}
}
| 4,098 | 0.699122 | 0.68082 | 74 | 53.37838 | 37.655518 | 192 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.702703 | false | false | 9 |
c33f9a753741ba9225e2eab9c1d60e5761b07fcd | 31,275,951,867,205 | 5963f93832e8776c9ddde44af37964783d126bd1 | /src/test/java/co/edu/usbcali/bank/repository/UserTypeRepositoryTest.java | 74815fb90a4253005d7c7b39b379ba4949a2e869 | [] | no_license | dsantafe/bank | https://github.com/dsantafe/bank | d011b51fae72fbff6557f4acc737386b9552da16 | 74bee364875a70b00734dc62bfd298a247e8ce68 | refs/heads/master | 2022-04-11T16:02:09.706000 | 2020-03-26T05:52:53 | 2020-03-26T05:52:53 | 250,172,867 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.edu.usbcali.bank.repository;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import co.edu.usbcali.bank.domain.UserType;
@SpringBootTest
@Rollback(false)
class UserTypeRepositoryTest {
final static Logger log = LoggerFactory.getLogger(ClientRepositoryTest.class);
@Autowired
UserTypeRepository userTypeRepository;
Long ustyId = 4L;
@BeforeEach
void beforeEach() {
log.info("Se ejecuto el beforeEach");
assertNotNull(userTypeRepository, "The userTypeRepository is null");
}
@AfterEach
void afterEach() {
log.info("Se ejecuto el afterEach");
}
@Test
@DisplayName("save")
@Transactional(readOnly = false)
void atest() {
UserType userType = new UserType();
userType.setUstyId(0L);
userType.setName("PROMOTOR");
userType.setEnable("S");
userTypeRepository.save(userType);
}
@Test
@DisplayName("findById")
void btest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
}
@Test
@DisplayName("update")
@Transactional(readOnly = false)
void ctest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
userTypeOptional.ifPresent(entity -> {
entity.setEnable("S");
userTypeRepository.save(entity);
});
}
@Test
@DisplayName("delete")
@Transactional(readOnly = false)
void dtest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
userTypeOptional.ifPresent(entity -> {
userTypeRepository.delete(entity);
});
}
}
| UTF-8 | Java | 2,202 | java | UserTypeRepositoryTest.java | Java | [] | null | [] | package co.edu.usbcali.bank.repository;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;
import co.edu.usbcali.bank.domain.UserType;
@SpringBootTest
@Rollback(false)
class UserTypeRepositoryTest {
final static Logger log = LoggerFactory.getLogger(ClientRepositoryTest.class);
@Autowired
UserTypeRepository userTypeRepository;
Long ustyId = 4L;
@BeforeEach
void beforeEach() {
log.info("Se ejecuto el beforeEach");
assertNotNull(userTypeRepository, "The userTypeRepository is null");
}
@AfterEach
void afterEach() {
log.info("Se ejecuto el afterEach");
}
@Test
@DisplayName("save")
@Transactional(readOnly = false)
void atest() {
UserType userType = new UserType();
userType.setUstyId(0L);
userType.setName("PROMOTOR");
userType.setEnable("S");
userTypeRepository.save(userType);
}
@Test
@DisplayName("findById")
void btest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
}
@Test
@DisplayName("update")
@Transactional(readOnly = false)
void ctest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
userTypeOptional.ifPresent(entity -> {
entity.setEnable("S");
userTypeRepository.save(entity);
});
}
@Test
@DisplayName("delete")
@Transactional(readOnly = false)
void dtest() {
Optional<UserType> userTypeOptional = userTypeRepository.findById(ustyId);
assertTrue(userTypeOptional.isPresent(), "The user type doesn't exist");
userTypeOptional.ifPresent(entity -> {
userTypeRepository.delete(entity);
});
}
}
| 2,202 | 0.758856 | 0.757039 | 87 | 24.310345 | 23.43458 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.471264 | false | false | 9 |
6d0d2c91cfe36d08a2de72acafc77d804d8ffe2f | 19,756,849,587,113 | dda5914b456e78beb9259a9664b803dcf710b7a8 | /app/src/main/java/com/magnum/handloom/activity/ActivityProduct.java | 65d130664063f2b0a3f618f0d5b65d1c39ce9fd9 | [] | no_license | GajendraVish/Handicarft | https://github.com/GajendraVish/Handicarft | 90e49fd8296a54c6644ac33f75e42206ce495f89 | cd9ad904fdafd2d398019f05fd46eb9a03bf87d8 | refs/heads/master | 2022-11-17T06:39:32.149000 | 2020-07-03T05:17:47 | 2020-07-03T05:17:47 | 276,813,136 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.magnum.handloom.activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magnum.handloom.R;
import com.magnum.handloom.adaptor.EcomCategoryListViewListAdapter;
import com.magnum.handloom.adaptor.RecyclerAdapterProduct;
import com.magnum.handloom.request.EcomProductRequestBean;
import com.magnum.handloom.response.EcomCategoryResponseBean;
import com.magnum.handloom.response.EcomProductResponseBean;
import com.magnum.handloom.response.Product;
import com.magnum.handloom.rest.ApiClient;
import com.magnum.handloom.rest.ApiInterface;
import com.magnum.handloom.rest.Config;
import com.magnum.handloom.utilities.ItemOffsetDecoration;
import com.magnum.handloom.utilities.UserPreference;
import com.magnum.handloom.utilities.Utils;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ActivityProduct extends AppCompatActivity implements RecyclerAdapterProduct.ContactsAdapterListener {
private RecyclerView recyclerView;
private List<Product> productList;
private RecyclerAdapterProduct mAdapter;
private SearchView searchView;
SwipeRefreshLayout swipeRefreshLayout = null;
private String category_id, category_name;
public Toolbar toolbar;
int p_n = 0;
boolean isEnd = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
Intent intent = getIntent();
category_id = intent.getStringExtra("category_id");
category_name = intent.getStringExtra("category_name");
// toolbar fancy stuff
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(category_name);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
recyclerView = findViewById(R.id.recycler_view);
productList = new ArrayList<>();
// fetchData();
EcomProductRequestBean ecomProductRequestBean=new EcomProductRequestBean();
ecomProductRequestBean.setUser_id(UserPreference.getPreference(ActivityProduct.this).getUsers_id());
ecomProductRequestBean.setCategory_id(category_id);
ecomProductRequestBean.setPage_no(0);
getEcomProduct(ecomProductRequestBean);
onRefresh();
}
private void onRefresh() {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
productList.clear();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (Utils.isNetworkAvailable(ActivityProduct.this)) {
swipeRefreshLayout.setRefreshing(false);
// fetchData();
EcomProductRequestBean ecomProductRequestBean=new EcomProductRequestBean();
ecomProductRequestBean.setUser_id(UserPreference.getPreference(ActivityProduct.this).getUsers_id());
ecomProductRequestBean.setCategory_id(category_id);
ecomProductRequestBean.setPage_no(0);
getEcomProduct(ecomProductRequestBean);
} else {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
}
}, 1500);
}
});
}
// private void fetchData() {
// JsonArrayRequest request = new JsonArrayRequest(GET_CATEGORY_DETAIL + category_id, new Response.Listener<JSONArray>() {
// @Override
// public void onResponse(JSONArray response) {
// if (response == null) {
// Toast.makeText(getApplicationContext(), R.string.failed_fetch_data, Toast.LENGTH_LONG).show();
// return;
// }
//
// List<Product> items = new Gson().fromJson(response.toString(), new TypeToken<List<Product>>() {
// }.getType());
//
// // adding contacts to contacts list
// productList.clear();
// productList.addAll(items);
//
// // refreshing recycler view
// mAdapter.notifyDataSetChanged();
// }
// }, new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
// // error in getting json
// Log.e("INFO", "Error: " + error.getMessage());
// Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
// }
// });
//
// MyApplication.getInstance().addToRequestQueue(request);
// }
public void getEcomProduct(EcomProductRequestBean ecomProductRequestBean) {
try {
final ProgressDialog progressDialog = new ProgressDialog(ActivityProduct.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<EcomProductResponseBean> call = apiService.getEcomProduct(ecomProductRequestBean);
call.enqueue(new Callback<EcomProductResponseBean>() {
@Override
public void onResponse(Call<EcomProductResponseBean> call, Response<EcomProductResponseBean> response) {
EcomProductResponseBean ecomCategoryResponseBean = response.body();
if (ecomCategoryResponseBean.getCategorieInfo()!=null){
productList.clear();
productList.addAll(ecomCategoryResponseBean.getCategorieInfo());
mAdapter = new RecyclerAdapterProduct(ActivityProduct.this, productList, ActivityProduct.this);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(ActivityProduct.this, 2);
recyclerView.setLayoutManager(mLayoutManager);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(ActivityProduct.this, R.dimen.item_offset);
recyclerView.addItemDecoration(itemDecoration);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<EcomProductResponseBean> call, Throwable t) {
// Log error here since request failed
Toast.makeText(ActivityProduct.this, t.getMessage(), Toast.LENGTH_LONG).show();
// tv_msg.setVisibility(View.VISIBLE);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
@Override
public void onContactSelected(Product product) {
Intent intent = new Intent(getApplicationContext(), ActivityProductDetail.class);
intent.putExtra("product_id", product.getEcomm_product_id());
intent.putExtra("title", product.getEcomm_product_name());
intent.putExtra("image", product.getEcomm_product_image1());
intent.putExtra("product_price", product.getEcomm_product_offer_price());
intent.putExtra("product_description", product.getEcomm_product_description());
// intent.putExtra("product_quantity", product.getProduct_quantity());
intent.putExtra("product_status", "Available");
// intent.putExtra("currency_code", product.getCurrency_code());
intent.putExtra("category_name", product.getEcomm_product_category_id());
startActivity(intent);
}
}
| UTF-8 | Java | 11,131 | java | ActivityProduct.java | Java | [] | null | [] | package com.magnum.handloom.activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.magnum.handloom.R;
import com.magnum.handloom.adaptor.EcomCategoryListViewListAdapter;
import com.magnum.handloom.adaptor.RecyclerAdapterProduct;
import com.magnum.handloom.request.EcomProductRequestBean;
import com.magnum.handloom.response.EcomCategoryResponseBean;
import com.magnum.handloom.response.EcomProductResponseBean;
import com.magnum.handloom.response.Product;
import com.magnum.handloom.rest.ApiClient;
import com.magnum.handloom.rest.ApiInterface;
import com.magnum.handloom.rest.Config;
import com.magnum.handloom.utilities.ItemOffsetDecoration;
import com.magnum.handloom.utilities.UserPreference;
import com.magnum.handloom.utilities.Utils;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ActivityProduct extends AppCompatActivity implements RecyclerAdapterProduct.ContactsAdapterListener {
private RecyclerView recyclerView;
private List<Product> productList;
private RecyclerAdapterProduct mAdapter;
private SearchView searchView;
SwipeRefreshLayout swipeRefreshLayout = null;
private String category_id, category_name;
public Toolbar toolbar;
int p_n = 0;
boolean isEnd = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
Intent intent = getIntent();
category_id = intent.getStringExtra("category_id");
category_name = intent.getStringExtra("category_name");
// toolbar fancy stuff
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(category_name);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
recyclerView = findViewById(R.id.recycler_view);
productList = new ArrayList<>();
// fetchData();
EcomProductRequestBean ecomProductRequestBean=new EcomProductRequestBean();
ecomProductRequestBean.setUser_id(UserPreference.getPreference(ActivityProduct.this).getUsers_id());
ecomProductRequestBean.setCategory_id(category_id);
ecomProductRequestBean.setPage_no(0);
getEcomProduct(ecomProductRequestBean);
onRefresh();
}
private void onRefresh() {
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
productList.clear();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (Utils.isNetworkAvailable(ActivityProduct.this)) {
swipeRefreshLayout.setRefreshing(false);
// fetchData();
EcomProductRequestBean ecomProductRequestBean=new EcomProductRequestBean();
ecomProductRequestBean.setUser_id(UserPreference.getPreference(ActivityProduct.this).getUsers_id());
ecomProductRequestBean.setCategory_id(category_id);
ecomProductRequestBean.setPage_no(0);
getEcomProduct(ecomProductRequestBean);
} else {
swipeRefreshLayout.setRefreshing(false);
Toast.makeText(getApplicationContext(), getResources().getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
}
}, 1500);
}
});
}
// private void fetchData() {
// JsonArrayRequest request = new JsonArrayRequest(GET_CATEGORY_DETAIL + category_id, new Response.Listener<JSONArray>() {
// @Override
// public void onResponse(JSONArray response) {
// if (response == null) {
// Toast.makeText(getApplicationContext(), R.string.failed_fetch_data, Toast.LENGTH_LONG).show();
// return;
// }
//
// List<Product> items = new Gson().fromJson(response.toString(), new TypeToken<List<Product>>() {
// }.getType());
//
// // adding contacts to contacts list
// productList.clear();
// productList.addAll(items);
//
// // refreshing recycler view
// mAdapter.notifyDataSetChanged();
// }
// }, new Response.ErrorListener() {
// @Override
// public void onErrorResponse(VolleyError error) {
// // error in getting json
// Log.e("INFO", "Error: " + error.getMessage());
// Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
// }
// });
//
// MyApplication.getInstance().addToRequestQueue(request);
// }
public void getEcomProduct(EcomProductRequestBean ecomProductRequestBean) {
try {
final ProgressDialog progressDialog = new ProgressDialog(ActivityProduct.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<EcomProductResponseBean> call = apiService.getEcomProduct(ecomProductRequestBean);
call.enqueue(new Callback<EcomProductResponseBean>() {
@Override
public void onResponse(Call<EcomProductResponseBean> call, Response<EcomProductResponseBean> response) {
EcomProductResponseBean ecomCategoryResponseBean = response.body();
if (ecomCategoryResponseBean.getCategorieInfo()!=null){
productList.clear();
productList.addAll(ecomCategoryResponseBean.getCategorieInfo());
mAdapter = new RecyclerAdapterProduct(ActivityProduct.this, productList, ActivityProduct.this);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(ActivityProduct.this, 2);
recyclerView.setLayoutManager(mLayoutManager);
ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(ActivityProduct.this, R.dimen.item_offset);
recyclerView.addItemDecoration(itemDecoration);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<EcomProductResponseBean> call, Throwable t) {
// Log error here since request failed
Toast.makeText(ActivityProduct.this, t.getMessage(), Toast.LENGTH_LONG).show();
// tv_msg.setVisibility(View.VISIBLE);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
@Override
public void onContactSelected(Product product) {
Intent intent = new Intent(getApplicationContext(), ActivityProductDetail.class);
intent.putExtra("product_id", product.getEcomm_product_id());
intent.putExtra("title", product.getEcomm_product_name());
intent.putExtra("image", product.getEcomm_product_image1());
intent.putExtra("product_price", product.getEcomm_product_offer_price());
intent.putExtra("product_description", product.getEcomm_product_description());
// intent.putExtra("product_quantity", product.getProduct_quantity());
intent.putExtra("product_status", "Available");
// intent.putExtra("currency_code", product.getCurrency_code());
intent.putExtra("category_name", product.getEcomm_product_category_id());
startActivity(intent);
}
}
| 11,131 | 0.63121 | 0.629234 | 259 | 41.976833 | 31.300503 | 143 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.667954 | false | false | 9 |
b4e95c2ec9295e547c1751e355eeb34720b45000 | 19,756,849,588,427 | f22b1419d52a7c42a9de8cbe621f34d74b6fd0f3 | /homework2/src/task2_2.java | 0e94134b800631bdd5b6d539dd2e4be8f4cac464 | [] | no_license | alexeykozovsky/java_study | https://github.com/alexeykozovsky/java_study | e7144bfc7127a76f75665528ee43a05ee3357cb6 | 977a392ebcc3c181f4d7067158b63883bb4a1523 | refs/heads/master | 2020-11-24T06:24:02.912000 | 2020-02-13T22:06:21 | 2020-02-13T22:06:21 | 227,994,593 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class task2_2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Введите длину массива: ");
int len = in.nextInt(); // Читаем с консоли размер массива и записываем в len
int array[] = new int[len]; // Создаём массив int размером в len
System.out.println("Введите элемент массива: ");
for (int i = 0; i < len; i++) {
array[i] = in.nextInt(); // Заполняем массив элементами, введёнными с консоли
}
// Массив создан
// do ... while
System.out.print ("Вывод элементов массива:");
int i1 = 0;
do {
System.out.print(" " + array[i1]);
i1+=2;
} while (i1 < len);
System.out.println("\n Следующий способ");
// while
System.out.print ("Вывод элементов массива:");
int i2 = 0;
while (i2 < len) {
System.out.print(" " + array[i2]);
i2+=2;
}
System.out.println("\n Следующий способ");
// for
System.out.print ("Вывод элементов массива:");
for (int i3 = 0; i3 < len; i3+=2) {
System.out.print (" " + array[i3]);
}
System.out.println("\n Следующий способ");
// foreach
System.out.print ("Вывод элементов массива:");
for (int i4: array) {
if (i4%2 == 1) {
System.out.print (" " + array[i4-1]);
}
}
System.out.println("\n Конец");
}
}
| UTF-8 | Java | 1,856 | java | task2_2.java | Java | [] | null | [] | import java.util.Scanner;
public class task2_2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Введите длину массива: ");
int len = in.nextInt(); // Читаем с консоли размер массива и записываем в len
int array[] = new int[len]; // Создаём массив int размером в len
System.out.println("Введите элемент массива: ");
for (int i = 0; i < len; i++) {
array[i] = in.nextInt(); // Заполняем массив элементами, введёнными с консоли
}
// Массив создан
// do ... while
System.out.print ("Вывод элементов массива:");
int i1 = 0;
do {
System.out.print(" " + array[i1]);
i1+=2;
} while (i1 < len);
System.out.println("\n Следующий способ");
// while
System.out.print ("Вывод элементов массива:");
int i2 = 0;
while (i2 < len) {
System.out.print(" " + array[i2]);
i2+=2;
}
System.out.println("\n Следующий способ");
// for
System.out.print ("Вывод элементов массива:");
for (int i3 = 0; i3 < len; i3+=2) {
System.out.print (" " + array[i3]);
}
System.out.println("\n Следующий способ");
// foreach
System.out.print ("Вывод элементов массива:");
for (int i4: array) {
if (i4%2 == 1) {
System.out.print (" " + array[i4-1]);
}
}
System.out.println("\n Конец");
}
}
| 1,856 | 0.506386 | 0.489144 | 50 | 30.32 | 22.648127 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.58 | false | false | 9 |
112c1286c1b76db5495d93d4273b3f03551dec6e | 14,955,076,143,927 | a59f03b222eb72cee28018705ddd04f8b518cac7 | /triana-toolboxes/common/src/main/java/common/array/ArrayToStream.java | 9b29c2e18892b5d58cfac4ad8059729101e169a8 | [
"Apache-2.0"
] | permissive | Janix520/Triana | https://github.com/Janix520/Triana | 487c90a0d822d8a6338f940fb5e4740ba5bd069f | da48ffaa0183f59e3fe7c6dc59d9f91234e65809 | refs/heads/master | 2022-03-27T19:29:45.050000 | 2014-08-29T17:43:13 | 2014-08-29T17:43:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package common.array;
import org.trianacode.taskgraph.Unit;
import triana.types.clipins.SequenceClipIn;
/**
* Turns an array into a stream of data
*
* @author Ian Wang
* @version $Revision: 2921 $
*/
public class ArrayToStream extends Unit {
/*
* Called whenever there is data for the unit to process
*/
public void process() throws Exception {
java.lang.Object[] input = (java.lang.Object[]) getInputAtNode(0);
String groupid = getToolName() + ":" + System.currentTimeMillis() + ":" + ((int) Math.random() * 1000000);
for (int count = 0; count < input.length; count++) {
SequenceClipIn clipin = new SequenceClipIn(groupid, count, input.length);
clipin.setComponentType(input.getClass().getComponentType().getName());
putClipIn(SequenceClipIn.SEQUENCE_CLIPIN_TAG, clipin);
output(input[count]);
}
}
/**
* Called when the unit is created. Initialises the unit's properties and parameters.
*/
public void init() {
super.init();
// Initialise node properties
setDefaultInputNodes(1);
setMinimumInputNodes(1);
setMaximumInputNodes(1);
setDefaultOutputNodes(1);
setMinimumOutputNodes(0);
setMaximumOutputNodes(Integer.MAX_VALUE);
// Initialise parameter update policy and output policy
setParameterUpdatePolicy(PROCESS_UPDATE);
setOutputPolicy(CLONE_MULTIPLE_OUTPUT);
// Initialise pop-up description and help file location
setPopUpDescription("Turns an array into a stream of data");
setHelpFileLocation("ArrayToStream.html");
}
/**
* Called when the unit is reset. Restores the unit's variables to values specified by the parameters.
*/
public void reset() {
}
/**
* Called when the unit is disposed of.
*/
public void dispose() {
// Insert code to clean-up ArrayToStream (e.g. close open files)
}
/**
* Called a parameters is updated (e.g. by the GUI)
*/
public void parameterUpdate(String paramname, Object value) {
// Code to update local variables
}
/**
* @return an array of the types accepted by each input node. For node indexes not covered the types specified by
* getInputTypes() are assumed.
*/
public String[][] getNodeInputTypes() {
return new String[0][0];
}
/**
* @return an array of the input types accepted by nodes not covered by getNodeInputTypes().
*/
public String[] getInputTypes() {
return new String[]{"java.lang.Object[]"};
}
/**
* @return an array of the types output by each output node. For node indexes not covered the types specified by
* getOutputTypes() are assumed.
*/
public String[][] getNodeOutputTypes() {
return new String[0][0];
}
/**
* @return an array of the input types output by nodes not covered by getNodeOutputTypes().
*/
public String[] getOutputTypes() {
return new String[]{"java.lang.Object"};
}
}
| UTF-8 | Java | 3,141 | java | ArrayToStream.java | Java | [
{
"context": "Turns an array into a stream of data\n *\n * @author Ian Wang\n * @version $Revision: 2921 $\n */\npublic class Ar",
"end": 174,
"score": 0.9996058344841003,
"start": 166,
"tag": "NAME",
"value": "Ian Wang"
}
] | null | [] | package common.array;
import org.trianacode.taskgraph.Unit;
import triana.types.clipins.SequenceClipIn;
/**
* Turns an array into a stream of data
*
* @author <NAME>
* @version $Revision: 2921 $
*/
public class ArrayToStream extends Unit {
/*
* Called whenever there is data for the unit to process
*/
public void process() throws Exception {
java.lang.Object[] input = (java.lang.Object[]) getInputAtNode(0);
String groupid = getToolName() + ":" + System.currentTimeMillis() + ":" + ((int) Math.random() * 1000000);
for (int count = 0; count < input.length; count++) {
SequenceClipIn clipin = new SequenceClipIn(groupid, count, input.length);
clipin.setComponentType(input.getClass().getComponentType().getName());
putClipIn(SequenceClipIn.SEQUENCE_CLIPIN_TAG, clipin);
output(input[count]);
}
}
/**
* Called when the unit is created. Initialises the unit's properties and parameters.
*/
public void init() {
super.init();
// Initialise node properties
setDefaultInputNodes(1);
setMinimumInputNodes(1);
setMaximumInputNodes(1);
setDefaultOutputNodes(1);
setMinimumOutputNodes(0);
setMaximumOutputNodes(Integer.MAX_VALUE);
// Initialise parameter update policy and output policy
setParameterUpdatePolicy(PROCESS_UPDATE);
setOutputPolicy(CLONE_MULTIPLE_OUTPUT);
// Initialise pop-up description and help file location
setPopUpDescription("Turns an array into a stream of data");
setHelpFileLocation("ArrayToStream.html");
}
/**
* Called when the unit is reset. Restores the unit's variables to values specified by the parameters.
*/
public void reset() {
}
/**
* Called when the unit is disposed of.
*/
public void dispose() {
// Insert code to clean-up ArrayToStream (e.g. close open files)
}
/**
* Called a parameters is updated (e.g. by the GUI)
*/
public void parameterUpdate(String paramname, Object value) {
// Code to update local variables
}
/**
* @return an array of the types accepted by each input node. For node indexes not covered the types specified by
* getInputTypes() are assumed.
*/
public String[][] getNodeInputTypes() {
return new String[0][0];
}
/**
* @return an array of the input types accepted by nodes not covered by getNodeInputTypes().
*/
public String[] getInputTypes() {
return new String[]{"java.lang.Object[]"};
}
/**
* @return an array of the types output by each output node. For node indexes not covered the types specified by
* getOutputTypes() are assumed.
*/
public String[][] getNodeOutputTypes() {
return new String[0][0];
}
/**
* @return an array of the input types output by nodes not covered by getNodeOutputTypes().
*/
public String[] getOutputTypes() {
return new String[]{"java.lang.Object"};
}
}
| 3,139 | 0.625279 | 0.618274 | 111 | 27.270269 | 30.42964 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.27027 | false | false | 9 |
ef768243ece3109ec32d04c6c066e10ead14ea3b | 6,030,134,111,544 | 29693091f634cc1e259a11801ff3e0808a9ae278 | /src/changeSingleton/ChangeViewsSingleton.java | bd2adae22ebf2c0b790326d922f6cc512c4929bd | [] | no_license | jesus5413/booki | https://github.com/jesus5413/booki | 5a2d40d462f600aae644409039685fb2470971a7 | 808d889efac2f267f7d366715970584b63093c34 | refs/heads/master | 2018-09-17T21:23:10.475000 | 2018-05-08T18:46:00 | 2018-05-08T18:46:00 | 118,393,722 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package changeSingleton;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import controller.MainMenuController;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.BorderPane;
import view.MainLauncher;
public class ChangeViewsSingleton {
private static ChangeViewsSingleton singleton = null;
private static Logger logger = LogManager.getLogger(MainMenuController.class);
private ChangeViewsSingleton() {
}
public static ChangeViewsSingleton getInstance() {
if(singleton == null) {
singleton = new ChangeViewsSingleton();
}
return singleton;
}
public void changeViews(String x) {
try {
String fxmlPath = "";
BorderPane test = MainLauncher.getMainPane();
if(x == "z") {
fxmlPath = "/fxml/authorsTableView.fxml";
}
if(x == "b") {
fxmlPath = "/fxml/authorDetail.fxml";
}
if(x == "y") {
fxmlPath = "/fxml/bookDetail.fxml";
}
if(x == "t") {
fxmlPath = "/fxml/bookTableView.fxml";
}
if(x == "a") {
fxmlPath = "/fxml/auditTableView.fxml";
}
if(x == "c") {
fxmlPath = "/fxml/authorAuditTrail.fxml";
}
if(x == "e") {
fxmlPath = "/fxml/excel.fxml";
}
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource(fxmlPath));
test.setCenter(null);
test.setCenter(root);
} catch (IOException e) {
logger.error("Error when trying to change views");
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,474 | java | ChangeViewsSingleton.java | Java | [] | null | [] | package changeSingleton;
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import controller.MainMenuController;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.BorderPane;
import view.MainLauncher;
public class ChangeViewsSingleton {
private static ChangeViewsSingleton singleton = null;
private static Logger logger = LogManager.getLogger(MainMenuController.class);
private ChangeViewsSingleton() {
}
public static ChangeViewsSingleton getInstance() {
if(singleton == null) {
singleton = new ChangeViewsSingleton();
}
return singleton;
}
public void changeViews(String x) {
try {
String fxmlPath = "";
BorderPane test = MainLauncher.getMainPane();
if(x == "z") {
fxmlPath = "/fxml/authorsTableView.fxml";
}
if(x == "b") {
fxmlPath = "/fxml/authorDetail.fxml";
}
if(x == "y") {
fxmlPath = "/fxml/bookDetail.fxml";
}
if(x == "t") {
fxmlPath = "/fxml/bookTableView.fxml";
}
if(x == "a") {
fxmlPath = "/fxml/auditTableView.fxml";
}
if(x == "c") {
fxmlPath = "/fxml/authorAuditTrail.fxml";
}
if(x == "e") {
fxmlPath = "/fxml/excel.fxml";
}
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource(fxmlPath));
test.setCenter(null);
test.setCenter(root);
} catch (IOException e) {
logger.error("Error when trying to change views");
e.printStackTrace();
}
}
}
| 1,474 | 0.66825 | 0.666893 | 64 | 22.03125 | 19.887157 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.359375 | false | false | 9 |
391e349d9d4a896bd4d39f0fc5a8288f871bf3af | 6,030,134,108,185 | 28c0700e0eee225da630b33cbd6aa77cabcbf539 | /app/src/main/java/com/codehub/pfacademy/AbstrctActivity.java | dafe36af8a6b3564d36f7f75f010d7c96003535c | [] | no_license | GeorgiaKasfiki/PFAcademy | https://github.com/GeorgiaKasfiki/PFAcademy | 933e43417c15377a46531b2a82fa2a32d6887f5b | 65fae7023381a1b20f36dca6237ec47a4d202a0c | refs/heads/master | 2022-09-09T20:37:44.321000 | 2020-05-31T09:47:40 | 2020-05-31T09:47:40 | 268,250,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codehub.pfacademy;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public abstract class AbstrctActivity extends AppCompatActivity{
abstract void initial();
abstract void running();
abstract void stopped();
abstract void destroy();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initial();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
running();
}
@Override
protected void onResume() {
super.onResume();
}
//Running
@Override
protected void onPause() {
super.onPause();
stopped();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
destroy();
}
}
| UTF-8 | Java | 1,208 | java | AbstrctActivity.java | Java | [] | null | [] | package com.codehub.pfacademy;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public abstract class AbstrctActivity extends AppCompatActivity{
abstract void initial();
abstract void running();
abstract void stopped();
abstract void destroy();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initial();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void onPostCreate(@Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
running();
}
@Override
protected void onResume() {
super.onResume();
}
//Running
@Override
protected void onPause() {
super.onPause();
stopped();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
destroy();
}
}
| 1,208 | 0.623344 | 0.623344 | 69 | 16.47826 | 16.956558 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.304348 | false | false | 9 |
1cdeed1710fb3a09e2c7e768637beae3329a2dd8 | 31,233,002,200,659 | d16d43dbec71e837d17df247b041b9a677000f4f | /Challenges/WonderWoman/Player.java | 83e72af6b63e9b916d0e7063c7bf1b0051b1658b | [] | no_license | Wissben/CodinGame | https://github.com/Wissben/CodinGame | 72af81947dab030d29e1cd5f828e32058eb4aea7 | 8c8ce01287b10d41ce8b03b8a2376b38d8c4d8dc | refs/heads/master | 2020-12-02T23:58:10.806000 | 2017-07-01T14:19:40 | 2017-07-01T14:19:40 | 95,967,882 | 3 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
import java.io.*;
import java.math.*;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class unit {
public int x,y;
public int level;
public Grid playground;
public unit (int x , int y,Grid g)
{
this.x = x;
this.y = y;
this.level = 0;
this.plavoid=g;
}
public String move_build(String move , String build)
{
String act = move+" "+build;
if(move == "N" || build =="N" )
{
x++;
if(this.outOfBound())
this.regulate();
this.playground[
}
if(move == "
}
public void regulate()
{
if(this.x>playground.width)
this.x=width;
if(this.x<0)
this.x=0;
if(this.y > playground.height)
this.y)playground.height;
if(y<0)
y=0;
}
public boolean outOfBound()
{
return this.x>this.playground.width ||
this.x<0 ||
this.y>this.playground.height ||
this.y<0;
}
}
class Grid{
int width , height ;
int maxLevel;
String[] mat;
public Grid(String[] mat)
{
if(mat != null)
{
this.width=mat[0].length();
this.height=mat.size;
this.mat= mat.clone();
}
}
}
class Player {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int unitsPerPlayer = in.nextInt();
// game loop
while (true) {
for (int i = 0; i < size; i++) {
String row = in.next();
}
for (int i = 0; i < unitsPerPlayer; i++) {
int unitX = in.nextInt();
int unitY = in.nextInt();
}
for (int i = 0; i < unitsPerPlayer; i++) {
int otherX = in.nextInt();
int otherY = in.nextInt();
}
int legalActions = in.nextInt();
for (int i = 0; i < legalActions; i++) {
String atype = in.next();
int index = in.nextInt();
String dir1 = in.next();
String dir2 = in.next();
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
System.out.println("MOVE&BUILD 0 N S");
}
}
}
| UTF-8 | Java | 2,611 | java | Player.java | Java | [] | null | [] | import java.util.*;
import java.io.*;
import java.math.*;
/**
* Auto-generated code below aims at helping you parse
* the standard input according to the problem statement.
**/
class unit {
public int x,y;
public int level;
public Grid playground;
public unit (int x , int y,Grid g)
{
this.x = x;
this.y = y;
this.level = 0;
this.plavoid=g;
}
public String move_build(String move , String build)
{
String act = move+" "+build;
if(move == "N" || build =="N" )
{
x++;
if(this.outOfBound())
this.regulate();
this.playground[
}
if(move == "
}
public void regulate()
{
if(this.x>playground.width)
this.x=width;
if(this.x<0)
this.x=0;
if(this.y > playground.height)
this.y)playground.height;
if(y<0)
y=0;
}
public boolean outOfBound()
{
return this.x>this.playground.width ||
this.x<0 ||
this.y>this.playground.height ||
this.y<0;
}
}
class Grid{
int width , height ;
int maxLevel;
String[] mat;
public Grid(String[] mat)
{
if(mat != null)
{
this.width=mat[0].length();
this.height=mat.size;
this.mat= mat.clone();
}
}
}
class Player {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int unitsPerPlayer = in.nextInt();
// game loop
while (true) {
for (int i = 0; i < size; i++) {
String row = in.next();
}
for (int i = 0; i < unitsPerPlayer; i++) {
int unitX = in.nextInt();
int unitY = in.nextInt();
}
for (int i = 0; i < unitsPerPlayer; i++) {
int otherX = in.nextInt();
int otherY = in.nextInt();
}
int legalActions = in.nextInt();
for (int i = 0; i < legalActions; i++) {
String atype = in.next();
int index = in.nextInt();
String dir1 = in.next();
String dir2 = in.next();
}
// Write an action using System.out.println()
// To debug: System.err.println("Debug messages...");
System.out.println("MOVE&BUILD 0 N S");
}
}
}
| 2,611 | 0.44887 | 0.443125 | 110 | 22.736364 | 17.491129 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.