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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e0852658ba9f58a5fdf08461eaf67b697494cc8b | 7,507,602,900,493 | fa93c9be2923e697fb8a2066f8fb65c7718cdec7 | /sources/xwKerWrNChj/xwKerWrNChj/xwKerWrNChj/xwKerWrNChj/Qnf0Cfjkr0jPeIjQbdNVc33uFHO6g/drPJedvLehhLIDUBStFv2zCqMzLzQ.java | 1d6de6ca420748946783866bdaef1d74d44799f8 | [] | no_license | Auch-Auch/avito_source | https://github.com/Auch-Auch/avito_source | b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b | 76fdcc5b7e036c57ecc193e790b0582481768cdc | refs/heads/master | 2023-05-06T01:32:43.014000 | 2021-05-25T10:19:22 | 2021-05-25T10:19:22 | 370,650,685 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.Qnf0Cfjkr0jPeIjQbdNVc33uFHO6g;
import a2.b.a.a.a;
import androidx.lifecycle.ViewModelKt;
import com.sumsub.sns.core.domain.FaceDetector;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.internal.Lambda;
import kotlinx.coroutines.BuildersKt;
import timber.log.Timber;
import xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.Qnf0Cfjkr0jPeIjQbdNVc33uFHO6g.tjrpI83q5sk1iMEXPz1hKo;
public final class drPJedvLehhLIDUBStFv2zCqMzLzQ extends Lambda implements Function1<FaceDetector.FaceDetectorResult, Unit> {
public final /* synthetic */ tjrpI83q5sk1iMEXPz1hKo Cwa7EHp4RmMFhwpOCPWojiqbo;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public drPJedvLehhLIDUBStFv2zCqMzLzQ(tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko) {
super(1);
this.Cwa7EHp4RmMFhwpOCPWojiqbo = tjrpi83q5sk1imexpz1hko;
}
/* Return type fixed from 'java.lang.Object' to match base method */
/* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */
@Override // kotlin.jvm.functions.Function1
public Unit invoke(FaceDetector.FaceDetectorResult faceDetectorResult) {
FaceDetector.FaceDetectorResult faceDetectorResult2 = faceDetectorResult;
tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko = this.Cwa7EHp4RmMFhwpOCPWojiqbo;
FaceDetector.RawImage image = faceDetectorResult2.getImage();
if (tjrpi83q5sk1imexpz1hko.mdHgHuGChkRJqBUMUk707 <= 0 && tjrpi83q5sk1imexpz1hko.qNDua1J9EaZOsmugz0J != 0 && System.currentTimeMillis() - tjrpi83q5sk1imexpz1hko.aHA7rWvEdW6bbOdx1EKD4aVF0k >= 0) {
BuildersKt.launch$default(ViewModelKt.getViewModelScope(tjrpi83q5sk1imexpz1hko), null, null, new djGN3DbfslkNo4T0(tjrpi83q5sk1imexpz1hko, image, new FaceDetector.Size(image.getWidth(), image.getHeight()), "NOT_ALIGNED", null), 3, null);
tjrpi83q5sk1imexpz1hko.aHA7rWvEdW6bbOdx1EKD4aVF0k = System.currentTimeMillis() + ((long) 8000);
}
if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.NoFace) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.UGPkPVVOmk179tTX8sQoOodQt.Cwa7EHp4RmMFhwpOCPWojiqbo);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.TooManyFaces) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.alNh9hLeM39.Cwa7EHp4RmMFhwpOCPWojiqbo);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.NotInCaptureBox) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(new tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.C0694BYfFGQyI88(((FaceDetector.FaceDetectorResult.NotInCaptureBox) faceDetectorResult2).getFaceBox()));
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.Error) {
StringBuilder L = a.L("FaceDetectorResult: ");
L.append(((FaceDetector.FaceDetectorResult.Error) faceDetectorResult2).getE());
Timber.e(L.toString(), new Object[0]);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.FaceSegment) {
FaceDetector.FaceDetectorResult.FaceSegment faceSegment = (FaceDetector.FaceDetectorResult.FaceSegment) faceDetectorResult2;
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(new tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.VVeXCTyov0hLti0HOLqom2taL0gk(faceSegment.getFaceBox()));
tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko2 = this.Cwa7EHp4RmMFhwpOCPWojiqbo;
if (!tjrpi83q5sk1imexpz1hko2.YWVVuaVDYicbKjhsZbjQiRooZ) {
tjrpi83q5sk1imexpz1hko2.idM1z15K75 = System.currentTimeMillis() + ((long) 200);
} else {
int i = tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707;
if (i == tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J && i > 0 && tjrpi83q5sk1imexpz1hko2.lk42nG4RRcMiHe8r6w == null) {
Timer timer = new Timer();
timer.schedule(new A8EntBCcqmn(tjrpi83q5sk1imexpz1hko2), TimeUnit.SECONDS.toMillis(2));
tjrpi83q5sk1imexpz1hko2.lk42nG4RRcMiHe8r6w = timer;
}
if (tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707 < tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J && System.currentTimeMillis() - tjrpi83q5sk1imexpz1hko2.idM1z15K75 >= 0) {
tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707++;
BuildersKt.launch$default(ViewModelKt.getViewModelScope(tjrpi83q5sk1imexpz1hko2), null, null, new djGN3DbfslkNo4T0(tjrpi83q5sk1imexpz1hko2, faceSegment.getImage(), faceSegment.getTrackSize(), "OK", null), 3, null);
tjrpi83q5sk1imexpz1hko2.idM1z15K75 = System.currentTimeMillis() + ((long) 200);
tjrpi83q5sk1imexpz1hko2.M6kaoQeazePMH0Sq8.postValue(new tjrpI83q5sk1iMEXPz1hKo.alNh9hLeM39.C0698alNh9hLeM39(((float) tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707) / ((float) tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J)));
}
}
}
return Unit.INSTANCE;
}
}
| UTF-8 | Java | 5,290 | java | drPJedvLehhLIDUBStFv2zCqMzLzQ.java | Java | [] | null | [] | package xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.Qnf0Cfjkr0jPeIjQbdNVc33uFHO6g;
import a2.b.a.a.a;
import androidx.lifecycle.ViewModelKt;
import com.sumsub.sns.core.domain.FaceDetector;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.internal.Lambda;
import kotlinx.coroutines.BuildersKt;
import timber.log.Timber;
import xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.xwKerWrNChj.Qnf0Cfjkr0jPeIjQbdNVc33uFHO6g.tjrpI83q5sk1iMEXPz1hKo;
public final class drPJedvLehhLIDUBStFv2zCqMzLzQ extends Lambda implements Function1<FaceDetector.FaceDetectorResult, Unit> {
public final /* synthetic */ tjrpI83q5sk1iMEXPz1hKo Cwa7EHp4RmMFhwpOCPWojiqbo;
/* JADX INFO: super call moved to the top of the method (can break code semantics) */
public drPJedvLehhLIDUBStFv2zCqMzLzQ(tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko) {
super(1);
this.Cwa7EHp4RmMFhwpOCPWojiqbo = tjrpi83q5sk1imexpz1hko;
}
/* Return type fixed from 'java.lang.Object' to match base method */
/* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object] */
@Override // kotlin.jvm.functions.Function1
public Unit invoke(FaceDetector.FaceDetectorResult faceDetectorResult) {
FaceDetector.FaceDetectorResult faceDetectorResult2 = faceDetectorResult;
tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko = this.Cwa7EHp4RmMFhwpOCPWojiqbo;
FaceDetector.RawImage image = faceDetectorResult2.getImage();
if (tjrpi83q5sk1imexpz1hko.mdHgHuGChkRJqBUMUk707 <= 0 && tjrpi83q5sk1imexpz1hko.qNDua1J9EaZOsmugz0J != 0 && System.currentTimeMillis() - tjrpi83q5sk1imexpz1hko.aHA7rWvEdW6bbOdx1EKD4aVF0k >= 0) {
BuildersKt.launch$default(ViewModelKt.getViewModelScope(tjrpi83q5sk1imexpz1hko), null, null, new djGN3DbfslkNo4T0(tjrpi83q5sk1imexpz1hko, image, new FaceDetector.Size(image.getWidth(), image.getHeight()), "NOT_ALIGNED", null), 3, null);
tjrpi83q5sk1imexpz1hko.aHA7rWvEdW6bbOdx1EKD4aVF0k = System.currentTimeMillis() + ((long) 8000);
}
if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.NoFace) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.UGPkPVVOmk179tTX8sQoOodQt.Cwa7EHp4RmMFhwpOCPWojiqbo);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.TooManyFaces) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.alNh9hLeM39.Cwa7EHp4RmMFhwpOCPWojiqbo);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.NotInCaptureBox) {
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(new tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.C0694BYfFGQyI88(((FaceDetector.FaceDetectorResult.NotInCaptureBox) faceDetectorResult2).getFaceBox()));
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.Error) {
StringBuilder L = a.L("FaceDetectorResult: ");
L.append(((FaceDetector.FaceDetectorResult.Error) faceDetectorResult2).getE());
Timber.e(L.toString(), new Object[0]);
} else if (faceDetectorResult2 instanceof FaceDetector.FaceDetectorResult.FaceSegment) {
FaceDetector.FaceDetectorResult.FaceSegment faceSegment = (FaceDetector.FaceDetectorResult.FaceSegment) faceDetectorResult2;
this.Cwa7EHp4RmMFhwpOCPWojiqbo.cPMlB5HN7W4Ve3yHBwMXNEUvD.postValue(new tjrpI83q5sk1iMEXPz1hKo.BYfFGQyI88.VVeXCTyov0hLti0HOLqom2taL0gk(faceSegment.getFaceBox()));
tjrpI83q5sk1iMEXPz1hKo tjrpi83q5sk1imexpz1hko2 = this.Cwa7EHp4RmMFhwpOCPWojiqbo;
if (!tjrpi83q5sk1imexpz1hko2.YWVVuaVDYicbKjhsZbjQiRooZ) {
tjrpi83q5sk1imexpz1hko2.idM1z15K75 = System.currentTimeMillis() + ((long) 200);
} else {
int i = tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707;
if (i == tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J && i > 0 && tjrpi83q5sk1imexpz1hko2.lk42nG4RRcMiHe8r6w == null) {
Timer timer = new Timer();
timer.schedule(new A8EntBCcqmn(tjrpi83q5sk1imexpz1hko2), TimeUnit.SECONDS.toMillis(2));
tjrpi83q5sk1imexpz1hko2.lk42nG4RRcMiHe8r6w = timer;
}
if (tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707 < tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J && System.currentTimeMillis() - tjrpi83q5sk1imexpz1hko2.idM1z15K75 >= 0) {
tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707++;
BuildersKt.launch$default(ViewModelKt.getViewModelScope(tjrpi83q5sk1imexpz1hko2), null, null, new djGN3DbfslkNo4T0(tjrpi83q5sk1imexpz1hko2, faceSegment.getImage(), faceSegment.getTrackSize(), "OK", null), 3, null);
tjrpi83q5sk1imexpz1hko2.idM1z15K75 = System.currentTimeMillis() + ((long) 200);
tjrpi83q5sk1imexpz1hko2.M6kaoQeazePMH0Sq8.postValue(new tjrpI83q5sk1iMEXPz1hKo.alNh9hLeM39.C0698alNh9hLeM39(((float) tjrpi83q5sk1imexpz1hko2.mdHgHuGChkRJqBUMUk707) / ((float) tjrpi83q5sk1imexpz1hko2.qNDua1J9EaZOsmugz0J)));
}
}
}
return Unit.INSTANCE;
}
}
| 5,290 | 0.757278 | 0.683176 | 67 | 77.955223 | 61.841984 | 248 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.925373 | false | false | 13 |
7a1871c7a15ed4b571b71aa7f5ac50868cf701d7 | 12,867,722,057,837 | 662ca07b6facd71fd2c4d61d5862d0017f0db47a | /src/main/java/com/cc/admin/controller/AdminController.java | f2a052e1577048d92afeb1102e3132e43263714f | [] | no_license | chenqifeng1006/convenienceBus | https://github.com/chenqifeng1006/convenienceBus | 27c915d9d13c34d06720d0345ff1df84cd077d46 | b19b55c8215f10281c7d9a639b7401d810d82fee | refs/heads/master | 2020-03-30T08:03:11.909000 | 2016-04-26T03:31:37 | 2016-04-26T03:31:37 | 57,093,773 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cc.admin.controller;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cc.admin.dto.Admin;
import com.cc.admin.enums.AdminRole;
import com.cc.admin.service.AdminService;
import com.cc.base.BaseController;
import com.utils.json.JsonData;
import com.utils.json.JsonObject;
import com.utils.json.JsonSuccess;
@Controller
@RequestMapping("admin")
public class AdminController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(AdminController.class);
@Autowired
private AdminService adminService;
@RequestMapping(value = "/query", method = RequestMethod.GET)
@ResponseBody
public JsonObject query() throws Exception {
return new JsonData(this.adminService.query());
}
/**
* 新增管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public JsonObject add(@Validated Admin admin) throws Exception {
admin.setRegisterTime(new Date());
this.adminService.add(admin);
return new JsonData(admin);
}
/**
* 编辑管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
public JsonObject edit(@Validated Admin admin) throws Exception {
admin.setRegisterTime(new Date());
this.adminService.edit(admin);
return new JsonData(admin);
}
/**
* 编辑管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public JsonObject delete(@RequestParam(value = "id") Long id) throws Exception {
Admin admin = this.adminService.getById(id);
if(admin == null){
throw new Exception("管理员信息有误,请重试");
}else if(admin.getRole().equals(AdminRole.superAdmin.toString())){
throw new Exception("超级管理员不可删除");
}
this.adminService.delete(id);
return new JsonSuccess();
}
}
| UTF-8 | Java | 2,462 | java | AdminController.java | Java | [] | null | [] | package com.cc.admin.controller;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cc.admin.dto.Admin;
import com.cc.admin.enums.AdminRole;
import com.cc.admin.service.AdminService;
import com.cc.base.BaseController;
import com.utils.json.JsonData;
import com.utils.json.JsonObject;
import com.utils.json.JsonSuccess;
@Controller
@RequestMapping("admin")
public class AdminController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(AdminController.class);
@Autowired
private AdminService adminService;
@RequestMapping(value = "/query", method = RequestMethod.GET)
@ResponseBody
public JsonObject query() throws Exception {
return new JsonData(this.adminService.query());
}
/**
* 新增管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public JsonObject add(@Validated Admin admin) throws Exception {
admin.setRegisterTime(new Date());
this.adminService.add(admin);
return new JsonData(admin);
}
/**
* 编辑管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/edit", method = RequestMethod.POST)
@ResponseBody
public JsonObject edit(@Validated Admin admin) throws Exception {
admin.setRegisterTime(new Date());
this.adminService.edit(admin);
return new JsonData(admin);
}
/**
* 编辑管理员
* @return
* @throws Exception
*/
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public JsonObject delete(@RequestParam(value = "id") Long id) throws Exception {
Admin admin = this.adminService.getById(id);
if(admin == null){
throw new Exception("管理员信息有误,请重试");
}else if(admin.getRole().equals(AdminRole.superAdmin.toString())){
throw new Exception("超级管理员不可删除");
}
this.adminService.delete(id);
return new JsonSuccess();
}
}
| 2,462 | 0.726589 | 0.725753 | 84 | 26.333334 | 22.98205 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.321429 | false | false | 13 |
453bd749159284b429b120def2bab805a3bb792a | 20,650,202,793,345 | 0668eb233a516d1d8d07038f3b4b6293c7a31a4f | /src/com/example/android/login/XMLHandler.java | 50bb356e57ecf5db89d88b31f07ec1b271a3bbdd | [] | no_license | csl/EManagement | https://github.com/csl/EManagement | 1c14bf02638dd686be975f3433d6efb174cc3a2e | 4e2a3b413c5f3d72342515f317322de97b884c28 | refs/heads/master | 2016-08-04T22:22:59.286000 | 2011-08-08T08:46:14 | 2011-08-08T08:46:14 | 2,169,368 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.login;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLHandler extends DefaultHandler
{
private boolean h_id = false;
private boolean h_name = false;
private boolean address = false;
private boolean photo_name = false;
private boolean h_phone1 = false;
private boolean h_fax1 = false;
private XMLDataSet myParsedExampleDataSet = new XMLDataSet();
public XMLDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new XMLDataSet();
}
@Override
public void endDocument() throws SAXException {
// Nothing to do
}
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("RECORD")) {
if (localName.equals("H_ID")) {
//this.myParsedExampleDataSet.setId(11);
this.h_id = true;
}else if (localName.toUpperCase().equals("H_NAME")) {
this.h_name = true;
}else if (localName.toUpperCase().equals("ADDRESS")) {
this.address = true;
}else if (localName.toUpperCase().equals("PHOTO_NAME")) {
this.photo_name = true;
}else if (localName.toUpperCase().equals("H_PHONE1")) {
this.h_phone1 = true;
}else if (localName.toUpperCase().equals("H_FAX1")) {
this.h_fax1 = true;
}
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("H_ID")) {
this.h_id = false;
}else if (localName.toUpperCase().equals("H_NAME")) {
this.h_name = false;
}else if (localName.toUpperCase().equals("ADDRESS")) {
this.address = false;
}else if (localName.toUpperCase().equals("PHOTO_NAME")) {
this.photo_name = false;
}else if (localName.toUpperCase().equals("H_PHONE1")) {
this.h_phone1 = false;
}else if (localName.toUpperCase().equals("H_FAX1")) {
this.h_fax1 = false;
}
}
@Override
public void characters(char ch[], int start, int length) {
if(this.h_id){
myParsedExampleDataSet.setId(Integer.parseInt(new String(ch,start,length)));
}
if(this.h_name){
myParsedExampleDataSet.setName(new String(ch,start,length));
}
if(this.address){
myParsedExampleDataSet.setAddress( new String(ch,start,length));
}
if(this.photo_name){
myParsedExampleDataSet.setPhoto_name( new String(ch,start,length));
}
if(this.h_phone1){
myParsedExampleDataSet.setH_phone1( new String(ch,start,length));
}
if(this.h_fax1){
myParsedExampleDataSet.setH_fax1( new String(ch,start,length));
}
}
}
| UTF-8 | Java | 3,108 | java | XMLHandler.java | Java | [] | null | [] | package com.example.android.login;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLHandler extends DefaultHandler
{
private boolean h_id = false;
private boolean h_name = false;
private boolean address = false;
private boolean photo_name = false;
private boolean h_phone1 = false;
private boolean h_fax1 = false;
private XMLDataSet myParsedExampleDataSet = new XMLDataSet();
public XMLDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new XMLDataSet();
}
@Override
public void endDocument() throws SAXException {
// Nothing to do
}
@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("RECORD")) {
if (localName.equals("H_ID")) {
//this.myParsedExampleDataSet.setId(11);
this.h_id = true;
}else if (localName.toUpperCase().equals("H_NAME")) {
this.h_name = true;
}else if (localName.toUpperCase().equals("ADDRESS")) {
this.address = true;
}else if (localName.toUpperCase().equals("PHOTO_NAME")) {
this.photo_name = true;
}else if (localName.toUpperCase().equals("H_PHONE1")) {
this.h_phone1 = true;
}else if (localName.toUpperCase().equals("H_FAX1")) {
this.h_fax1 = true;
}
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("H_ID")) {
this.h_id = false;
}else if (localName.toUpperCase().equals("H_NAME")) {
this.h_name = false;
}else if (localName.toUpperCase().equals("ADDRESS")) {
this.address = false;
}else if (localName.toUpperCase().equals("PHOTO_NAME")) {
this.photo_name = false;
}else if (localName.toUpperCase().equals("H_PHONE1")) {
this.h_phone1 = false;
}else if (localName.toUpperCase().equals("H_FAX1")) {
this.h_fax1 = false;
}
}
@Override
public void characters(char ch[], int start, int length) {
if(this.h_id){
myParsedExampleDataSet.setId(Integer.parseInt(new String(ch,start,length)));
}
if(this.h_name){
myParsedExampleDataSet.setName(new String(ch,start,length));
}
if(this.address){
myParsedExampleDataSet.setAddress( new String(ch,start,length));
}
if(this.photo_name){
myParsedExampleDataSet.setPhoto_name( new String(ch,start,length));
}
if(this.h_phone1){
myParsedExampleDataSet.setH_phone1( new String(ch,start,length));
}
if(this.h_fax1){
myParsedExampleDataSet.setH_fax1( new String(ch,start,length));
}
}
}
| 3,108 | 0.600386 | 0.595238 | 100 | 29.08 | 24.206478 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.51 | false | false | 13 |
c2dc10b5199c610b770cd84c97d57e90fa522c40 | 29,326,036,700,573 | e1fe0d8ff42720168221911fbee5dc4afbb1e23f | /src/gui/RacerLabel.java | d629bd619dc79970a0b93fd2f8aad7d486bcbfac | [] | no_license | orco6/Ski-Game | https://github.com/orco6/Ski-Game | 87ef183a903ccc4cec1293110464862678f8da0f | 87096ec396c09f0c35595dde2944b2ca66c4a851 | refs/heads/main | 2023-05-03T08:06:21.118000 | 2021-05-18T14:39:26 | 2021-05-18T14:39:26 | 368,564,303 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gui;
import java.util.Observable;
import java.util.Observer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import game.entities.sportsman.WinterSportsman;
public class RacerLabel extends JLabel implements Observer{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* ctor of RacerLabel
* @param imageIcon
*/
public RacerLabel(ImageIcon imageIcon) {
super(imageIcon);
}
/**
* func that each competitor update the loaction of the label
*/
@Override
public void update(Observable o, Object arg) {
WinterSportsman racer=(WinterSportsman)o;
this.setLocation((int)(racer.getLocation().getX()),(int)(racer.getLocation().getY()));
}
}
| UTF-8 | Java | 704 | java | RacerLabel.java | Java | [] | null | [] | package gui;
import java.util.Observable;
import java.util.Observer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import game.entities.sportsman.WinterSportsman;
public class RacerLabel extends JLabel implements Observer{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* ctor of RacerLabel
* @param imageIcon
*/
public RacerLabel(ImageIcon imageIcon) {
super(imageIcon);
}
/**
* func that each competitor update the loaction of the label
*/
@Override
public void update(Observable o, Object arg) {
WinterSportsman racer=(WinterSportsman)o;
this.setLocation((int)(racer.getLocation().getX()),(int)(racer.getLocation().getY()));
}
}
| 704 | 0.71733 | 0.715909 | 36 | 18.555555 | 22.234163 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.138889 | false | false | 13 |
9153f7c59458a2808dad432b504c833be2611405 | 23,622,320,135,095 | 08432b9774506993a0ff10525b05ef93538427dd | /govtPermit/src/main/java/org/govtPermit/controller/RequestResponse.java | cce17949f4282724936107aaa1518073cffae276 | [] | no_license | bonthavamsee/SolarVillagePOC | https://github.com/bonthavamsee/SolarVillagePOC | 6f4e3073e8616a0b7611961d2bc781d1d8e47731 | 3828bf9dd45450091a4309866d037a80955fd03c | refs/heads/master | 2020-04-15T06:32:20.866000 | 2019-01-09T22:38:02 | 2019-01-09T22:38:02 | 164,464,300 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.govtPermit.controller;
import org.hibernate.Session;
import org.domainModel.govtPermit.*;
import org.domainModel.controller.*;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/solarDB")
public class RequestResponse {
private static final String SUCCESS_STATUS = "success";
private static final String ERROR_STATUS = "error";
private static final int CODE_SUCCESS = 100;
private static final int CODE_FAILURE = 102;
//Raise Electrical Request
@RequestMapping(value = "/raiseElectricalRequest", method = RequestMethod.POST)
public BaseResponse raiseElectrialReq(@RequestBody ElectricalPermit request) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
sessionObj.save(request);
System.out.println("RECORD SAVED TO DB SUCCESSFULLY");
sessionObj.getTransaction().commit();
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Electrical Permit Request Received Successfully");
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Request Unsuccessful..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
HibernateController.close();
return response;
}
//Raise Structural Request
@RequestMapping(value = "/raiseStructuralRequest", method = RequestMethod.POST)
public BaseResponse raiseStructuralReq(@RequestBody StructuralPermit request) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
sessionObj.save(request);
System.out.println("RECORD SAVED TO DB SUCCESSFULLY");
sessionObj.getTransaction().commit();
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Structural Permit Request Received Successfully");
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Request Unsuccessful..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
//Get Electrical Request Status
@RequestMapping(value = "/getElectricalReqStatus", method = RequestMethod.GET)
public ElectricalPermit getElectricalReq(@RequestParam(value = "id")String Id) {
Session sessionObj=null;
ElectricalPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
ep = (ElectricalPermit) sessionObj.get(ElectricalPermit.class, Id);
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return ep;
}
//Get Structural Request Status
@RequestMapping(value = "/getStructuralReqStatus", method = RequestMethod.GET)
public StructuralPermit getStructuralReq(@RequestParam(value = "id")String Id) {
Session sessionObj=null;
StructuralPermit sp=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sp = (StructuralPermit) sessionObj.get(StructuralPermit.class, Id);
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return sp;
}
//Rescind Electrical Request
@RequestMapping(value = "/rescindElectricalRequest", method = RequestMethod.GET)
public BaseResponse rescindElectrialReq(@RequestParam(value = "id") String Id) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
ElectricalPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
ep=(ElectricalPermit)sessionObj.load(ElectricalPermit.class, Id);
if(ep!=null)
{
sessionObj.delete(ep);
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Electrical Permit Request Rescinded Successfully");
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Request ID Not Found..");
}
sessionObj.getTransaction().commit();
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Rescinded Unsuccessfully..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
//Rescind Structural Request
@RequestMapping(value = "/rescindStructuralRequest", method = RequestMethod.GET)
public BaseResponse rescindStructuralReq(@RequestParam(value = "id") String Id) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
StructuralPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
ep=(StructuralPermit)sessionObj.load(StructuralPermit.class, Id);
if(ep!=null)
{
sessionObj.delete(ep);
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Structural Permit Request Rescinded Successfully");
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Request ID Not Found..");
}
sessionObj.getTransaction().commit();
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Rescinded Unsuccessfully..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
}
| UTF-8 | Java | 8,496 | java | RequestResponse.java | Java | [] | null | [] | package org.govtPermit.controller;
import org.hibernate.Session;
import org.domainModel.govtPermit.*;
import org.domainModel.controller.*;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/solarDB")
public class RequestResponse {
private static final String SUCCESS_STATUS = "success";
private static final String ERROR_STATUS = "error";
private static final int CODE_SUCCESS = 100;
private static final int CODE_FAILURE = 102;
//Raise Electrical Request
@RequestMapping(value = "/raiseElectricalRequest", method = RequestMethod.POST)
public BaseResponse raiseElectrialReq(@RequestBody ElectricalPermit request) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
sessionObj.save(request);
System.out.println("RECORD SAVED TO DB SUCCESSFULLY");
sessionObj.getTransaction().commit();
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Electrical Permit Request Received Successfully");
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Request Unsuccessful..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
HibernateController.close();
return response;
}
//Raise Structural Request
@RequestMapping(value = "/raiseStructuralRequest", method = RequestMethod.POST)
public BaseResponse raiseStructuralReq(@RequestBody StructuralPermit request) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
sessionObj.save(request);
System.out.println("RECORD SAVED TO DB SUCCESSFULLY");
sessionObj.getTransaction().commit();
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Structural Permit Request Received Successfully");
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Request Unsuccessful..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
//Get Electrical Request Status
@RequestMapping(value = "/getElectricalReqStatus", method = RequestMethod.GET)
public ElectricalPermit getElectricalReq(@RequestParam(value = "id")String Id) {
Session sessionObj=null;
ElectricalPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
ep = (ElectricalPermit) sessionObj.get(ElectricalPermit.class, Id);
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return ep;
}
//Get Structural Request Status
@RequestMapping(value = "/getStructuralReqStatus", method = RequestMethod.GET)
public StructuralPermit getStructuralReq(@RequestParam(value = "id")String Id) {
Session sessionObj=null;
StructuralPermit sp=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sp = (StructuralPermit) sessionObj.get(StructuralPermit.class, Id);
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return sp;
}
//Rescind Electrical Request
@RequestMapping(value = "/rescindElectricalRequest", method = RequestMethod.GET)
public BaseResponse rescindElectrialReq(@RequestParam(value = "id") String Id) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
ElectricalPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
ep=(ElectricalPermit)sessionObj.load(ElectricalPermit.class, Id);
if(ep!=null)
{
sessionObj.delete(ep);
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Electrical Permit Request Rescinded Successfully");
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Request ID Not Found..");
}
sessionObj.getTransaction().commit();
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Electrical Permit Rescinded Unsuccessfully..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
//Rescind Structural Request
@RequestMapping(value = "/rescindStructuralRequest", method = RequestMethod.GET)
public BaseResponse rescindStructuralReq(@RequestParam(value = "id") String Id) {
BaseResponse response = new BaseResponse();
Session sessionObj=null;
StructuralPermit ep=null;
try{
//sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj=HibernateController.buildSessionFactory().openSession();
sessionObj.beginTransaction();
ep=(StructuralPermit)sessionObj.load(StructuralPermit.class, Id);
if(ep!=null)
{
sessionObj.delete(ep);
response.setStatus(SUCCESS_STATUS);
response.setCode(CODE_SUCCESS);
response.setMessage("Structural Permit Request Rescinded Successfully");
}
else
{
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Request ID Not Found..");
}
sessionObj.getTransaction().commit();
}
catch(Exception e)
{
System.out.println("---------STACK TRACE START---------------");
e.printStackTrace();
System.out.println("---------STACK TRACE END---------------");
if(null!=sessionObj.getTransaction())
{
System.out.println("TRANSACTION ROLLED BACK");
sessionObj.getTransaction().rollback();
}
response.setStatus(ERROR_STATUS);
response.setCode(CODE_FAILURE);
response.setMessage("Structural Permit Rescinded Unsuccessfully..Please Try Later...");
}
finally{
if(sessionObj !=null)
sessionObj.close();
HibernateController.close();
}
return response;
}
}
| 8,496 | 0.684675 | 0.683969 | 254 | 32.448818 | 26.016109 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.795276 | false | false | 13 |
b7a98d064040be88cd9121a201efc04e7b8f0d60 | 29,867,202,624,705 | e2f83315c6d852dc42ecc0b4ece3737c6bfcf261 | /core/src/main/java/com/googlecode/pigwt/client/DefaultPlace.java | d1f395ae1991410f962d9d1ed7acb312c7cacdf5 | [] | no_license | chrisfjones/pigwt | https://github.com/chrisfjones/pigwt | 826a62dd4cdefed7731ccb72a8e023b4053a2c11 | 9ee39a2e8fca7d51f12a54ff56063b952253d629 | refs/heads/master | 2021-01-18T13:51:48.079000 | 2011-08-21T21:34:03 | 2011-08-21T21:34:03 | 2,870,742 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.googlecode.pigwt.client;
import com.google.gwt.place.shared.*;
import java.util.Map;
public class DefaultPlace extends PigwtPlace {
@Prefix("")
public static class Tokenizer implements PlaceTokenizer<DefaultPlace> {
@Override
public DefaultPlace getPlace(final String token) {
return new DefaultPlace(TokenizerUtil.parseParams(token));
}
@Override
public String getToken(final DefaultPlace place) {
return "";
}
}
public DefaultPlace(final Map<String, String> params) {
super(params);
}
@Override
public String getPrefix() {
return "";
}
}
| UTF-8 | Java | 678 | java | DefaultPlace.java | Java | [] | null | [] | package com.googlecode.pigwt.client;
import com.google.gwt.place.shared.*;
import java.util.Map;
public class DefaultPlace extends PigwtPlace {
@Prefix("")
public static class Tokenizer implements PlaceTokenizer<DefaultPlace> {
@Override
public DefaultPlace getPlace(final String token) {
return new DefaultPlace(TokenizerUtil.parseParams(token));
}
@Override
public String getToken(final DefaultPlace place) {
return "";
}
}
public DefaultPlace(final Map<String, String> params) {
super(params);
}
@Override
public String getPrefix() {
return "";
}
}
| 678 | 0.635693 | 0.635693 | 29 | 22.379311 | 22.663071 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.275862 | false | false | 13 |
b2dc1cb0705b0050e14e730f06873d6d8fc7341f | 17,136,919,580,549 | b023ffaf6c6a0f652a4c798c1193687925d34edf | /app/src/main/java/com/infitronics/www/School_Parent/ui/Notice_Fragment.java | a90fd7a27ce7796366b4d46b42f1832447090343 | [] | no_license | runaliA/School_Parent | https://github.com/runaliA/School_Parent | 30376b153c89d38ab5bc253acf3766f15ecf3584 | 52a286c4ca167c795e00b5618c32adffbb0787dd | refs/heads/master | 2021-06-23T03:41:50.395000 | 2017-09-01T11:52:57 | 2017-09-01T11:52:57 | 102,108,071 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.infitronics.www.School_Parent.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.gson.reflect.TypeToken;
import com.infitronics.www.School_Parent.R;
import com.infitronics.www.School_Parent.adapter.Notice_Adapter;
import com.infitronics.www.School_Parent.api.ApiClient;
import com.infitronics.www.School_Parent.api.ApiInterface;
import com.infitronics.www.School_Parent.models.Get_Notice;
import com.infitronics.www.School_Parent.utils.DialogUtils;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
/**
* Created by Shashank on 29-01-2017.
*/
public class Notice_Fragment extends Fragment {
View myview;
private Notice_Adapter mAdapter;
private List<Get_Notice.Data> data;
public RecyclerView mRecyclerView;
public ProgressDialog mProgressDialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
myview = inflater.inflate(R.layout.fragment_notice, container, false);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mRecyclerView = (RecyclerView) myview.findViewById(R.id.recycler_notice);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
// mRecyclerView.setAdapter(mAdapter);
boolean flaginternet = false;
ConnectivityManager connectivity = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
flaginternet = true;
break;
}
}
if (flaginternet) {
ApiInterface apiservice = ApiClient.getClient().create(ApiInterface.class);
Call<Get_Notice> call = apiservice.getNotice();
mProgressDialog = DialogUtils.showProgressDialog(getActivity(), "Loading Data...");
call.enqueue(new Callback<Get_Notice>() {
@Override
public void onResponse(Call<Get_Notice> call, Response<Get_Notice> response) {
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
if (response.isSuccessful()) {
data = response.body().getData();
for (int i = 0; i < data.size(); i++) {
Log.e("Notice Data ", data.get(i).toString());
}
mAdapter = new Notice_Adapter(data, R.layout.list_item_notice, getActivity());
mRecyclerView.setAdapter(mAdapter);
} else {
Log.d(TAG, "random error: ");
}
}
@Override
public void onFailure(Call<Get_Notice> call, Throwable t) {
Log.e(TAG, t.toString());
mProgressDialog.dismiss();
Toast.makeText(getActivity(), "Unable to fetch Response ", Toast.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(getActivity(), "Plz check Internet Connectivity", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),Login.class);
getActivity().finish();
}
return myview;
}
}
| UTF-8 | Java | 4,204 | java | Notice_Fragment.java | Java | [
{
"context": "roid.content.ContentValues.TAG;\n\n/**\n * Created by Shashank on 29-01-2017.\n */\n\npublic class Notice_Fragment ",
"end": 1141,
"score": 0.9982002377510071,
"start": 1133,
"tag": "NAME",
"value": "Shashank"
}
] | null | [] | package com.infitronics.www.School_Parent.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.gson.reflect.TypeToken;
import com.infitronics.www.School_Parent.R;
import com.infitronics.www.School_Parent.adapter.Notice_Adapter;
import com.infitronics.www.School_Parent.api.ApiClient;
import com.infitronics.www.School_Parent.api.ApiInterface;
import com.infitronics.www.School_Parent.models.Get_Notice;
import com.infitronics.www.School_Parent.utils.DialogUtils;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.ContentValues.TAG;
/**
* Created by Shashank on 29-01-2017.
*/
public class Notice_Fragment extends Fragment {
View myview;
private Notice_Adapter mAdapter;
private List<Get_Notice.Data> data;
public RecyclerView mRecyclerView;
public ProgressDialog mProgressDialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
myview = inflater.inflate(R.layout.fragment_notice, container, false);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mRecyclerView = (RecyclerView) myview.findViewById(R.id.recycler_notice);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
// mRecyclerView.setAdapter(mAdapter);
boolean flaginternet = false;
ConnectivityManager connectivity = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
flaginternet = true;
break;
}
}
if (flaginternet) {
ApiInterface apiservice = ApiClient.getClient().create(ApiInterface.class);
Call<Get_Notice> call = apiservice.getNotice();
mProgressDialog = DialogUtils.showProgressDialog(getActivity(), "Loading Data...");
call.enqueue(new Callback<Get_Notice>() {
@Override
public void onResponse(Call<Get_Notice> call, Response<Get_Notice> response) {
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
if (response.isSuccessful()) {
data = response.body().getData();
for (int i = 0; i < data.size(); i++) {
Log.e("Notice Data ", data.get(i).toString());
}
mAdapter = new Notice_Adapter(data, R.layout.list_item_notice, getActivity());
mRecyclerView.setAdapter(mAdapter);
} else {
Log.d(TAG, "random error: ");
}
}
@Override
public void onFailure(Call<Get_Notice> call, Throwable t) {
Log.e(TAG, t.toString());
mProgressDialog.dismiss();
Toast.makeText(getActivity(), "Unable to fetch Response ", Toast.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(getActivity(), "Plz check Internet Connectivity", Toast.LENGTH_SHORT).show();
Intent i=new Intent(getActivity(),Login.class);
getActivity().finish();
}
return myview;
}
}
| 4,204 | 0.633444 | 0.629638 | 111 | 36.873875 | 30.212198 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.747748 | false | false | 13 |
fb2b6953e9dd8a122910d605a877e49962b8130d | 3,573,412,841,457 | 2ac11e0515b8c46b9c9ce022332c1d4b6e5f7736 | /src/main/java/org/youtube/youtube/YouTubeException.java | b4ca889eb34e58f12dc4f3f2b16d356676f44f7a | [] | no_license | Code4Pizza/youtube-auto | https://github.com/Code4Pizza/youtube-auto | a00aa2ded10279a48c6db5fc372662b0c59f2da3 | ca563702d3e3d1bb0b352427389eba2d8fcf84f1 | refs/heads/master | 2023-07-12T05:32:57.408000 | 2020-08-06T10:41:06 | 2020-08-06T10:41:06 | 394,962,065 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.youtube.youtube;
public class YouTubeException extends Exception {
public YouTubeException(String message) {
super(message);
}
public static class YouTubeFailedToPlayException extends YouTubeException {
public YouTubeFailedToPlayException() {
super("Failed to play video");
}
}
}
| UTF-8 | Java | 308 | java | YouTubeException.java | Java | [] | null | [] | package org.youtube.youtube;
public class YouTubeException extends Exception {
public YouTubeException(String message) {
super(message);
}
public static class YouTubeFailedToPlayException extends YouTubeException {
public YouTubeFailedToPlayException() {
super("Failed to play video");
}
}
}
| 308 | 0.772727 | 0.772727 | 14 | 21 | 23.342175 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142857 | false | false | 13 |
c16e6d4f918ddbec9375118b2315dda0a58bb332 | 21,354,577,465,180 | fd9946d4f69176e0cd9dc3fb5c222b4a302cd3a2 | /src/Product.java | d1f1cb43b8da5f9ce42221bd61427103c0195ff2 | [] | no_license | Natt913/JPProject | https://github.com/Natt913/JPProject | 04cbc22a662920991b1bebe1032dcee179471ba1 | f596995196b50f3151f58dcb371672482be36ddf | refs/heads/master | 2020-03-30T04:45:37.779000 | 2018-12-09T21:56:57 | 2018-12-09T21:56:57 | 150,760,546 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author Nathalie Crespo
* Many of the notes were used from the JP Project file.
* This file is an abstract class made to be subclassed by other classes.
*/
//Required in order to use Date class
import java.util.Date;
public abstract class Product implements Item, Comparable<Product> {
//Instance variables
private int serialNumber;
private String manufacturer = Item.manufacturer;
private Date manufacturedOn;
private String name;
//Specified to be a class variable, therefore it will only be used in this class.
//Given error for misuse of static fields though
private static int currentProductionNumber = 1;
/**
* Default constructor for the Product class.
*/
public Product() {
name = "Generic";
//More or less specified to do this but gives error for misuse of static fields.
serialNumber = currentProductionNumber++;
manufacturedOn = new Date();
}
/**
* A constructor that will take in the name of the product.
* And set this to the field variable name.
* Will also assign a serial number from the currentProductionNumber.
* More or less specified to do this.
* The currentProductionNumber is incremented in readiness for the next instance.
* Set manufacturedOn as the current date and time.
* @param n It takes a String as the name for the product.
*/
public Product(String n) {
name = n;
serialNumber = currentProductionNumber++;
manufacturedOn = new Date();
}
//Completing all the methods from the Item interface
/**
* Set function to set the serial number equal to the production number.
* More or less specified to set currentProductionNumber equal to production number.
* @param productionNumber It takes an integer to set as the production number.
*/
public void setProductionNumber(int productionNumber) {
currentProductionNumber = productionNumber;
//serialNumber = productionNumber
}
/**
* Set function to set the name of the product.
* @param name A string parameter to take the name of the product.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get function to return the name of the product.
* @return Returns the set name of the product.
*/
public String getName() {
return name;
}
/**
*Get function to return the date the product was manufactured.
* There is a bug for this but this is what is required.
* @return Returns the date the product was manufactured on
*/
public Date getManufacturerDate() {
return manufacturedOn;
}
/**
* Get function to return the serial number.
* @return Returns the serial number.
*/
public int getSerialNumber() {
return serialNumber;
}
/**
* Method to return a template provided by Oracle.
* Adds non-sample data.
* @return The template that is required to use.
*/
public String toString() {
return "\n" + "Manufacturer : " + manufacturer + "\n"
+ "Serial Number : " + serialNumber + "\n"
+ "Date : " + manufacturedOn + "\n"
+ "Name : " + name;
}
/**
* Method to compare name of the Product objects.
* @param obj The object to compare.
* @return returns an int to signify how it compared.
*/
public int compareTo(Product obj) {
return name.compareTo(obj.getName());
}
} | UTF-8 | Java | 3,367 | java | Product.java | Java | [
{
"context": "/**\n * @author Nathalie Crespo\n * Many of the notes were used from the JP Projec",
"end": 30,
"score": 0.9998763203620911,
"start": 15,
"tag": "NAME",
"value": "Nathalie Crespo"
}
] | null | [] | /**
* @author <NAME>
* Many of the notes were used from the JP Project file.
* This file is an abstract class made to be subclassed by other classes.
*/
//Required in order to use Date class
import java.util.Date;
public abstract class Product implements Item, Comparable<Product> {
//Instance variables
private int serialNumber;
private String manufacturer = Item.manufacturer;
private Date manufacturedOn;
private String name;
//Specified to be a class variable, therefore it will only be used in this class.
//Given error for misuse of static fields though
private static int currentProductionNumber = 1;
/**
* Default constructor for the Product class.
*/
public Product() {
name = "Generic";
//More or less specified to do this but gives error for misuse of static fields.
serialNumber = currentProductionNumber++;
manufacturedOn = new Date();
}
/**
* A constructor that will take in the name of the product.
* And set this to the field variable name.
* Will also assign a serial number from the currentProductionNumber.
* More or less specified to do this.
* The currentProductionNumber is incremented in readiness for the next instance.
* Set manufacturedOn as the current date and time.
* @param n It takes a String as the name for the product.
*/
public Product(String n) {
name = n;
serialNumber = currentProductionNumber++;
manufacturedOn = new Date();
}
//Completing all the methods from the Item interface
/**
* Set function to set the serial number equal to the production number.
* More or less specified to set currentProductionNumber equal to production number.
* @param productionNumber It takes an integer to set as the production number.
*/
public void setProductionNumber(int productionNumber) {
currentProductionNumber = productionNumber;
//serialNumber = productionNumber
}
/**
* Set function to set the name of the product.
* @param name A string parameter to take the name of the product.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get function to return the name of the product.
* @return Returns the set name of the product.
*/
public String getName() {
return name;
}
/**
*Get function to return the date the product was manufactured.
* There is a bug for this but this is what is required.
* @return Returns the date the product was manufactured on
*/
public Date getManufacturerDate() {
return manufacturedOn;
}
/**
* Get function to return the serial number.
* @return Returns the serial number.
*/
public int getSerialNumber() {
return serialNumber;
}
/**
* Method to return a template provided by Oracle.
* Adds non-sample data.
* @return The template that is required to use.
*/
public String toString() {
return "\n" + "Manufacturer : " + manufacturer + "\n"
+ "Serial Number : " + serialNumber + "\n"
+ "Date : " + manufacturedOn + "\n"
+ "Name : " + name;
}
/**
* Method to compare name of the Product objects.
* @param obj The object to compare.
* @return returns an int to signify how it compared.
*/
public int compareTo(Product obj) {
return name.compareTo(obj.getName());
}
} | 3,358 | 0.677458 | 0.677161 | 115 | 28.286957 | 25.538298 | 86 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.182609 | false | false | 13 |
976a55904be5f260e94dfb4983de0c641b43f57c | 14,396,730,443,693 | a4f0aad03fdae664dc8e624233bf30a87adb464a | /src/main/java/com/wordpress/carledwinti/newcarshop/batchapi/utils/CarroUtils.java | e7be5da0c230977df9f3c7b85d251c9ff48650a2 | [] | no_license | cyborgmg/spring-batch | https://github.com/cyborgmg/spring-batch | 09b6a62ff5b63990bf6d5d6104340d8fbb2950c6 | 4fa5e20db941442069d9ff86c3dad62191583c85 | refs/heads/main | 2023-03-12T05:42:25.309000 | 2021-03-05T16:23:12 | 2021-03-05T16:23:12 | 344,867,264 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wordpress.carledwinti.newcarshop.batchapi.utils;
import com.wordpress.carledwinti.newcarshop.batchapi.enums.LojaEnum;
import com.wordpress.carledwinti.newcarshop.batchapi.enums.PercentEnum;
import java.math.BigDecimal;
public class CarroUtils {
private static final BigDecimal _99_H = new BigDecimal("99999.99");
private static final BigDecimal _149_H = new BigDecimal("149999.99");
public static LojaEnum chooseStore(String price) {
BigDecimal valor = convertToBigDecimal(price);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return LojaEnum.LOJA_AV_PAULISTA;
}
if(isLojaIbirapuera(valor)){
return LojaEnum.LOJA_IBIRAPUERA;
}
if(isLojaJardins(valor)){
return LojaEnum.LOJA_JARDINS;
}
return null;
}
public static BigDecimal calculateDiscount(String valorVenda) {
BigDecimal valor = convertToBigDecimal(valorVenda);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return new BigDecimal(PercentEnum.P_10.getPercent());
}
if(isLojaIbirapuera(valor)){
return new BigDecimal(PercentEnum.P_05.getPercent());
}
if(isLojaJardins(valor)){
return new BigDecimal(PercentEnum.P_02.getPercent());
}
return null;
}
public static BigDecimal calculatePrice(String valorCompra) {
BigDecimal valor = convertToBigDecimal(valorCompra);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_25.getPercent())));
}
if(isLojaIbirapuera(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_15.getPercent())));
}
if(isLojaJardins(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_05.getPercent())));
}
return null;
}
private static BigDecimal calculateAddPercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.add(calculatePercent(valorOriginal, percentEnum));
}
private static BigDecimal calculateSubtractPercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.subtract(calculatePercent(valorOriginal, percentEnum));
}
private static BigDecimal calculatePercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.multiply(new BigDecimal(percentEnum.getPercent()));
}
private static boolean isLojaJardins(BigDecimal valor) {
return valor.compareTo(_149_H) == 1;
}
private static boolean isLojaIbirapuera(BigDecimal valor) {
return ((valor.compareTo(_149_H) == 0) || (valor.compareTo(_99_H) == 1) && (valor.compareTo(_149_H) == -1));
}
private static boolean isLojaPaulista(BigDecimal valor) {
return (valor.compareTo(_99_H) <= 0) && (valor.compareTo(_99_H) <= 0);
}
public static BigDecimal convertToBigDecimal(String valor) {
try {
return new BigDecimal(valor);
}catch(Exception e){
return null;
}
}
public static Integer convertToInteger(String ano) {
try {
return Integer.parseInt(ano);
}catch(Exception e){
return null;
}
}
// public static void main(String[] args) {
//
// System.out.println("ano: " + convertToInteger("2017"));
//
// System.out.println("40: " + chooseStore("40000.00"));
// System.out.println("98: " + chooseStore("98000.00"));
// System.out.println("99: " + chooseStore("99999.99"));
// System.out.println("100: " + chooseStore("100000.00"));
// System.out.println("148: " + chooseStore("148000.00"));
// System.out.println("149: " + chooseStore("149999.99"));
// System.out.println("150: " + chooseStore("150000.00"));
// System.out.println("299: " + chooseStore("299000.00"));
// }
} | UTF-8 | Java | 4,133 | java | CarroUtils.java | Java | [] | null | [] | package com.wordpress.carledwinti.newcarshop.batchapi.utils;
import com.wordpress.carledwinti.newcarshop.batchapi.enums.LojaEnum;
import com.wordpress.carledwinti.newcarshop.batchapi.enums.PercentEnum;
import java.math.BigDecimal;
public class CarroUtils {
private static final BigDecimal _99_H = new BigDecimal("99999.99");
private static final BigDecimal _149_H = new BigDecimal("149999.99");
public static LojaEnum chooseStore(String price) {
BigDecimal valor = convertToBigDecimal(price);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return LojaEnum.LOJA_AV_PAULISTA;
}
if(isLojaIbirapuera(valor)){
return LojaEnum.LOJA_IBIRAPUERA;
}
if(isLojaJardins(valor)){
return LojaEnum.LOJA_JARDINS;
}
return null;
}
public static BigDecimal calculateDiscount(String valorVenda) {
BigDecimal valor = convertToBigDecimal(valorVenda);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return new BigDecimal(PercentEnum.P_10.getPercent());
}
if(isLojaIbirapuera(valor)){
return new BigDecimal(PercentEnum.P_05.getPercent());
}
if(isLojaJardins(valor)){
return new BigDecimal(PercentEnum.P_02.getPercent());
}
return null;
}
public static BigDecimal calculatePrice(String valorCompra) {
BigDecimal valor = convertToBigDecimal(valorCompra);
if(valor == null){
return null;
}
if(isLojaPaulista(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_25.getPercent())));
}
if(isLojaIbirapuera(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_15.getPercent())));
}
if(isLojaJardins(valor)){
return valor.add(valor.multiply(new BigDecimal(PercentEnum.P_05.getPercent())));
}
return null;
}
private static BigDecimal calculateAddPercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.add(calculatePercent(valorOriginal, percentEnum));
}
private static BigDecimal calculateSubtractPercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.subtract(calculatePercent(valorOriginal, percentEnum));
}
private static BigDecimal calculatePercent(BigDecimal valorOriginal, PercentEnum percentEnum) {
return valorOriginal.multiply(new BigDecimal(percentEnum.getPercent()));
}
private static boolean isLojaJardins(BigDecimal valor) {
return valor.compareTo(_149_H) == 1;
}
private static boolean isLojaIbirapuera(BigDecimal valor) {
return ((valor.compareTo(_149_H) == 0) || (valor.compareTo(_99_H) == 1) && (valor.compareTo(_149_H) == -1));
}
private static boolean isLojaPaulista(BigDecimal valor) {
return (valor.compareTo(_99_H) <= 0) && (valor.compareTo(_99_H) <= 0);
}
public static BigDecimal convertToBigDecimal(String valor) {
try {
return new BigDecimal(valor);
}catch(Exception e){
return null;
}
}
public static Integer convertToInteger(String ano) {
try {
return Integer.parseInt(ano);
}catch(Exception e){
return null;
}
}
// public static void main(String[] args) {
//
// System.out.println("ano: " + convertToInteger("2017"));
//
// System.out.println("40: " + chooseStore("40000.00"));
// System.out.println("98: " + chooseStore("98000.00"));
// System.out.println("99: " + chooseStore("99999.99"));
// System.out.println("100: " + chooseStore("100000.00"));
// System.out.println("148: " + chooseStore("148000.00"));
// System.out.println("149: " + chooseStore("149999.99"));
// System.out.println("150: " + chooseStore("150000.00"));
// System.out.println("299: " + chooseStore("299000.00"));
// }
} | 4,133 | 0.625938 | 0.592306 | 136 | 29.397058 | 30.563166 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.367647 | false | false | 13 |
eb5812821bb12046f279af06cd507a64fae261bb | 34,170,759,817,447 | d0eed6d531a2b1f0de919efbb45548d71494f1fb | /src/main/java/ua/kharkiv/gvg/service/ExtractTextFromDoc.java | 73d080f585797044c703d741fa33abbbd8fda781 | [] | no_license | GVGUAD/knowledgetester | https://github.com/GVGUAD/knowledgetester | bad81e3675a55173ca79eb77a34cb52f68865007 | bb640b0edefe3df1efc603f868a71d2db2a85a94 | refs/heads/master | 2018-03-28T00:52:07.281000 | 2017-04-06T12:07:14 | 2017-04-06T12:07:14 | 87,424,744 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ua.kharkiv.gvg.service;
import org.apache.poi.hwpf.HWPFDocument;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;
import org.apache.poi.hwpf.extractor.WordExtractor;
import ua.kharkiv.gvg.model.Answer;
import ua.kharkiv.gvg.model.Question;
import ua.kharkiv.gvg.model.Test;
import javax.xml.transform.*;
import java.io.*;
/**
* Created by Vladimir on 21.03.2017.
*/
@Service
public class ExtractTextFromDoc implements ExtractText {
@Override
public Test extractText(String file, String title) throws IOException, SAXException, TransformerConfigurationException {
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream("D:\\apps\\apache-tomcat-8.5.9\\temp\\"+file));
// WordToHtmlUtils.loadDoc(new FileInputStream("D:\\apps\\apache-tomcat-8.5.9\\temp\\1.doc"));
WordExtractor w = new WordExtractor(wordDocument);
Question q = null;
Test test = new Test();
test.setTitle(title);
String s = w.getText();
String res[] = s.substring(23, s.length() - 11).split("\\r\\n");
//TODO replace for to while
for (int i = 0; i < res.length - 1; ) {
q = new Question();
if (res[i].matches("^\\d.*$")) {
q.setQuestion(res[i]);
i++;
}
if (res[i].equals("")) {
i++;
}
while (res[i].matches("^\\D\\.\\t.*$")) {
if (q.getAnswers().size() == 0) {
q.getAnswers().add(new Answer(res[i].substring(3), true, q));
} else {
q.getAnswers().add(new Answer(res[i].substring(3), false, q));
}
if (i < res.length-1) {
i++;
} else {
break;
}
}
test.getQuestions().add(q);
}
System.out.println("dddd");
return test;
// WordToHtmlConverter wordToHtmlConverter = null;
// try {
// wordToHtmlConverter = new WordToHtmlConverter(
// DocumentBuilderFactory.newInstance().newDocumentBuilder()
// .newDocument());
// } catch (ParserConfigurationException e) {
// e.printStackTrace();
// }
// wordToHtmlConverter.processDocument(wordDocument);
// Document htmlDocument = wordToHtmlConverter.getDocument();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// DOMSource domSource = new DOMSource(htmlDocument);
// StreamResult streamResult = new StreamResult(out);
//
// TransformerFactory tf = TransformerFactory.newInstance();
// Transformer serializer = tf.newTransformer();
// serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.INDENT, "yes");
// serializer.setOutputProperty(OutputKeys.METHOD, "text");
// try {
// serializer.transform(domSource, streamResult);
// } catch (TransformerException e) {
// e.printStackTrace();
// }
// out.close();
//
// String result = new String(out.toByteArray(), "UTF-8");
// System.out.println(result);
}
}
| UTF-8 | Java | 3,295 | java | ExtractTextFromDoc.java | Java | [
{
"context": ".transform.*;\nimport java.io.*;\n\n/**\n * Created by Vladimir on 21.03.2017.\n */\n@Service\npublic class ExtractT",
"end": 390,
"score": 0.9685989618301392,
"start": 382,
"tag": "NAME",
"value": "Vladimir"
}
] | null | [] | package ua.kharkiv.gvg.service;
import org.apache.poi.hwpf.HWPFDocument;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;
import org.apache.poi.hwpf.extractor.WordExtractor;
import ua.kharkiv.gvg.model.Answer;
import ua.kharkiv.gvg.model.Question;
import ua.kharkiv.gvg.model.Test;
import javax.xml.transform.*;
import java.io.*;
/**
* Created by Vladimir on 21.03.2017.
*/
@Service
public class ExtractTextFromDoc implements ExtractText {
@Override
public Test extractText(String file, String title) throws IOException, SAXException, TransformerConfigurationException {
HWPFDocument wordDocument = new HWPFDocument(new FileInputStream("D:\\apps\\apache-tomcat-8.5.9\\temp\\"+file));
// WordToHtmlUtils.loadDoc(new FileInputStream("D:\\apps\\apache-tomcat-8.5.9\\temp\\1.doc"));
WordExtractor w = new WordExtractor(wordDocument);
Question q = null;
Test test = new Test();
test.setTitle(title);
String s = w.getText();
String res[] = s.substring(23, s.length() - 11).split("\\r\\n");
//TODO replace for to while
for (int i = 0; i < res.length - 1; ) {
q = new Question();
if (res[i].matches("^\\d.*$")) {
q.setQuestion(res[i]);
i++;
}
if (res[i].equals("")) {
i++;
}
while (res[i].matches("^\\D\\.\\t.*$")) {
if (q.getAnswers().size() == 0) {
q.getAnswers().add(new Answer(res[i].substring(3), true, q));
} else {
q.getAnswers().add(new Answer(res[i].substring(3), false, q));
}
if (i < res.length-1) {
i++;
} else {
break;
}
}
test.getQuestions().add(q);
}
System.out.println("dddd");
return test;
// WordToHtmlConverter wordToHtmlConverter = null;
// try {
// wordToHtmlConverter = new WordToHtmlConverter(
// DocumentBuilderFactory.newInstance().newDocumentBuilder()
// .newDocument());
// } catch (ParserConfigurationException e) {
// e.printStackTrace();
// }
// wordToHtmlConverter.processDocument(wordDocument);
// Document htmlDocument = wordToHtmlConverter.getDocument();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// DOMSource domSource = new DOMSource(htmlDocument);
// StreamResult streamResult = new StreamResult(out);
//
// TransformerFactory tf = TransformerFactory.newInstance();
// Transformer serializer = tf.newTransformer();
// serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.INDENT, "yes");
// serializer.setOutputProperty(OutputKeys.METHOD, "text");
// try {
// serializer.transform(domSource, streamResult);
// } catch (TransformerException e) {
// e.printStackTrace();
// }
// out.close();
//
// String result = new String(out.toByteArray(), "UTF-8");
// System.out.println(result);
}
}
| 3,295 | 0.571775 | 0.563581 | 87 | 36.873562 | 26.915279 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.712644 | false | false | 13 |
a035cde6721a55b5a178ae450ec01a6d890e70a3 | 19,610,820,690,375 | 2a438ba0633c532038bfe7d83ff9e88ae7d7a9c1 | /spring-boot-starter-data-jpa-plus/src/test/java/org/springframework/boot/autoconfigure/flyway/XFlywayAutoConfigurationTests.java | b8a9c345bb121738527ea09bf14c7e66eb4d6e3b | [
"Apache-2.0"
] | permissive | spt-oss/spring-boot-plus_ | https://github.com/spt-oss/spring-boot-plus_ | 8a7f3876d47c5f7c36583191d73ce08dfdb37fb8 | 21cf882098eff320b6f4b042a9d6a96daf1ae8e4 | refs/heads/master | 2021-10-15T08:13:48.450000 | 2018-12-30T15:08:18 | 2018-12-30T15:08:18 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2017-2018 the original author or authors.
*
* 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.springframework.boot.autoconfigure.flyway;
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.flywaydb.core.XFlyway;
import org.flywaydb.core.internal.util.XMysqlToH2SqlReplacer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.flyway.XFlywayAutoConfigurationTests.XOptionalConfiguration;
import org.springframework.boot.autoconfigure.jdbc.XDataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Tests for {@link XFlywayAutoConfiguration}
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
/* @formatter:off */
XFlywayAutoConfiguration.class,
XDataSourceAutoConfiguration.class,
XOptionalConfiguration.class
/* @formatter:on */
})
@ActiveProfiles({ "test", "test-flyway-config" })
public class XFlywayAutoConfigurationTests {
/**
* Schema: foo
*/
private static final String SCHEMA_FOO = "foo";
/**
* Schema: bar
*/
private static final String SCHEMA_BAR = "bar";
/**
* {@link XFlyway}
*/
@Autowired
private XFlyway flyway;
/**
* {@link DataSource}
*/
@Autowired
private DataSource dataSource;
/**
* Annotation
*/
@Test
public void annotation() {
ConditionalOnProperty property = AnnotationUtils.findAnnotation(XFlywayAutoConfiguration.class,
ConditionalOnProperty.class);
assertThat(property.prefix()).isEqualTo(XFlywayProperties.PREFIX);
assertThat(property.name()).isEqualTo(new String[] { "enabled" });
assertThat(property.havingValue()).isEqualTo("true");
assertThat(property.matchIfMissing()).isEqualTo(false);
}
/**
* {@link org.springframework.boot.autoconfigure.flyway.XFlywayAutoConfiguration.XFlywayConfiguration#flyway()}
*/
@Test
public void flyway() {
assertThat(this.hasData(SCHEMA_FOO)).isEqualTo(false);
assertThat(this.hasData(SCHEMA_BAR)).isEqualTo(false);
this.flyway.migrate();
assertThat(this.hasData(SCHEMA_FOO)).isEqualTo(true);
assertThat(this.hasData(SCHEMA_BAR)).isEqualTo(true);
}
/**
* Has data?
*
* @param name name
* @return {@code true} if has data
*/
private boolean hasData(String name) {
try (Connection connection = this.dataSource.getConnection()) {
try (ResultSet result = connection.prepareCall("select * from " + name + "." + name).executeQuery()) {
if (!result.next()) {
return false;
}
return result.getString("code").equals(name);
}
}
catch (SQLException e) {
// No table
if (e.getMessage().contains("not found")) {
return false;
}
throw new IllegalStateException("Failed to execute SQL", e);
}
}
/**
* {@link Configuration} for optional
*/
@Configuration
protected static class XOptionalConfiguration {
/**
* {@link XFlywayMigrationStrategy}
*
* @return {@link XFlywayMigrationStrategy}
*/
@Bean
public XFlywayMigrationStrategy migrationStrategy() {
return flyway -> flyway.setPlaceholderReplacer(new XMysqlToH2SqlReplacer());
}
}
}
| UTF-8 | Java | 4,221 | java | XFlywayAutoConfigurationTests.java | Java | [] | null | [] | /*
* Copyright 2017-2018 the original author or authors.
*
* 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.springframework.boot.autoconfigure.flyway;
import static org.assertj.core.api.Assertions.assertThat;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.flywaydb.core.XFlyway;
import org.flywaydb.core.internal.util.XMysqlToH2SqlReplacer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.flyway.XFlywayAutoConfigurationTests.XOptionalConfiguration;
import org.springframework.boot.autoconfigure.jdbc.XDataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Tests for {@link XFlywayAutoConfiguration}
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
/* @formatter:off */
XFlywayAutoConfiguration.class,
XDataSourceAutoConfiguration.class,
XOptionalConfiguration.class
/* @formatter:on */
})
@ActiveProfiles({ "test", "test-flyway-config" })
public class XFlywayAutoConfigurationTests {
/**
* Schema: foo
*/
private static final String SCHEMA_FOO = "foo";
/**
* Schema: bar
*/
private static final String SCHEMA_BAR = "bar";
/**
* {@link XFlyway}
*/
@Autowired
private XFlyway flyway;
/**
* {@link DataSource}
*/
@Autowired
private DataSource dataSource;
/**
* Annotation
*/
@Test
public void annotation() {
ConditionalOnProperty property = AnnotationUtils.findAnnotation(XFlywayAutoConfiguration.class,
ConditionalOnProperty.class);
assertThat(property.prefix()).isEqualTo(XFlywayProperties.PREFIX);
assertThat(property.name()).isEqualTo(new String[] { "enabled" });
assertThat(property.havingValue()).isEqualTo("true");
assertThat(property.matchIfMissing()).isEqualTo(false);
}
/**
* {@link org.springframework.boot.autoconfigure.flyway.XFlywayAutoConfiguration.XFlywayConfiguration#flyway()}
*/
@Test
public void flyway() {
assertThat(this.hasData(SCHEMA_FOO)).isEqualTo(false);
assertThat(this.hasData(SCHEMA_BAR)).isEqualTo(false);
this.flyway.migrate();
assertThat(this.hasData(SCHEMA_FOO)).isEqualTo(true);
assertThat(this.hasData(SCHEMA_BAR)).isEqualTo(true);
}
/**
* Has data?
*
* @param name name
* @return {@code true} if has data
*/
private boolean hasData(String name) {
try (Connection connection = this.dataSource.getConnection()) {
try (ResultSet result = connection.prepareCall("select * from " + name + "." + name).executeQuery()) {
if (!result.next()) {
return false;
}
return result.getString("code").equals(name);
}
}
catch (SQLException e) {
// No table
if (e.getMessage().contains("not found")) {
return false;
}
throw new IllegalStateException("Failed to execute SQL", e);
}
}
/**
* {@link Configuration} for optional
*/
@Configuration
protected static class XOptionalConfiguration {
/**
* {@link XFlywayMigrationStrategy}
*
* @return {@link XFlywayMigrationStrategy}
*/
@Bean
public XFlywayMigrationStrategy migrationStrategy() {
return flyway -> flyway.setPlaceholderReplacer(new XMysqlToH2SqlReplacer());
}
}
}
| 4,221 | 0.733476 | 0.729922 | 157 | 25.885351 | 26.933031 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.515924 | false | false | 13 |
27908fd1c06e2a74becab3b1f391f0cd17e43449 | 17,575,006,206,958 | ca0e9689023cc9998c7f24b9e0532261fd976e0e | /src/com/tencent/mm/pluginsdk/ui/chat/at.java | d21c9f1a56b9bcd6fb46727797e5f6a6c400192a | [] | no_license | honeyflyfish/com.tencent.mm | https://github.com/honeyflyfish/com.tencent.mm | c7e992f51070f6ac5e9c05e9a2babd7b712cf713 | ce6e605ff98164359a7073ab9a62a3f3101b8c34 | refs/heads/master | 2020-03-28T15:42:52.284000 | 2016-07-19T16:33:30 | 2016-07-19T16:33:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.tencent.mm.pluginsdk.ui.chat;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.tencent.mm.sdk.platformtools.ac;
import com.tencent.mm.sdk.platformtools.e;
import com.tencent.mm.sdk.platformtools.t;
final class at
implements Runnable
{
at(aq paramaq, ac paramac) {}
public final void run()
{
int i = 1;
aq localaq = gVQ;
String str = localaq.aBs();
if (str == null) {
i = 0;
}
while (i != 0)
{
gVR.sendEmptyMessage(0);
return;
int j = (int)localaq.lI(70);
int k = (int)localaq.lI(120);
int m = (int)localaq.lI(4);
bitmap = e.a(e.a(str, k, j, true), true, m);
boF.edit().putString("chattingui_recent_shown_image_path", gVL.gVJ).commit();
t.d("!44@/B4Tb64lLpKYgkPW7g2h7ZPkZDASCTQgMn5vbr5V3XA=", "check ok");
}
t.d("!44@/B4Tb64lLpKYgkPW7g2h7ZPkZDASCTQgMn5vbr5V3XA=", "check false");
}
public final String toString()
{
return super.toString() + "|checkIfShow";
}
}
/* Location:
* Qualified Name: com.tencent.mm.pluginsdk.ui.chat.at
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,180 | java | at.java | Java | [] | null | [] | package com.tencent.mm.pluginsdk.ui.chat;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.tencent.mm.sdk.platformtools.ac;
import com.tencent.mm.sdk.platformtools.e;
import com.tencent.mm.sdk.platformtools.t;
final class at
implements Runnable
{
at(aq paramaq, ac paramac) {}
public final void run()
{
int i = 1;
aq localaq = gVQ;
String str = localaq.aBs();
if (str == null) {
i = 0;
}
while (i != 0)
{
gVR.sendEmptyMessage(0);
return;
int j = (int)localaq.lI(70);
int k = (int)localaq.lI(120);
int m = (int)localaq.lI(4);
bitmap = e.a(e.a(str, k, j, true), true, m);
boF.edit().putString("chattingui_recent_shown_image_path", gVL.gVJ).commit();
t.d("!44@/B4Tb64lLpKYgkPW7g2h7ZPkZDASCTQgMn5vbr5V3XA=", "check ok");
}
t.d("!44@/B4Tb64lLpKYgkPW7g2h7ZPkZDASCTQgMn5vbr5V3XA=", "check false");
}
public final String toString()
{
return super.toString() + "|checkIfShow";
}
}
/* Location:
* Qualified Name: com.tencent.mm.pluginsdk.ui.chat.at
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 1,180 | 0.638983 | 0.605932 | 46 | 24.673914 | 21.504353 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 13 |
23939981f0b8090e33aac402ec129e18ca02daf1 | 18,957,985,658,812 | 15bc5fac153bc4e4cf94dcdb2f5d6bcc6b0212ba | /dynamic-programming/SubsetSum.java | 6476aeb0140ec02a480ce00f1d4bb032a3e902b8 | [] | no_license | dee-fiance/Algorithms-DataStructures | https://github.com/dee-fiance/Algorithms-DataStructures | 4e39685fcbf9acf6185728fa9fb643a9f4c77b58 | 5907eae5dd2a68df159e5f5d55d9906c3a2f5f51 | refs/heads/master | 2020-04-11T14:25:12.826000 | 2019-09-25T22:39:51 | 2019-09-25T22:39:51 | 161,854,299 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
Detect if a subset from a given set of N non-negative integers sums up to a given value S.
Example:
Input: Set: {1, 3, 9, 2}, S = 5
Output: true
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
Solution:
The recursive solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem).
We can solve the problem in Pseudo-polynomial time using Dynamic programming.
Time: O(sum*N)
0 1 2 3 4 5 6 7 8 9
0 T F F F F F F F F F
3 T F F T F F F F F F
34 T F F T F F F F F F
4 T F F T T F F T F F
12 T F F T T F F T F F
5 T F F T T T F T T T
2 T F T T T T T T F T
**/
public boolean SubsetSum() {
boolean table[][] = new boolean [input.length][sum+1];
int input[] = {3,34,4,12,5,2}
for(int i=0; i < input.length ; i++)
table[i][0] = true;
for(int j=1; j<=sum; j++)
table[0][j] = false;
for(int i=1; I <= input.length ; i++) {
for(int j=1; j<=sum; j++) {
if(j - input[i] >=0) {
table[i][j] = table[i-1][j] || table[i-1][j - input[i] ];
//excluding current element can u find the sum || including current element can u find sum-current.
else table[i][j] = tabl1[i-1][j];
}
}
return table[input.length][sum];
}
| UTF-8 | Java | 1,380 | java | SubsetSum.java | Java | [] | null | [] | /**
Detect if a subset from a given set of N non-negative integers sums up to a given value S.
Example:
Input: Set: {1, 3, 9, 2}, S = 5
Output: true
Input: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
Output: True //There is a subset (4, 5) with sum 9.
Solution:
The recursive solution may try all subsets of given set in worst case. Therefore time complexity of the above solution is exponential. The problem is in-fact NP-Complete (There is no known polynomial time solution for this problem).
We can solve the problem in Pseudo-polynomial time using Dynamic programming.
Time: O(sum*N)
0 1 2 3 4 5 6 7 8 9
0 T F F F F F F F F F
3 T F F T F F F F F F
34 T F F T F F F F F F
4 T F F T T F F T F F
12 T F F T T F F T F F
5 T F F T T T F T T T
2 T F T T T T T T F T
**/
public boolean SubsetSum() {
boolean table[][] = new boolean [input.length][sum+1];
int input[] = {3,34,4,12,5,2}
for(int i=0; i < input.length ; i++)
table[i][0] = true;
for(int j=1; j<=sum; j++)
table[0][j] = false;
for(int i=1; I <= input.length ; i++) {
for(int j=1; j<=sum; j++) {
if(j - input[i] >=0) {
table[i][j] = table[i-1][j] || table[i-1][j - input[i] ];
//excluding current element can u find the sum || including current element can u find sum-current.
else table[i][j] = tabl1[i-1][j];
}
}
return table[input.length][sum];
}
| 1,380 | 0.612364 | 0.571636 | 43 | 30.976744 | 39.425224 | 232 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.651163 | false | false | 13 |
206af8a7880a03eab40613acd619c975f195963e | 25,151,328,494,545 | ebb33c5a50a3835c03473f568e277250d50104a5 | /src/main/java/mabit/gui/javafx/table/GenericOrderPanelBuilder.java | 0f5b4bef6064f8bd9e714c49f2948510980f5da9 | [] | no_license | martinquebec/mabit | https://github.com/martinquebec/mabit | 033475569cec3cca6af362a4117b35cd17e32464 | ffeef222fad8f9eefecdb3e0f4543665f1be7479 | refs/heads/master | 2020-05-21T22:38:38.845000 | 2017-01-22T07:21:27 | 2017-01-22T07:21:27 | 63,477,509 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mabit.gui.javafx.table;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import mabit.gui.javafx.table.columnfactory.ColumnFactory;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.List;
/**
* Created by martin on 15/9/2016.
*/
//http://stackoverflow.com/questions/22417370/working-with-datetime-as-stringproperty
public class GenericOrderPanelBuilder {
private static final Logger Log = Logger.getLogger(GenericOrderPanelBuilder.class);
final BorderPane logPane;
final ObservableList<TableMapRow> data;
/* Parent root = null; */
public GenericOrderPanelBuilder(List<ColumnDef> colDefs) throws IOException {
logPane = new BorderPane();
logPane.setPrefSize(1000.0, 1400);
TableView table = new TableView();
for(ColumnDef colDef : colDefs) {
TableColumn<TableMapRow, Object> col = new TableColumn<>(colDef.getProperty());
col.setCellValueFactory(new AbstractPropertyValueFactory.ObjectPropertyValueFactory(colDef));
col.setEditable(false);
col.setPrefWidth(colDef.getPrefWith());
if(colDef.getType() != ColumnFactory.CellFactoryType.NONE ) {
col.setCellFactory( new ColumnFactory.CellFactoryCallBack(colDef.getType()));
}
table.getColumns().add(col);
}
this.data = FXCollections.observableArrayList();
table.setItems(data);
// table.setEditable(true);
logPane.setCenter(table);
}
public BorderPane getLogPane() {
return logPane;
}
public ObservableList<TableMapRow> getData() {
return data;
}
}
| UTF-8 | Java | 1,820 | java | GenericOrderPanelBuilder.java | Java | [
{
"context": "ception;\nimport java.util.List;\n\n/**\n * Created by martin on 15/9/2016.\n */\n//http://stackoverflow.com/ques",
"end": 403,
"score": 0.9861046671867371,
"start": 397,
"tag": "USERNAME",
"value": "martin"
}
] | null | [] | package mabit.gui.javafx.table;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import mabit.gui.javafx.table.columnfactory.ColumnFactory;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.List;
/**
* Created by martin on 15/9/2016.
*/
//http://stackoverflow.com/questions/22417370/working-with-datetime-as-stringproperty
public class GenericOrderPanelBuilder {
private static final Logger Log = Logger.getLogger(GenericOrderPanelBuilder.class);
final BorderPane logPane;
final ObservableList<TableMapRow> data;
/* Parent root = null; */
public GenericOrderPanelBuilder(List<ColumnDef> colDefs) throws IOException {
logPane = new BorderPane();
logPane.setPrefSize(1000.0, 1400);
TableView table = new TableView();
for(ColumnDef colDef : colDefs) {
TableColumn<TableMapRow, Object> col = new TableColumn<>(colDef.getProperty());
col.setCellValueFactory(new AbstractPropertyValueFactory.ObjectPropertyValueFactory(colDef));
col.setEditable(false);
col.setPrefWidth(colDef.getPrefWith());
if(colDef.getType() != ColumnFactory.CellFactoryType.NONE ) {
col.setCellFactory( new ColumnFactory.CellFactoryCallBack(colDef.getType()));
}
table.getColumns().add(col);
}
this.data = FXCollections.observableArrayList();
table.setItems(data);
// table.setEditable(true);
logPane.setCenter(table);
}
public BorderPane getLogPane() {
return logPane;
}
public ObservableList<TableMapRow> getData() {
return data;
}
}
| 1,820 | 0.698352 | 0.684615 | 55 | 32.072727 | 27.451679 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.563636 | false | false | 13 |
e87cc7044d2d500a6389e4abdaa61a22bfb60d35 | 3,736,621,601,729 | 0914fd59899ae68242c8285e106c81ca33fa8559 | /src/PalindromDynamic.java | e211de08da43bd6d6227fe25cacd658545fd82be | [] | no_license | ltregan/Algol | https://github.com/ltregan/Algol | 559ce1f493587f5bbec2851f066bb09be99ca8e7 | 3f2c4be72a1657915ff7f8c619ab446b3d780a31 | refs/heads/master | 2021-01-21T00:47:54.326000 | 2014-11-10T15:03:04 | 2014-11-10T15:03:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Created by ltregan on 23/10/2014.
*/
public class PalindromDynamic {
public static String longestPalindrome(String s){
int cache[][] = new int[s.length()][s.length()];
String result = "";
for( int i=0; i<s.length(); i++) {
System.out.println("------------- i="+i);
for (int j = i; j < s.length(); j++) {
// printTable( cache );
// System.out.println();
if( j-i+1 <= result.length() && result.length() >0 )
continue;
if (isPalindrom(s, cache, i ,j))
result = s.substring(i, j+1);
}
}
return result;
}
public static boolean isPalindrom(String s,int cache[][], int i, int j){
int x=i, y=j;
while( i <= j ){
if( cache[i][j] < 0) {
cache[x][y] = -1;
return false;
}
if( cache[i][j] > 0) {
cache[x][y] = 1;
return true;
}
if( s.charAt(i) != s.charAt(j) ) {
cache[x][y] = -1;
return false;
}
i++;
j--;
}
cache[x][y] = 1;
return true;
}
public static void printTable(int cache[][]){
for( int i=0 ;i < cache.length; i++){
System.out.print("[ ");
for( int j=0 ;j < cache[i].length; j++)
System.out.print(cache[i][j]+" ");
System.out.println("]");
}
}
}
| UTF-8 | Java | 1,563 | java | PalindromDynamic.java | Java | [
{
"context": "/**\n * Created by ltregan on 23/10/2014.\n */\npublic class PalindromDynamic ",
"end": 25,
"score": 0.9995142817497253,
"start": 18,
"tag": "USERNAME",
"value": "ltregan"
}
] | null | [] | /**
* Created by ltregan on 23/10/2014.
*/
public class PalindromDynamic {
public static String longestPalindrome(String s){
int cache[][] = new int[s.length()][s.length()];
String result = "";
for( int i=0; i<s.length(); i++) {
System.out.println("------------- i="+i);
for (int j = i; j < s.length(); j++) {
// printTable( cache );
// System.out.println();
if( j-i+1 <= result.length() && result.length() >0 )
continue;
if (isPalindrom(s, cache, i ,j))
result = s.substring(i, j+1);
}
}
return result;
}
public static boolean isPalindrom(String s,int cache[][], int i, int j){
int x=i, y=j;
while( i <= j ){
if( cache[i][j] < 0) {
cache[x][y] = -1;
return false;
}
if( cache[i][j] > 0) {
cache[x][y] = 1;
return true;
}
if( s.charAt(i) != s.charAt(j) ) {
cache[x][y] = -1;
return false;
}
i++;
j--;
}
cache[x][y] = 1;
return true;
}
public static void printTable(int cache[][]){
for( int i=0 ;i < cache.length; i++){
System.out.print("[ ");
for( int j=0 ;j < cache[i].length; j++)
System.out.print(cache[i][j]+" ");
System.out.println("]");
}
}
}
| 1,563 | 0.394754 | 0.381958 | 58 | 25.948277 | 19.572519 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 13 |
95cda2ece5afcd6aece4aabbe26d0b1bbe7679fd | 9,981,503,997,659 | a56f318c70b96842bf4d5380d721b87f998d128d | /asc/src/main/java/com/hj/pos/android/asc/AutoSizeButton.java | 383aad03fab3d6929ea321244e60516fe8ca5994 | [] | no_license | e2lc5/AutomaticSizeComponent | https://github.com/e2lc5/AutomaticSizeComponent | 5307abe0c7b49a4151ee382a9ae5dfc9927722f4 | 7dd0afbc93a06ef11b2de03e69bc8a54076dbd57 | refs/heads/master | 2020-04-15T15:11:19.940000 | 2020-02-25T08:56:35 | 2020-02-25T08:56:35 | 164,784,139 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hj.pos.android.asc;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import androidx.appcompat.widget.AppCompatButton;
import com.hj.pos.android.asc.emu.Orientation;
/**
* AutoSizeButton
* Created by zhanghuiqiang on 2017/2/14.
*/
public class AutoSizeButton extends AppCompatButton {
private double mScaleRate;
private int orientation;
private int widthSize;
private int heightSize;
public AutoSizeButton(Context context) {
this(context, null);
}
public AutoSizeButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.buttonStyle);
}
public AutoSizeButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AutoSizeTextView, defStyleAttr, 0);
mScaleRate = a.getFloat(R.styleable.AutoSizeTextView_mScaleRate, 0.35f);
if (a.hasValue(R.styleable.AutoSizeButton_tOrientation)) {
try {
orientation = a.getInt(R.styleable.AutoSizeButton_tOrientation, -1);
} catch (NumberFormatException n) {
// Log.e(getClass().getSimpleName(), "orientation unset");
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
widthSize = View.MeasureSpec.getSize(widthMeasureSpec);
heightSize = View.MeasureSpec.getSize(heightMeasureSpec); //获取高的尺寸
switch (orientation) {
case 0:
setTextSize(TypedValue.COMPLEX_UNIT_PX, heightSize * (float)
mScaleRate);
break;
case 1:
setTextSize(TypedValue.COMPLEX_UNIT_PX, widthSize * (float)
mScaleRate);
break;
case -1:
if (widthSize > heightSize) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, heightSize * (float)
mScaleRate);
} else {
setTextSize(TypedValue.COMPLEX_UNIT_PX, widthSize * (float)
mScaleRate);
}
break;
}
}
public double getmScaleRate() {
return mScaleRate;
}
public void setmScaleRate(double mScaleRate) {
this.mScaleRate = mScaleRate;
if (widthSize > heightSize) {
// 宽度大于高度 直接用高计算
setTextSize(TypedValue.COMPLEX_UNIT_PX, (heightSize * (float) mScaleRate));
} else {
// 高度大于宽大
if (orientation == Orientation.HORIZONTAL.getValue()) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, (heightSize * (float) mScaleRate));
} else if (orientation == Orientation.VERTICAL.getValue()) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, (widthSize * (float) mScaleRate));
}
}
}
}
| UTF-8 | Java | 3,166 | java | AutoSizeButton.java | Java | [
{
"context": "Orientation;\n\n\n/**\n * AutoSizeButton\n * Created by zhanghuiqiang on 2017/2/14.\n */\n\npublic class AutoSizeButton ex",
"end": 346,
"score": 0.9934501051902771,
"start": 333,
"tag": "USERNAME",
"value": "zhanghuiqiang"
}
] | null | [] | package com.hj.pos.android.asc;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import androidx.appcompat.widget.AppCompatButton;
import com.hj.pos.android.asc.emu.Orientation;
/**
* AutoSizeButton
* Created by zhanghuiqiang on 2017/2/14.
*/
public class AutoSizeButton extends AppCompatButton {
private double mScaleRate;
private int orientation;
private int widthSize;
private int heightSize;
public AutoSizeButton(Context context) {
this(context, null);
}
public AutoSizeButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.buttonStyle);
}
public AutoSizeButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AutoSizeTextView, defStyleAttr, 0);
mScaleRate = a.getFloat(R.styleable.AutoSizeTextView_mScaleRate, 0.35f);
if (a.hasValue(R.styleable.AutoSizeButton_tOrientation)) {
try {
orientation = a.getInt(R.styleable.AutoSizeButton_tOrientation, -1);
} catch (NumberFormatException n) {
// Log.e(getClass().getSimpleName(), "orientation unset");
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
widthSize = View.MeasureSpec.getSize(widthMeasureSpec);
heightSize = View.MeasureSpec.getSize(heightMeasureSpec); //获取高的尺寸
switch (orientation) {
case 0:
setTextSize(TypedValue.COMPLEX_UNIT_PX, heightSize * (float)
mScaleRate);
break;
case 1:
setTextSize(TypedValue.COMPLEX_UNIT_PX, widthSize * (float)
mScaleRate);
break;
case -1:
if (widthSize > heightSize) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, heightSize * (float)
mScaleRate);
} else {
setTextSize(TypedValue.COMPLEX_UNIT_PX, widthSize * (float)
mScaleRate);
}
break;
}
}
public double getmScaleRate() {
return mScaleRate;
}
public void setmScaleRate(double mScaleRate) {
this.mScaleRate = mScaleRate;
if (widthSize > heightSize) {
// 宽度大于高度 直接用高计算
setTextSize(TypedValue.COMPLEX_UNIT_PX, (heightSize * (float) mScaleRate));
} else {
// 高度大于宽大
if (orientation == Orientation.HORIZONTAL.getValue()) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, (heightSize * (float) mScaleRate));
} else if (orientation == Orientation.VERTICAL.getValue()) {
setTextSize(TypedValue.COMPLEX_UNIT_PX, (widthSize * (float) mScaleRate));
}
}
}
}
| 3,166 | 0.606479 | 0.601668 | 93 | 32.526882 | 28.392635 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.602151 | false | false | 13 |
c8b3dba916beeb5e241e8e6d83165525cc1f8277 | 26,774,826,138,543 | ac745a8ec10ce2bee6c9ea48dd5eba358f3ec45a | /TravelLogger_Project_KhirthanaSubramanian_and_Jaina_Patel/app/src/main/java/csci4100u/travellogger_project_khirthanasubramanian_and_jainapatel/NoteDBHelper.java | bb81fbca3b3edd4c7e91d30bfc6c6a3c8521b945 | [] | no_license | khirthana/MobileDevices | https://github.com/khirthana/MobileDevices | 1b04aab9937c4ccc0d36eb56008f003a0b51ee46 | 9ba84f42715d75dbb05baff154dcdc1fbffabbb9 | refs/heads/master | 2021-05-01T01:54:12.126000 | 2016-11-29T04:20:49 | 2016-11-29T04:20:49 | 70,266,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
CSCI4100U Project - TravelLogger
Team Members: Khirthana Subramanian(100453865) and Jaina Patel(100523188)
NoteDBHelper: database to store notes contents
*/
package csci4100u.travellogger_project_khirthanasubramanian_and_jainapatel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class NoteDBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notes";
private static final String TABLE_NOTE_DETAIL = "notesdetail";
private static final String KEY_id = "id";
private static final String KEY_name = "notename";
private static final String KEY_detail = "notedetail";
public NoteDBHelper (Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate (SQLiteDatabase db){
String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_NOTE_DETAIL + "("
+ KEY_id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_name + " TEXT,"
+ KEY_detail + " TEXT"+ ")";
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE_DETAIL);
onCreate(db);
}
public void addNote (String name, String desc){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_name,name);
contentValues.put(KEY_detail,desc);
db.insert(TABLE_NOTE_DETAIL, null, contentValues);
db.close();
}
public List<Note> getAllNotes (){
List<Note> nlist = new ArrayList<Note>();
String selectQuery = "SELECT * FROM " + TABLE_NOTE_DETAIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note task = new Note();
task.setId(cursor.getInt(0));
task.setNote_name(cursor.getString(1));
task.setNote_content(cursor.getString(2));
nlist.add(task);
} while (cursor.moveToNext());
}
return nlist;
}
public void deleteNote (String id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTE_DETAIL, KEY_id + " = ?", new String[] { id });
db.close();
}
public void updateNote(int id, String name, String content) {
SQLiteDatabase db = this.getWritableDatabase();
if (db == null) {
return;
}
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_detail, content);
db.update(TABLE_NOTE_DETAIL, values, KEY_id + " = ?", new String[] { String.valueOf(id) } );
db.close();
}
}
| UTF-8 | Java | 3,126 | java | NoteDBHelper.java | Java | [
{
"context": "SCI4100U Project - TravelLogger\n\n Team Members: Khirthana Subramanian(100453865) and Jaina Patel(100523188)\n\n NoteDB",
"end": 80,
"score": 0.9998874068260193,
"start": 59,
"tag": "NAME",
"value": "Khirthana Subramanian"
},
{
"context": "Team Members: Khirthana... | null | [] | /*
CSCI4100U Project - TravelLogger
Team Members: <NAME>(100453865) and <NAME>(100523188)
NoteDBHelper: database to store notes contents
*/
package csci4100u.travellogger_project_khirthanasubramanian_and_jainapatel;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class NoteDBHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "notes";
private static final String TABLE_NOTE_DETAIL = "notesdetail";
private static final String KEY_id = "id";
private static final String KEY_name = "notename";
private static final String KEY_detail = "notedetail";
public NoteDBHelper (Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public void onCreate (SQLiteDatabase db){
String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_NOTE_DETAIL + "("
+ KEY_id + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_name + " TEXT,"
+ KEY_detail + " TEXT"+ ")";
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTE_DETAIL);
onCreate(db);
}
public void addNote (String name, String desc){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_name,name);
contentValues.put(KEY_detail,desc);
db.insert(TABLE_NOTE_DETAIL, null, contentValues);
db.close();
}
public List<Note> getAllNotes (){
List<Note> nlist = new ArrayList<Note>();
String selectQuery = "SELECT * FROM " + TABLE_NOTE_DETAIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note task = new Note();
task.setId(cursor.getInt(0));
task.setNote_name(cursor.getString(1));
task.setNote_content(cursor.getString(2));
nlist.add(task);
} while (cursor.moveToNext());
}
return nlist;
}
public void deleteNote (String id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTE_DETAIL, KEY_id + " = ?", new String[] { id });
db.close();
}
public void updateNote(int id, String name, String content) {
SQLiteDatabase db = this.getWritableDatabase();
if (db == null) {
return;
}
ContentValues values = new ContentValues();
values.put(KEY_name, name);
values.put(KEY_detail, content);
db.update(TABLE_NOTE_DETAIL, values, KEY_id + " = ?", new String[] { String.valueOf(id) } );
db.close();
}
}
| 3,106 | 0.631158 | 0.621561 | 103 | 29.349514 | 26.079679 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.660194 | false | false | 13 |
52e4211ac36d29fc3d1e4e7af02cbad518f00202 | 28,020,366,694,592 | 1cc48e969e38d9411e2c8df0d2611edee8508a92 | /keijiban/WEB-INF/src/keijiban/DBManager.java | 3df1baff2313ee29db662bf4338f19113d9a29b8 | [] | no_license | Masatomo-Hamada/bbs | https://github.com/Masatomo-Hamada/bbs | d69c1c75beffee44c2f42fb441f0970b097009dd | ab1bd9341f6d5556394dd591477df6ddd0b6513d | refs/heads/master | 2020-12-10T03:22:52.699000 | 2017-06-28T01:12:05 | 2017-06-28T01:12:05 | 95,519,108 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package keijiban;
import java.sql.Connection;
import java.sql.DriverManager;
/** DB接続用クラス*/
public class DBManager {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/DB_KEIJIBAN", "KEIUSER", "SSS");
return con;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| UTF-8 | Java | 443 | java | DBManager.java | Java | [] | null | [] | package keijiban;
import java.sql.Connection;
import java.sql.DriverManager;
/** DB接続用クラス*/
public class DBManager {
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/DB_KEIJIBAN", "KEIUSER", "SSS");
return con;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| 443 | 0.675174 | 0.675174 | 20 | 19.549999 | 24.292952 | 104 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.45 | false | false | 13 |
9742943c9850fd6b6ad759c2d978640631f6f8b4 | 14,164,802,168,774 | e66bae327f69a1aa9e4a06690abe4fb08402d9d0 | /taverna-workbench-renderers-impl/src/main/java/net/sf/taverna/t2/renderers/impl/AdvancedImageRenderer.java | 6c15834aa490aa92c481c2a520064f794b8916a2 | [] | no_license | taverna-incubator/incubator-taverna-workbench | https://github.com/taverna-incubator/incubator-taverna-workbench | a1d6728c2cf45987264893f14f601c5f754ac46e | de04c8f86c4da42a0dedb4a66e90cdba9263420d | refs/heads/master | 2021-01-20T21:31:44.566000 | 2015-02-05T10:38:46 | 2015-02-05T10:38:46 | 30,350,440 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*******************************************************************************
* Copyright (C) 2007 The University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
******************************************************************************/
package net.sf.taverna.t2.renderers.impl;
import static javax.imageio.ImageIO.getReaderMIMETypes;
import static javax.imageio.ImageIO.getWriterFormatNames;
import static net.sf.taverna.t2.renderers.RendererUtils.getInputStream;
import static net.sf.taverna.t2.renderers.impl.RendererConstants.SEE_LOG_MSG;
import java.awt.Image;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import org.apache.log4j.Logger;
/**
* Advanced renderer for mime type image/* that can render tiff files. Uses Java
* Advanced Imaging (JAI) ImageIO from https://jai-imageio.dev.java.net/.
*
* @author Alex Nenadic
* @author David Withers
*/
public class AdvancedImageRenderer extends AbstractRenderer {
private static final String BAD_FORMAT_MSG = "Data does not seem to contain an image in any of the recognised formats:\n";
private static final String UNRENDERABLE_MSG = "Failed to create image renderer " + SEE_LOG_MSG;
private Logger logger = Logger.getLogger(AdvancedImageRenderer.class);
private List<String> mimeTypesList;
public AdvancedImageRenderer() {
mimeTypesList = Arrays.asList(getReaderMIMETypes());
}
@Override
public boolean canHandle(String mimeType) {
return mimeTypesList.contains(mimeType);
}
@Override
public String getType() {
return "Image";
}
@Override
public JComponent getRendererComponent(Path path) {
// Render into a label
try (InputStream inputStream = getInputStream(path)) {
Image image = ImageIO.read(inputStream);
if (image == null)
return new JTextArea(BAD_FORMAT_MSG
+ Arrays.asList(getWriterFormatNames()));
return new JLabel(new ImageIcon(image));
} catch (Exception e) {
logger.error("unrenderable: failed to create image renderer", e);
return new JTextArea(UNRENDERABLE_MSG + e.getMessage());
}
}
@Override
protected int getSizeLimit() {
return 4;
}
@Override
protected String getResultType() {
return "Image";
}
}
| UTF-8 | Java | 3,205 | java | AdvancedImageRenderer.java | Java | [
{
"context": " https://jai-imageio.dev.java.net/.\n * \n * @author Alex Nenadic\n * @author David Withers\n */\npublic class Advance",
"end": 1888,
"score": 0.9998501539230347,
"start": 1876,
"tag": "NAME",
"value": "Alex Nenadic"
},
{
"context": ".java.net/.\n * \n * @author Alex Ne... | null | [] | /*******************************************************************************
* Copyright (C) 2007 The University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
******************************************************************************/
package net.sf.taverna.t2.renderers.impl;
import static javax.imageio.ImageIO.getReaderMIMETypes;
import static javax.imageio.ImageIO.getWriterFormatNames;
import static net.sf.taverna.t2.renderers.RendererUtils.getInputStream;
import static net.sf.taverna.t2.renderers.impl.RendererConstants.SEE_LOG_MSG;
import java.awt.Image;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import org.apache.log4j.Logger;
/**
* Advanced renderer for mime type image/* that can render tiff files. Uses Java
* Advanced Imaging (JAI) ImageIO from https://jai-imageio.dev.java.net/.
*
* @author <NAME>
* @author <NAME>
*/
public class AdvancedImageRenderer extends AbstractRenderer {
private static final String BAD_FORMAT_MSG = "Data does not seem to contain an image in any of the recognised formats:\n";
private static final String UNRENDERABLE_MSG = "Failed to create image renderer " + SEE_LOG_MSG;
private Logger logger = Logger.getLogger(AdvancedImageRenderer.class);
private List<String> mimeTypesList;
public AdvancedImageRenderer() {
mimeTypesList = Arrays.asList(getReaderMIMETypes());
}
@Override
public boolean canHandle(String mimeType) {
return mimeTypesList.contains(mimeType);
}
@Override
public String getType() {
return "Image";
}
@Override
public JComponent getRendererComponent(Path path) {
// Render into a label
try (InputStream inputStream = getInputStream(path)) {
Image image = ImageIO.read(inputStream);
if (image == null)
return new JTextArea(BAD_FORMAT_MSG
+ Arrays.asList(getWriterFormatNames()));
return new JLabel(new ImageIcon(image));
} catch (Exception e) {
logger.error("unrenderable: failed to create image renderer", e);
return new JTextArea(UNRENDERABLE_MSG + e.getMessage());
}
}
@Override
protected int getSizeLimit() {
return 4;
}
@Override
protected String getResultType() {
return "Image";
}
}
| 3,192 | 0.717005 | 0.709204 | 94 | 33.095745 | 28.675392 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.148936 | false | false | 13 |
affaf1e515f4af5e1e15f090825b5d984d9a02d2 | 2,783,138,839,379 | b5772a066892ea0ec014969da09ab870ed3b4ba3 | /src/main/java/fr/univ_amu/iut/twitminer/Main.java | 10a68d83a8541655d9b707a46a646ab7f63343e9 | [] | no_license | Pyrrha/TwitMiner | https://github.com/Pyrrha/TwitMiner | a4e448f644c4fbaa7485f9e1356979c1a312ba11 | d4f1c9bb50eadf12aaa62689ba68786c78004c89 | refs/heads/master | 2021-06-15T10:57:46.179000 | 2017-04-07T06:52:55 | 2017-04-07T06:52:55 | 86,814,927 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fr.univ_amu.iut.twitminer;
import static fr.univ_amu.iut.twitminer.AprioriInterface.apriori;
import static fr.univ_amu.iut.twitminer.Converter.CSVtoTrans;
import static fr.univ_amu.iut.twitminer.Converter.decodeTrans;
public class Main {
public static void main(String[] args) {
//getTwits();
CSVtoTrans("resultats.csv");
apriori("twit.trans","out.txt",50);
decodeTrans("./out.txt");
}
}
| UTF-8 | Java | 438 | java | Main.java | Java | [] | null | [] | package fr.univ_amu.iut.twitminer;
import static fr.univ_amu.iut.twitminer.AprioriInterface.apriori;
import static fr.univ_amu.iut.twitminer.Converter.CSVtoTrans;
import static fr.univ_amu.iut.twitminer.Converter.decodeTrans;
public class Main {
public static void main(String[] args) {
//getTwits();
CSVtoTrans("resultats.csv");
apriori("twit.trans","out.txt",50);
decodeTrans("./out.txt");
}
}
| 438 | 0.696347 | 0.691781 | 14 | 30.285715 | 22.524363 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 13 |
36b3b2a8c41aa4462044c6f40c2d07005e92615e | 27,462,020,920,042 | d0b7fc167843763a52d5b832324fa10996f1004d | /ToyStorey.java | a6afef81e6b52f5a97c443c752c1350c646b7ae6 | [] | no_license | ecembalikci/Toy-Storey | https://github.com/ecembalikci/Toy-Storey | 99391267f619f1791bb03b032e8d9e02111eeff3 | dcbc4d6492453a3b9ae60112e21288cafc87f0d9 | refs/heads/master | 2020-05-03T09:09:10.268000 | 2019-03-30T11:00:14 | 2019-03-30T11:00:14 | 178,546,644 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
public class ToyStorey {
private String yourToysName;
private int creditCardNumber;
public void setName(String itsName){
yourToysName=itsName;
}
void setNumber(int yourCreditCardNumber){
this.creditCardNumber=yourCreditCardNumber;
return;
}
public String getName() {
return yourToysName;
}
public int getNumber() {
return creditCardNumber;
}
public void display() {
System.out.println("The information for your toy and your credit card number for payment(You can be sure that this program is safe)");
System.out.println( "Your toy's name: " + getName() );
System.out.println( "Credit Card Number: " + getNumber() );
System.out.println();
}
}
//This class is just for get toy's name and get the credit card number from customer.So it's the first part of the program.
| UTF-8 | Java | 1,040 | java | ToyStorey.java | Java | [] | null | [] | import java.util.*;
public class ToyStorey {
private String yourToysName;
private int creditCardNumber;
public void setName(String itsName){
yourToysName=itsName;
}
void setNumber(int yourCreditCardNumber){
this.creditCardNumber=yourCreditCardNumber;
return;
}
public String getName() {
return yourToysName;
}
public int getNumber() {
return creditCardNumber;
}
public void display() {
System.out.println("The information for your toy and your credit card number for payment(You can be sure that this program is safe)");
System.out.println( "Your toy's name: " + getName() );
System.out.println( "Credit Card Number: " + getNumber() );
System.out.println();
}
}
//This class is just for get toy's name and get the credit card number from customer.So it's the first part of the program.
| 1,040 | 0.579808 | 0.579808 | 32 | 30.4375 | 33.829479 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 13 |
5528720a03f66bf5e178c9381a64ce775f04666f | 523,986,049,434 | b639977e84c152553dd9c74bda1ead2d8d0875e9 | /src/main/java/mx/com/aon/portal/model/UserVO.java | 7836ddeaac550ef399aacb2601577f908e75f0c8 | [] | no_license | BiosnetTCS/ice_all | https://github.com/BiosnetTCS/ice_all | a41e6deba3c947e369855ab68cb1c9442a4c6077 | d47f6d9a0f10dd5382b5a8fa6c6072db62cda276 | HEAD | 2018-04-07T16:10:49.031000 | 2017-05-02T15:47:17 | 2017-05-02T15:47:17 | 89,630,581 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
*
* Creado el 24/01/2008 11:36:29 a.m. (dd/mm/aaaa hh:mm:ss)
*
* Copyright (C) Biosnet S.C.
* All rights reserved. Todos los derechos reservados.
*
* http://www.biosnetmx.com/
*/
package mx.com.aon.portal.model;
import java.io.Serializable;
import java.util.List;
import mx.com.aon.portal.util.UserSQLDateConverter;
import mx.com.aon.portal.util.UserStringConverter;
import mx.com.aon.portal.util.UserTimestampConverter;
import mx.com.gseguros.portal.general.model.RolVO;
import mx.com.gseguros.utils.Utils;
import org.apache.commons.beanutils.Converter;
import org.apache.log4j.Logger;
/**
* Contiene la información del usuario ingresado
*/
public class UserVO implements Serializable {
/**
* UID Por defecto
*/
private static final long serialVersionUID = -1963470818294994036L;
private Logger logger = Logger.getLogger(UserVO.class);
private String codigoPersona;
private String name;
private String lastName;
private String perfil;
private PerfilVO fuentesPerfil;
private String cdUnieco;
private String user;
private String personId;
private String email;
private BaseObjectVO region;
private BaseObjectVO pais;
private BaseObjectVO idioma;
private List<RolVO> roles;
private EmpresaVO empresa;
private int tamagnoPaginacionGrid;
private String formatoNumerico;
private String formatoFecha;
private RolVO rolActivo;
private String cdElemento;
private String formatDate = "dd/MM/yyyy";
private String clientFormatDate = "";
private String decimalSeparator = ",";
private List<MenuPrincipalVO> listaMenu;
private List<MenuPrincipalVO> listaMenuVertical;
private Converter converterStringToDate;
private Converter converterToString;
private Converter converterStringToTimestamp;
private String currentUrl;
private String method;
/**
* Clave interna de GSeguros del usuario que captura un trámite
*/
private String claveUsuarioCaptura;
public UserVO () {
this.setFormatDate(formatDate);
}
/**
* @return the rolActivo
*/
public RolVO getRolActivo() {
return rolActivo;
}
/**
* @param rolActivo the rolActivo to set
*/
public void setRolActivo(RolVO rolActivo) {
this.rolActivo = rolActivo;
}
// Getters and Setters
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return perfil
*/
public String getPerfil() {
return perfil;
}
/**
* @param perfil
*/
public void setPerfil(String perfil) {
this.perfil = perfil;
}
/**
* @return fuentesPerfil
*/
public PerfilVO getFuentesPerfil() {
return fuentesPerfil;
}
/**
* @param fuentesPerfil
*/
public void setFuentesPerfil(PerfilVO fuentesPerfil) {
this.fuentesPerfil = fuentesPerfil;
}
/**
* @return user
*/
public String getUser() {
return user;
}
/**
* @param user
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return personId
*/
public String getPersonId() {
return personId;
}
/**
* @param personId
*/
public void setPersonId(String personId) {
this.personId = personId;
}
/**
* @return roles
*/
public List<RolVO> getRoles() {
return roles;
}
/**
* @param roles
*/
public void setRoles(List<RolVO> roles) {
this.roles = roles;
}
/**
* @return
*/
public int getTamagnoPaginacionGrid() {
return tamagnoPaginacionGrid;
}
/**
* @param tamagnoPaginacionGrid
*/
public void setTamagnoPaginacionGrid(int tamagnoPaginacionGrid) {
this.tamagnoPaginacionGrid = tamagnoPaginacionGrid;
}
/**
* @return
*/
public String getFormatoNumerico() {
return formatoNumerico;
}
/**
* @param formatoNumerico
*/
public void setFormatoNumerico(String formatoNumerico) {
this.formatoNumerico = formatoNumerico;
}
/**
* @return
*/
public String getFormatoFecha() {
return formatoFecha;
}
/**
* @param formatoFecha
*/
public void setFormatoFecha(String formatoFecha) {
this.formatoFecha = formatoFecha;
}
/**
* @return the codigoPersona
*/
public String getCodigoPersona() {
return codigoPersona;
}
/**
* @param codigoPersona the codigoPersona to set
*/
public void setCodigoPersona(String codigoPersona) {
this.codigoPersona = codigoPersona;
}
public String getCdElemento() {
return cdElemento;
}
public void setCdElemento(String cdElemento) {
this.cdElemento = cdElemento;
}
public String getFormatDate() {
return formatDate;
}
public void setFormatDate(String formatDate) {
this.formatDate = formatDate;
converterStringToDate = new UserSQLDateConverter(formatDate);
//converterToString = new UserStringConverter(formatDate);
converterStringToTimestamp = new UserTimestampConverter(formatDate);
}
public Converter getConverterStringToDate() {
return converterStringToDate;
}
public Converter getConverterToString() {
return converterToString;
}
public Converter getConverterStringToTimestamp() {
return converterStringToTimestamp;
}
public EmpresaVO getEmpresa() {
return empresa;
}
public void setEmpresa(EmpresaVO empresa) {
this.empresa = empresa;
}
public BaseObjectVO getIdioma() {
return idioma;
}
public void setIdioma(BaseObjectVO idioma) {
this.idioma = idioma;
}
public BaseObjectVO getPais() {
return pais;
}
public void setPais(BaseObjectVO pais) {
this.pais = pais;
}
public BaseObjectVO getRegion() {
return region;
}
public void setRegion(BaseObjectVO region) {
this.region = region;
}
public List<MenuPrincipalVO> getListaMenu() {
return listaMenu;
}
public void setListaMenu(List<MenuPrincipalVO> listaMenu) {
this.listaMenu = listaMenu;
}
public List<MenuPrincipalVO> getListaMenuVertical() {
return listaMenuVertical;
}
public void setListaMenuVertical(List<MenuPrincipalVO> listaMenuVertical) {
this.listaMenuVertical = listaMenuVertical;
}
public String getCurrentUrl() {
return currentUrl;
}
public void setCurrentUrl(String currentUrl) {
this.currentUrl = currentUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDecimalSeparator() {
return decimalSeparator;
}
public void setDecimalSeparator(String decimalSeparator) {
this.decimalSeparator = decimalSeparator;
}
public String getClientFormatDate() {
return clientFormatDate;
}
public void setClientFormatDate(String clientFormatDate) {
logger.debug("En UserVO: " + clientFormatDate);
if (clientFormatDate == null || clientFormatDate.equals("")) {
this.clientFormatDate = "d/m/Y"; //Formato por defecto
}else {
this.clientFormatDate = clientFormatDate;
}
logger.debug("En UserVO queda: " + this.clientFormatDate);
String _clientDateFormat = this.clientFormatDate.replace("d", "dd");
_clientDateFormat = _clientDateFormat.replace("m", "MM");
_clientDateFormat = _clientDateFormat.replace("Y", "yyyy");
logger.debug("En UserVO el converter: " + _clientDateFormat);
//Seteo del conversor por defecto
converterToString = new UserStringConverter(_clientDateFormat);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getClaveUsuarioCaptura() {
return claveUsuarioCaptura;
}
public void setClaveUsuarioCaptura(String claveUsuarioCaptura) {
this.claveUsuarioCaptura = claveUsuarioCaptura;
}
public String getCdUnieco() {
return cdUnieco;
}
public void setCdUnieco(String cdUnieco) {
this.cdUnieco = cdUnieco;
}
@Override
public String toString()
{
return Utils.join(
"\n*********************"
,"\n****** USUARIO ******"
,"\n*** cdusuari = " , this.user
,"\n*** cdsisrol = " , (this.rolActivo == null ? null : this.rolActivo.getClave())
,"\n*** name = " , this.name
,"\n*** cdunieco = " , this.cdUnieco
,"\n*** elementoId = " , (this.empresa == null ? null : this.empresa.getElementoId())
,"\n*********************"
);
}
} | UTF-8 | Java | 9,051 | java | UserVO.java | Java | [
{
"context": ":29 a.m. (dd/mm/aaaa hh:mm:ss)\n *\n * Copyright (C) Biosnet S.C.\n * All rights reserved. Todos los derechos r",
"end": 94,
"score": 0.771375834941864,
"start": 87,
"tag": "NAME",
"value": "Biosnet"
},
{
"context": "dd/mm/aaaa hh:mm:ss)\n *\n * Copyright (C) Biosnet S.... | null | [] | /*
*
* Creado el 24/01/2008 11:36:29 a.m. (dd/mm/aaaa hh:mm:ss)
*
* Copyright (C) Biosnet S.C.
* All rights reserved. Todos los derechos reservados.
*
* http://www.biosnetmx.com/
*/
package mx.com.aon.portal.model;
import java.io.Serializable;
import java.util.List;
import mx.com.aon.portal.util.UserSQLDateConverter;
import mx.com.aon.portal.util.UserStringConverter;
import mx.com.aon.portal.util.UserTimestampConverter;
import mx.com.gseguros.portal.general.model.RolVO;
import mx.com.gseguros.utils.Utils;
import org.apache.commons.beanutils.Converter;
import org.apache.log4j.Logger;
/**
* Contiene la información del usuario ingresado
*/
public class UserVO implements Serializable {
/**
* UID Por defecto
*/
private static final long serialVersionUID = -1963470818294994036L;
private Logger logger = Logger.getLogger(UserVO.class);
private String codigoPersona;
private String name;
private String lastName;
private String perfil;
private PerfilVO fuentesPerfil;
private String cdUnieco;
private String user;
private String personId;
private String email;
private BaseObjectVO region;
private BaseObjectVO pais;
private BaseObjectVO idioma;
private List<RolVO> roles;
private EmpresaVO empresa;
private int tamagnoPaginacionGrid;
private String formatoNumerico;
private String formatoFecha;
private RolVO rolActivo;
private String cdElemento;
private String formatDate = "dd/MM/yyyy";
private String clientFormatDate = "";
private String decimalSeparator = ",";
private List<MenuPrincipalVO> listaMenu;
private List<MenuPrincipalVO> listaMenuVertical;
private Converter converterStringToDate;
private Converter converterToString;
private Converter converterStringToTimestamp;
private String currentUrl;
private String method;
/**
* Clave interna de GSeguros del usuario que captura un trámite
*/
private String claveUsuarioCaptura;
public UserVO () {
this.setFormatDate(formatDate);
}
/**
* @return the rolActivo
*/
public RolVO getRolActivo() {
return rolActivo;
}
/**
* @param rolActivo the rolActivo to set
*/
public void setRolActivo(RolVO rolActivo) {
this.rolActivo = rolActivo;
}
// Getters and Setters
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return perfil
*/
public String getPerfil() {
return perfil;
}
/**
* @param perfil
*/
public void setPerfil(String perfil) {
this.perfil = perfil;
}
/**
* @return fuentesPerfil
*/
public PerfilVO getFuentesPerfil() {
return fuentesPerfil;
}
/**
* @param fuentesPerfil
*/
public void setFuentesPerfil(PerfilVO fuentesPerfil) {
this.fuentesPerfil = fuentesPerfil;
}
/**
* @return user
*/
public String getUser() {
return user;
}
/**
* @param user
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return personId
*/
public String getPersonId() {
return personId;
}
/**
* @param personId
*/
public void setPersonId(String personId) {
this.personId = personId;
}
/**
* @return roles
*/
public List<RolVO> getRoles() {
return roles;
}
/**
* @param roles
*/
public void setRoles(List<RolVO> roles) {
this.roles = roles;
}
/**
* @return
*/
public int getTamagnoPaginacionGrid() {
return tamagnoPaginacionGrid;
}
/**
* @param tamagnoPaginacionGrid
*/
public void setTamagnoPaginacionGrid(int tamagnoPaginacionGrid) {
this.tamagnoPaginacionGrid = tamagnoPaginacionGrid;
}
/**
* @return
*/
public String getFormatoNumerico() {
return formatoNumerico;
}
/**
* @param formatoNumerico
*/
public void setFormatoNumerico(String formatoNumerico) {
this.formatoNumerico = formatoNumerico;
}
/**
* @return
*/
public String getFormatoFecha() {
return formatoFecha;
}
/**
* @param formatoFecha
*/
public void setFormatoFecha(String formatoFecha) {
this.formatoFecha = formatoFecha;
}
/**
* @return the codigoPersona
*/
public String getCodigoPersona() {
return codigoPersona;
}
/**
* @param codigoPersona the codigoPersona to set
*/
public void setCodigoPersona(String codigoPersona) {
this.codigoPersona = codigoPersona;
}
public String getCdElemento() {
return cdElemento;
}
public void setCdElemento(String cdElemento) {
this.cdElemento = cdElemento;
}
public String getFormatDate() {
return formatDate;
}
public void setFormatDate(String formatDate) {
this.formatDate = formatDate;
converterStringToDate = new UserSQLDateConverter(formatDate);
//converterToString = new UserStringConverter(formatDate);
converterStringToTimestamp = new UserTimestampConverter(formatDate);
}
public Converter getConverterStringToDate() {
return converterStringToDate;
}
public Converter getConverterToString() {
return converterToString;
}
public Converter getConverterStringToTimestamp() {
return converterStringToTimestamp;
}
public EmpresaVO getEmpresa() {
return empresa;
}
public void setEmpresa(EmpresaVO empresa) {
this.empresa = empresa;
}
public BaseObjectVO getIdioma() {
return idioma;
}
public void setIdioma(BaseObjectVO idioma) {
this.idioma = idioma;
}
public BaseObjectVO getPais() {
return pais;
}
public void setPais(BaseObjectVO pais) {
this.pais = pais;
}
public BaseObjectVO getRegion() {
return region;
}
public void setRegion(BaseObjectVO region) {
this.region = region;
}
public List<MenuPrincipalVO> getListaMenu() {
return listaMenu;
}
public void setListaMenu(List<MenuPrincipalVO> listaMenu) {
this.listaMenu = listaMenu;
}
public List<MenuPrincipalVO> getListaMenuVertical() {
return listaMenuVertical;
}
public void setListaMenuVertical(List<MenuPrincipalVO> listaMenuVertical) {
this.listaMenuVertical = listaMenuVertical;
}
public String getCurrentUrl() {
return currentUrl;
}
public void setCurrentUrl(String currentUrl) {
this.currentUrl = currentUrl;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getDecimalSeparator() {
return decimalSeparator;
}
public void setDecimalSeparator(String decimalSeparator) {
this.decimalSeparator = decimalSeparator;
}
public String getClientFormatDate() {
return clientFormatDate;
}
public void setClientFormatDate(String clientFormatDate) {
logger.debug("En UserVO: " + clientFormatDate);
if (clientFormatDate == null || clientFormatDate.equals("")) {
this.clientFormatDate = "d/m/Y"; //Formato por defecto
}else {
this.clientFormatDate = clientFormatDate;
}
logger.debug("En UserVO queda: " + this.clientFormatDate);
String _clientDateFormat = this.clientFormatDate.replace("d", "dd");
_clientDateFormat = _clientDateFormat.replace("m", "MM");
_clientDateFormat = _clientDateFormat.replace("Y", "yyyy");
logger.debug("En UserVO el converter: " + _clientDateFormat);
//Seteo del conversor por defecto
converterToString = new UserStringConverter(_clientDateFormat);
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getClaveUsuarioCaptura() {
return claveUsuarioCaptura;
}
public void setClaveUsuarioCaptura(String claveUsuarioCaptura) {
this.claveUsuarioCaptura = claveUsuarioCaptura;
}
public String getCdUnieco() {
return cdUnieco;
}
public void setCdUnieco(String cdUnieco) {
this.cdUnieco = cdUnieco;
}
@Override
public String toString()
{
return Utils.join(
"\n*********************"
,"\n****** USUARIO ******"
,"\n*** cdusuari = " , this.user
,"\n*** cdsisrol = " , (this.rolActivo == null ? null : this.rolActivo.getClave())
,"\n*** name = " , this.name
,"\n*** cdunieco = " , this.cdUnieco
,"\n*** elementoId = " , (this.empresa == null ? null : this.empresa.getElementoId())
,"\n*********************"
);
}
} | 9,051 | 0.642029 | 0.638272 | 416 | 20.759615 | 20.257711 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.675481 | false | false | 13 |
de67944067c9901a133e87297a6f315e9a82905a | 3,753,801,453,892 | 917ce448d6e810ed9f4494cfe314cb44d81b0e0e | /school/src/grade/grade/GradeServiceImpl.java | 9196955dbf9cfc2df7cbf2127999e90ee495926b | [] | no_license | shg9094/school | https://github.com/shg9094/school | ef8b551a153281a3d9b66ad09cad4ca5f36fc120 | 7cc520490b8b7e37e02f7d4255209262b315118e | refs/heads/master | 2021-01-10T03:51:12.248000 | 2016-03-17T07:57:02 | 2016-03-17T07:57:13 | 54,099,101 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package grade.grade;
import java.util.ArrayList;
import java.util.Vector;
public class GradeServiceImpl implements GradeService {
//멤버 필드 속성 모아둔곳
ArrayList<GradeBean> gradeList;
public GradeServiceImpl() {
// TODO Auto-generated constructor stub초기화는 메서드가 한다 (생성자)
gradeList = new ArrayList<GradeBean>();// 초기화
}
//멤버 메서드 에어리어 메서드 모아둔곳
@Override
public void input(GradeBean grade) {
// 성적표 등록
gradeList.add(new GradeBean("김구",2,100,100,100,100));
gradeList.add(new GradeBean("강감찬",3,90,90,90,90));
gradeList.add(new GradeBean("유관순",4,80,80,80,80));
gradeList.add(new GradeBean("김구",5,70,70,70,70));
gradeList.add(grade);
}
@Override
public ArrayList<GradeBean> getList() {
// 성적표 리스트
return gradeList;
}
@Override
public GradeBean getGradeByHak(int hak) {
// 성적표 조회 (학번)
GradeBean tempGrade = new GradeBean();
for (int i = 0; i < gradeList.size(); i++) {
//배열 arr[i] = 벡터 gradeList.get(i)
int searchHak = gradeList.get(i).getHak();
if (hak == searchHak) {
tempGrade = gradeList.get(i);
break;
}
}
return tempGrade;
}
@Override
public ArrayList<GradeBean> getGradeByName(String name) {
// 성적표 조회 (이름)
ArrayList<GradeBean> tempList = new ArrayList<GradeBean>();
for (int i = 0; i < gradeList.size(); i++) {
if (name.equals(gradeList.get(i).getName())) {
tempList.add(gradeList.get(i));
}
}
return tempList;
}
@Override
public int getCount() {
return gradeList.size();
// 카운트 조회
}
@Override
public void getCountByName() {
// 이름조회시 카운트 조회
}
@Override
public String update(GradeBean grade) {
// 성적표 수정
String result = "수정하려는 학번이 존재하지 않음";
GradeBean searchedGrade = getGradeByHak(grade.getHak());
searchedGrade.setJava(grade.getJava());
searchedGrade.setSql(grade.getSql());
searchedGrade.setJsp(grade.getJsp());
searchedGrade.setSpring(grade.getSpring());
/*
this.delete(grade.getHak());
this.input(grade);
*/
return "수정성공";
}
@Override
public String delete(int hak) {
// 성적표 삭제
String temp = "";
return temp;
}
}
| UTF-8 | Java | 2,481 | java | GradeServiceImpl.java | Java | [] | null | [] | package grade.grade;
import java.util.ArrayList;
import java.util.Vector;
public class GradeServiceImpl implements GradeService {
//멤버 필드 속성 모아둔곳
ArrayList<GradeBean> gradeList;
public GradeServiceImpl() {
// TODO Auto-generated constructor stub초기화는 메서드가 한다 (생성자)
gradeList = new ArrayList<GradeBean>();// 초기화
}
//멤버 메서드 에어리어 메서드 모아둔곳
@Override
public void input(GradeBean grade) {
// 성적표 등록
gradeList.add(new GradeBean("김구",2,100,100,100,100));
gradeList.add(new GradeBean("강감찬",3,90,90,90,90));
gradeList.add(new GradeBean("유관순",4,80,80,80,80));
gradeList.add(new GradeBean("김구",5,70,70,70,70));
gradeList.add(grade);
}
@Override
public ArrayList<GradeBean> getList() {
// 성적표 리스트
return gradeList;
}
@Override
public GradeBean getGradeByHak(int hak) {
// 성적표 조회 (학번)
GradeBean tempGrade = new GradeBean();
for (int i = 0; i < gradeList.size(); i++) {
//배열 arr[i] = 벡터 gradeList.get(i)
int searchHak = gradeList.get(i).getHak();
if (hak == searchHak) {
tempGrade = gradeList.get(i);
break;
}
}
return tempGrade;
}
@Override
public ArrayList<GradeBean> getGradeByName(String name) {
// 성적표 조회 (이름)
ArrayList<GradeBean> tempList = new ArrayList<GradeBean>();
for (int i = 0; i < gradeList.size(); i++) {
if (name.equals(gradeList.get(i).getName())) {
tempList.add(gradeList.get(i));
}
}
return tempList;
}
@Override
public int getCount() {
return gradeList.size();
// 카운트 조회
}
@Override
public void getCountByName() {
// 이름조회시 카운트 조회
}
@Override
public String update(GradeBean grade) {
// 성적표 수정
String result = "수정하려는 학번이 존재하지 않음";
GradeBean searchedGrade = getGradeByHak(grade.getHak());
searchedGrade.setJava(grade.getJava());
searchedGrade.setSql(grade.getSql());
searchedGrade.setJsp(grade.getJsp());
searchedGrade.setSpring(grade.getSpring());
/*
this.delete(grade.getHak());
this.input(grade);
*/
return "수정성공";
}
@Override
public String delete(int hak) {
// 성적표 삭제
String temp = "";
return temp;
}
}
| 2,481 | 0.617107 | 0.598298 | 109 | 18.486238 | 18.356617 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.155963 | false | false | 13 |
4f1a64a044409991b1a2e8b3ef8fca83d65083a5 | 20,839,181,359,253 | 6b8c1f669eadf9327bbda3208e895162de7895c3 | /src/abscon/instance/intension/arithmetic/PowEvaluator.java | 8b69b6baf8cb0873c145229e76f9b973a178c23c | [] | no_license | tzxb018/csp-solver | https://github.com/tzxb018/csp-solver | 7e13babd657b35e893fc7ff2f0af1ea0e90dd99d | c54152428046bff907dd6f81dae75f1a5debe428 | refs/heads/master | 2021-07-15T23:06:10.163000 | 2021-06-24T16:06:47 | 2021-06-24T16:06:47 | 239,838,519 | 2 | 0 | null | false | 2020-04-28T17:00:50 | 2020-02-11T18:49:30 | 2020-04-11T17:01:28 | 2020-04-28T17:00:50 | 239,961 | 2 | 0 | 0 | Java | false | false | package abscon.instance.intension.arithmetic;
public class PowEvaluator extends Arity2ArithmeticEvaluator {
public void evaluate() {
top--;
stack[top] = (long) Math.pow(stack[top+1], stack[top]);
}
} | UTF-8 | Java | 206 | java | PowEvaluator.java | Java | [] | null | [] | package abscon.instance.intension.arithmetic;
public class PowEvaluator extends Arity2ArithmeticEvaluator {
public void evaluate() {
top--;
stack[top] = (long) Math.pow(stack[top+1], stack[top]);
}
} | 206 | 0.737864 | 0.728155 | 8 | 24.875 | 24.338434 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.25 | false | false | 13 |
991dba9fd698ce9747b37b9fcb2a9fa0611b3cb8 | 2,894,807,998,042 | 1e0fca7ee0a0ea1190da2fbbeba65747f0c75021 | /app/src/main/java/com/example/jdagnogo/alertlebonsoinappart/models/NewSearchView.java | d1a40e4463b22dc46eddf70019cac1f1e754e0af | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | jdagnogo/Alerte-leboncoin-appart | https://github.com/jdagnogo/Alerte-leboncoin-appart | 03ee2802253fcea00523fca17d8358c7770b0301 | 49d0f530f8a910b6f721abf3f1da720caa9d052a | refs/heads/master | 2021-01-20T03:03:45.841000 | 2017-09-08T14:31:19 | 2017-09-08T14:31:19 | 89,488,518 | 11 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.jdagnogo.alertlebonsoinappart.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.example.jdagnogo.alertlebonsoinappart.enums.City;
import com.example.jdagnogo.alertlebonsoinappart.enums.Meuble;
import com.example.jdagnogo.alertlebonsoinappart.enums.Type;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.NbRoomSwipeItem;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.RentSwipeItem;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.SurfaceSwipeItem;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jeff on 02/05/2017.
*/
public class NewSearchView implements Parcelable{
List<City> cities;
Type type;
Meuble meuble;
RentSwipeItem rent;
NbRoomSwipeItem nbRoom;
SurfaceSwipeItem surface;
String query;
private Search search;
public NewSearchView() {
this.rent = new RentSwipeItem();
this.cities = new ArrayList<>();
this.nbRoom = new NbRoomSwipeItem();
this.surface = new SurfaceSwipeItem();
}
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Meuble getMeuble() {
return meuble;
}
public void setMeuble(Meuble meuble) {
this.meuble = meuble;
}
public RentSwipeItem getRent() {
return rent;
}
public void setRent(RentSwipeItem rent) {
this.rent = rent;
}
public NbRoomSwipeItem getNbRoom() {
return nbRoom;
}
public void setNbRoom(NbRoomSwipeItem nbRoom) {
this.nbRoom = nbRoom;
}
public SurfaceSwipeItem getSurface() {
return surface;
}
public void setSurface(SurfaceSwipeItem surface) {
this.surface = surface;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(this.cities);
dest.writeInt(this.type == null ? -1 : this.type.ordinal());
dest.writeInt(this.meuble == null ? -1 : this.meuble.ordinal());
dest.writeParcelable(this.rent, flags);
dest.writeParcelable(this.nbRoom, flags);
dest.writeParcelable(this.surface, flags);
dest.writeString(this.query);
}
protected NewSearchView(Parcel in) {
this.cities = new ArrayList<City>();
in.readList(this.cities, City.class.getClassLoader());
int tmpType = in.readInt();
this.type = tmpType == -1 ? null : Type.values()[tmpType];
int tmpMeuble = in.readInt();
this.meuble = tmpMeuble == -1 ? null : Meuble.values()[tmpMeuble];
this.rent = in.readParcelable(RentSwipeItem.class.getClassLoader());
this.nbRoom = in.readParcelable(NbRoomSwipeItem.class.getClassLoader());
this.surface = in.readParcelable(SurfaceSwipeItem.class.getClassLoader());
this.query = in.readString();
}
public static final Creator<NewSearchView> CREATOR = new Creator<NewSearchView>() {
@Override
public NewSearchView createFromParcel(Parcel source) {
return new NewSearchView(source);
}
@Override
public NewSearchView[] newArray(int size) {
return new NewSearchView[size];
}
};
}
| UTF-8 | Java | 3,644 | java | NewSearchView.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Jeff on 02/05/2017.\n */\n\npublic class NewSearchView im",
"end": 624,
"score": 0.9994552731513977,
"start": 620,
"tag": "NAME",
"value": "Jeff"
}
] | null | [] | package com.example.jdagnogo.alertlebonsoinappart.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.example.jdagnogo.alertlebonsoinappart.enums.City;
import com.example.jdagnogo.alertlebonsoinappart.enums.Meuble;
import com.example.jdagnogo.alertlebonsoinappart.enums.Type;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.NbRoomSwipeItem;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.RentSwipeItem;
import com.example.jdagnogo.alertlebonsoinappart.models.swipeItem.SurfaceSwipeItem;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jeff on 02/05/2017.
*/
public class NewSearchView implements Parcelable{
List<City> cities;
Type type;
Meuble meuble;
RentSwipeItem rent;
NbRoomSwipeItem nbRoom;
SurfaceSwipeItem surface;
String query;
private Search search;
public NewSearchView() {
this.rent = new RentSwipeItem();
this.cities = new ArrayList<>();
this.nbRoom = new NbRoomSwipeItem();
this.surface = new SurfaceSwipeItem();
}
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public Meuble getMeuble() {
return meuble;
}
public void setMeuble(Meuble meuble) {
this.meuble = meuble;
}
public RentSwipeItem getRent() {
return rent;
}
public void setRent(RentSwipeItem rent) {
this.rent = rent;
}
public NbRoomSwipeItem getNbRoom() {
return nbRoom;
}
public void setNbRoom(NbRoomSwipeItem nbRoom) {
this.nbRoom = nbRoom;
}
public SurfaceSwipeItem getSurface() {
return surface;
}
public void setSurface(SurfaceSwipeItem surface) {
this.surface = surface;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(this.cities);
dest.writeInt(this.type == null ? -1 : this.type.ordinal());
dest.writeInt(this.meuble == null ? -1 : this.meuble.ordinal());
dest.writeParcelable(this.rent, flags);
dest.writeParcelable(this.nbRoom, flags);
dest.writeParcelable(this.surface, flags);
dest.writeString(this.query);
}
protected NewSearchView(Parcel in) {
this.cities = new ArrayList<City>();
in.readList(this.cities, City.class.getClassLoader());
int tmpType = in.readInt();
this.type = tmpType == -1 ? null : Type.values()[tmpType];
int tmpMeuble = in.readInt();
this.meuble = tmpMeuble == -1 ? null : Meuble.values()[tmpMeuble];
this.rent = in.readParcelable(RentSwipeItem.class.getClassLoader());
this.nbRoom = in.readParcelable(NbRoomSwipeItem.class.getClassLoader());
this.surface = in.readParcelable(SurfaceSwipeItem.class.getClassLoader());
this.query = in.readString();
}
public static final Creator<NewSearchView> CREATOR = new Creator<NewSearchView>() {
@Override
public NewSearchView createFromParcel(Parcel source) {
return new NewSearchView(source);
}
@Override
public NewSearchView[] newArray(int size) {
return new NewSearchView[size];
}
};
}
| 3,644 | 0.653677 | 0.65011 | 133 | 26.398497 | 23.753098 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 13 |
dc64667225af46f17483c82b1dcb1373c6f1e963 | 23,776,938,983,003 | b860c17949574d3400cf9a5587df436136b4a746 | /src/com/taarangana/collegefestapp/fragments/DJNightFragment.java | 46eec225a4d8e3ec5c62b09b2dd746b3f03220b5 | [] | no_license | mahimapulastya/taarangana-festApp | https://github.com/mahimapulastya/taarangana-festApp | 6aa8e32e08540016ec417e4e93faa67152f7d709 | da8e503d3e125e3f88f46b3efde36289b11b551c | refs/heads/master | 2020-03-20T02:22:48.196000 | 2018-10-29T20:47:08 | 2018-10-29T20:47:08 | 137,110,804 | 0 | 1 | null | false | 2018-10-29T20:47:09 | 2018-06-12T18:14:26 | 2018-10-29T20:40:59 | 2018-10-29T20:47:09 | 4,180 | 0 | 1 | 0 | Java | false | null | package com.taarangana.collegefestapp.fragments;
import com.taarangana.collegefestapp.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class DJNightFragment extends Fragment
{
private TextView description,name;
private ImageView image;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View star = inflater.inflate(R.layout.activity_star, container, false);
description= (TextView) star.findViewById(R.id.eventDescription_tv);
name = (TextView) star.findViewById(R.id.eventName_tv);
image = (ImageView) star.findViewById(R.id.eventImage_iv);
name.setText("DJ Night");
description.setText("We don't really care if you are the baraati dancer or a trained ballet dancer. Taarangana'15 invites you all to join us on our DJ night."+
" The music is going to be loud and you have full licence to go crazy."+
" So cancel all your prior plans and make way for the DJ night hosted by us girls. Do come!"+
"\n\nDate: 30th January 2015\nTime: 6:00-8:00PM\nVenue: Ground Main Stage");
image.setImageResource(R.drawable.dj);
return star;
}
}
| UTF-8 | Java | 1,389 | java | DJNightFragment.java | Java | [] | null | [] | package com.taarangana.collegefestapp.fragments;
import com.taarangana.collegefestapp.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
public class DJNightFragment extends Fragment
{
private TextView description,name;
private ImageView image;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View star = inflater.inflate(R.layout.activity_star, container, false);
description= (TextView) star.findViewById(R.id.eventDescription_tv);
name = (TextView) star.findViewById(R.id.eventName_tv);
image = (ImageView) star.findViewById(R.id.eventImage_iv);
name.setText("DJ Night");
description.setText("We don't really care if you are the baraati dancer or a trained ballet dancer. Taarangana'15 invites you all to join us on our DJ night."+
" The music is going to be loud and you have full licence to go crazy."+
" So cancel all your prior plans and make way for the DJ night hosted by us girls. Do come!"+
"\n\nDate: 30th January 2015\nTime: 6:00-8:00PM\nVenue: Ground Main Stage");
image.setImageResource(R.drawable.dj);
return star;
}
}
| 1,389 | 0.75018 | 0.739381 | 36 | 36.583332 | 33.741974 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.75 | false | false | 13 |
e67f5146c264e3e3cc00bb2dc769ddaa0e94626d | 27,350,351,773,352 | 95e380c49b143fb7271254ec2cf7b0f2ba47e616 | /infrastructure/ssz/src/main/java/tech/pegasys/teku/infrastructure/ssz/collections/impl/SszUInt64ListImpl.java | 540ac00e5edb7278e528e5f45c3865e70183e318 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | Nashatyrev/artemis | https://github.com/Nashatyrev/artemis | a34515760b8e64c28ca07b7a87b0c3729299e0fc | de2b2801c89ef5abf983d6bf37867c37fc47121f | refs/heads/master | 2022-09-17T01:28:08.612000 | 2022-06-06T14:19:07 | 2022-06-06T14:19:07 | 232,340,075 | 1 | 0 | Apache-2.0 | true | 2021-04-15T15:49:45 | 2020-01-07T14:18:44 | 2020-10-22T22:50:26 | 2021-04-15T15:49:44 | 123,612 | 1 | 0 | 0 | Java | false | false | /*
* Copyright 2021 ConsenSys AG.
*
* 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 tech.pegasys.teku.infrastructure.ssz.collections.impl;
import tech.pegasys.teku.infrastructure.ssz.cache.IntCache;
import tech.pegasys.teku.infrastructure.ssz.collections.SszMutableUInt64List;
import tech.pegasys.teku.infrastructure.ssz.collections.SszUInt64List;
import tech.pegasys.teku.infrastructure.ssz.primitive.SszUInt64;
import tech.pegasys.teku.infrastructure.ssz.schema.SszListSchema;
import tech.pegasys.teku.infrastructure.ssz.schema.collections.SszUInt64ListSchema;
import tech.pegasys.teku.infrastructure.ssz.tree.TreeNode;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
public class SszUInt64ListImpl extends SszPrimitiveListImpl<UInt64, SszUInt64>
implements SszUInt64List {
public SszUInt64ListImpl(SszUInt64ListSchema<?> schema, TreeNode backingNode) {
super(schema, backingNode);
}
SszUInt64ListImpl(
SszListSchema<SszUInt64, ?> schema, TreeNode backingNode, IntCache<SszUInt64> cache) {
super(schema, backingNode, cache);
}
@Override
public SszMutableUInt64List createWritableCopy() {
return new SszMutableUInt64ListImpl(this);
}
}
| UTF-8 | Java | 1,696 | java | SszUInt64ListImpl.java | Java | [] | null | [] | /*
* Copyright 2021 ConsenSys AG.
*
* 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 tech.pegasys.teku.infrastructure.ssz.collections.impl;
import tech.pegasys.teku.infrastructure.ssz.cache.IntCache;
import tech.pegasys.teku.infrastructure.ssz.collections.SszMutableUInt64List;
import tech.pegasys.teku.infrastructure.ssz.collections.SszUInt64List;
import tech.pegasys.teku.infrastructure.ssz.primitive.SszUInt64;
import tech.pegasys.teku.infrastructure.ssz.schema.SszListSchema;
import tech.pegasys.teku.infrastructure.ssz.schema.collections.SszUInt64ListSchema;
import tech.pegasys.teku.infrastructure.ssz.tree.TreeNode;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
public class SszUInt64ListImpl extends SszPrimitiveListImpl<UInt64, SszUInt64>
implements SszUInt64List {
public SszUInt64ListImpl(SszUInt64ListSchema<?> schema, TreeNode backingNode) {
super(schema, backingNode);
}
SszUInt64ListImpl(
SszListSchema<SszUInt64, ?> schema, TreeNode backingNode, IntCache<SszUInt64> cache) {
super(schema, backingNode, cache);
}
@Override
public SszMutableUInt64List createWritableCopy() {
return new SszMutableUInt64ListImpl(this);
}
}
| 1,696 | 0.793632 | 0.770047 | 41 | 40.365852 | 37.070637 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.609756 | false | false | 13 |
81ca944d2fbdebad1fdbd086b3aeec790096b104 | 32,573,032,008,393 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/9/9_db713726472adcd138fc55bddfab2e69b0efcb7a/DebugOptionsTestCase/9_db713726472adcd138fc55bddfab2e69b0efcb7a_DebugOptionsTestCase_t.java | 45ea36664a40dd8cc4decf850359d1d9d065a0cb | [] | 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 | /*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.osgi.tests.debugoptions;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.tests.harness.CoreTest;
import org.eclipse.osgi.framework.debug.FrameworkDebugTraceEntry;
import org.eclipse.osgi.service.debug.*;
import org.eclipse.osgi.tests.OSGiTestsActivator;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class DebugOptionsTestCase extends CoreTest {
public static Test suite() {
return new TestSuite(DebugOptionsTestCase.class);
}
DebugOptions debugOptions;
ServiceReference ref;
Dictionary props = null;
TestDebugOptionsListener listener = null;
ServiceRegistration reg = null;
private final static String TRACE_ELEMENT_DELIMITER = "|"; //$NON-NLS-1$ // this value needs to match EclipseDebugTrace#TRACE_ELEMENT_DELIMITER
private final static String TRACE_ELEMENT_DELIMITER_ENCODED = "|"; //$NON-NLS-1$ // this value needs to match EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED
private final static SimpleDateFormat TRACE_FILE_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //$NON-NLS-1$
private final static String LINE_SEPARATOR;
static {
String s = System.getProperty("line.separator"); //$NON-NLS-1$
LINE_SEPARATOR = s == null ? "\n" : s; //$NON-NLS-1$
}
private final static String TAB_CHARACTER = "\t"; //$NON-NLS-1$
protected void setUp() throws Exception {
ref = OSGiTestsActivator.getContext().getServiceReference(DebugOptions.class.getName());
assertNotNull("DebugOptions service is not available", ref); //$NON-NLS-1$
debugOptions = (DebugOptions) OSGiTestsActivator.getContext().getService(ref);
assertNotNull("DebugOptions service is not available", debugOptions); //$NON-NLS-1$
props = new Hashtable();
props.put(DebugOptions.LISTENER_SYMBOLICNAME, getName());
listener = new TestDebugOptionsListener();
reg = OSGiTestsActivator.getContext().registerService(DebugOptionsListener.class.getName(), listener, props);
}
protected void tearDown() throws Exception {
if (debugOptions == null)
return;
debugOptions.setDebugEnabled(false);
debugOptions = null;
OSGiTestsActivator.getContext().ungetService(ref);
if (reg != null)
reg.unregister();
}
public void testRegistration01() {
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
}
/**
* Test that a new {@link FrameworkDebugTraceEntry} object created without a trace class
* has 'org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase' as the class name and
* 'testTracingEntry01' as the method name that it determined as the caller of it.
*
* This test mimics the tracing framework to ensure that the correct class name and method name
* are returned and written to the trace file.
*/
public void testTracingEntry01() {
String bundleName = OSGiTestsActivator.getContext().getBundle().getSymbolicName();
String optionPath = "/debug"; //$NON-NLS-1$
String message = "Test message"; //$NON-NLS-1$
FrameworkDebugTraceEntry traceEntry = new FrameworkDebugTraceEntry(bundleName, optionPath, message, null);
String correctClassName = "org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase"; //$NON-NLS-1$
String correctMethodName = "testTracingEntry01"; //$NON-NLS-1$
assertEquals("The class calling the trace API does not match the expected value.", correctClassName, traceEntry.getClassName()); //$NON-NLS-1$
assertEquals("The method calling the trace API does not match the expected value.", correctMethodName, traceEntry.getMethodName()); //$NON-NLS-1$
}
/**
* Test that a new {@link FrameworkDebugTraceEntry} object created with a trace class
* of 'org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase' has the correct class name and
* method name of the caller.
*
* This test mimics the tracing framework to ensure that the correct class name and method name
* are returned and written to the trace file.
*/
public void testTracingEntry02() {
String correctClassName = Runner1.class.getName();
String correctMethodName = "run"; //$NON-NLS-1$
FrameworkDebugTraceEntry traceEntry = new Runner1().run();
assertEquals("The class calling the trace API does not match the expected value.", correctClassName, traceEntry.getClassName()); //$NON-NLS-1$
assertEquals("The method calling the trace API does not match the expected value.", correctMethodName, traceEntry.getMethodName()); //$NON-NLS-1$
}
static class Runner1 {
public FrameworkDebugTraceEntry run() {
return new Runner2().run();
}
}
static class Runner2 {
public FrameworkDebugTraceEntry run() {
String bundleName = OSGiTestsActivator.getContext().getBundle().getSymbolicName();
String optionPath = "/debug"; //$NON-NLS-1$
String message = "Test message"; //$NON-NLS-1$
String tracingClass = this.getClass().getName();
return new FrameworkDebugTraceEntry(bundleName, optionPath, message, tracingClass);
}
}
public void testDyanmicEnablement01() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testDyanmicEnablement02() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "false"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNotNull("Should find bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testDyanmicEnablement03() {
listener.clear();
if (debugOptions.isDebugEnabled())
return; // cannot test
TestDebugOptionsListener anotherListener = new TestDebugOptionsListener();
Dictionary anotherProps = new Hashtable();
anotherProps.put(DebugOptions.LISTENER_SYMBOLICNAME, "anotherListener"); //$NON-NLS-1$
ServiceRegistration anotherReg = OSGiTestsActivator.getContext().registerService(DebugOptionsListener.class.getName(), anotherListener, anotherProps);
assertTrue("Not called", anotherListener.gotCalled()); //$NON-NLS-1$
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertFalse("Should not call wrong listener", anotherListener.gotCalled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
debugOptions.setOption("anotherListener/test", "blah"); //$NON-NLS-1$ //$NON-NLS-2$
assertFalse("Listener should not have been called", listener.gotCalled()); //$NON-NLS-1$
assertTrue("Another listener should have been called", anotherListener.gotCalled()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
anotherProps.put(DebugOptions.LISTENER_SYMBOLICNAME, getName());
anotherReg.setProperties(anotherProps);
debugOptions.setOption(getName() + "/debug", "false"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertTrue("Another listener did not get called", anotherListener.gotCalled()); //$NON-NLS-1$
anotherReg.unregister();
}
public void testDyanmicEnablement04() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
listener.clear();
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
checkValues.put(getName() + "/debug", null); //$NON-NLS-1$
listener.setCheckValues(checkValues);
debugOptions.setDebugEnabled(false);
assertFalse("Debug is enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testSetOptionsWhenDisabled() {
// enable tracing initially.
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/disableCheck";
// set its value to 'ok'
debugOptions.setOption(testKey, "ok");
// make sure the right value is added
String actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The correct option value was not returned from the debug option: " + testKey, "ok", actualValue);
// disable tracing
debugOptions.setDebugEnabled(false);
// check for the value
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The 'default' value supplied was not returned when tracing is disabled.", "not ok", actualValue);
// try setting the value to "ok" (this should be a no-op and return the 'default' value)
debugOptions.setOption(testKey, "ok");
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The 'default' value supplied was not returned when tracing is disabled.", "not ok", actualValue);
// remove the option and check for the value (it should still exist after re-enabling tracing)
debugOptions.removeOption(testKey);
// re-enable tracing
debugOptions.setDebugEnabled(true);
// check that the value is still the initial "ok"
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The value after re-enabling tracing is invalid.", "ok", actualValue);
}
public void testStringValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/stringValue";
// set its value to 'test'
debugOptions.setOption(testKey, "test");
// check to make sure the value returned is correct
String actualValue = debugOptions.getOption(testKey, "default");
assertEquals("The correct option value was not returned from the debug option: " + testKey, "test", actualValue);
// remove the option and check for the value (it should not exist so the default value should be returned)
debugOptions.removeOption(testKey);
actualValue = debugOptions.getOption(testKey, "default");
assertEquals("The 'default' value supplied was not returned when the key does not exist in the DebugOptions.", "default", actualValue);
}
public void testIntegerValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/intValue";
// set its value to 42.
debugOptions.setOption(testKey, "42");
// check to make sure the value returned is correct
int actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The correct option value was not returned from the debug option: " + testKey, 42, actualValue);
// set the value of this key so that a NumberFormatException will occur
debugOptions.setOption(testKey, "test");
actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The 'default' value supplied was not returned when a NumberFormatException occurs.", 0, actualValue);
// remove the option and check for the value (it should not exist so the default value should be returned)
debugOptions.removeOption(testKey);
actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The 'default' value supplied was not returned when the key does not exist in the DebugOptions.", 0, actualValue);
}
public void testBooleanValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
String testKey = getName() + "/debug";
boolean testValue = debugOptions.getBooleanOption(testKey, false);
assertFalse(testKey + " is true", testValue);
debugOptions.setOption(testKey, "false");
testValue = debugOptions.getBooleanOption(testKey, true);
assertFalse(testKey + " is true", testValue);
debugOptions.setOption(testKey, "true");
testValue = debugOptions.getBooleanOption(testKey, false);
assertTrue(testKey + " is false", testValue);
testValue = debugOptions.getBooleanOption(testKey, true);
assertTrue(testKey + " is false", testValue);
}
private TestDebugTrace createDebugTrace(final File traceFile) {
TestDebugTrace debugTrace = null;
if (!debugOptions.isDebugEnabled()) {
/** Setup the DebugOptions */
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
}
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
debugOptions.setFile(traceFile);
DebugTrace wrapped = debugOptions.newDebugTrace(getName(), TestDebugTrace.class);
debugTrace = new TestDebugTrace(wrapped);
return debugTrace;
}
/**
* test DebugTrace.trace(option, message);
*/
public void testTraceFile01() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.trace("/debug", "testing 1"); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/notset", "testing 2"); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/debug", "testing 3"); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile01", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile01", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.trace(option, message, Throwable)
*/
public void testTraceFile02() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
final String exceptionMessage1 = "An error 1"; //$NON-NLS-1$
final String exceptionMessage2 = "An error 2"; //$NON-NLS-1$
final String exceptionMessage3 = "An error 3"; //$NON-NLS-1$
try {
debugTrace.trace("/debug", "testing 1", new Exception(exceptionMessage1)); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/notset", "testing 2", new Exception(exceptionMessage2)); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/debug", "testing 3", new Exception(exceptionMessage3)); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message, Throwable)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
final StringBuffer expectedThrowableText1 = new StringBuffer("java.lang.Exception: "); //$NON-NLS-1$
expectedThrowableText1.append(exceptionMessage1);
expectedThrowableText1.append(DebugOptionsTestCase.LINE_SEPARATOR);
expectedThrowableText1.append(DebugOptionsTestCase.TAB_CHARACTER);
expectedThrowableText1.append("at org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase.testTraceFile02(DebugOptionsTestCase.java:"); //$NON-NLS-1$
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile02", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNotNull("throwable text should not be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
if (!traceOutput[0].getThrowableText().startsWith(expectedThrowableText1.toString())) {
final StringBuffer errorMessage = new StringBuffer("The expected throwable text does not start with the actual throwable text."); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Expected"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(expectedThrowableText1.toString());
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Actual"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(traceOutput[0].getThrowableText());
fail(errorMessage.toString());
}
assertNotNull("throwable should not be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
final StringBuffer expectedThrowableText2 = new StringBuffer("java.lang.Exception: "); //$NON-NLS-1$
expectedThrowableText2.append(exceptionMessage3);
expectedThrowableText2.append(DebugOptionsTestCase.LINE_SEPARATOR);
expectedThrowableText2.append(DebugOptionsTestCase.TAB_CHARACTER);
expectedThrowableText2.append("at org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase.testTraceFile02(DebugOptionsTestCase.java:"); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile02", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNotNull("throwable text should not be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
if (!traceOutput[1].getThrowableText().startsWith(expectedThrowableText2.toString())) {
final StringBuffer errorMessage = new StringBuffer("The expected throwable text does not start with the actual throwable text."); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Expected"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(expectedThrowableText2.toString());
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Actual"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(traceOutput[1].getThrowableText());
fail(errorMessage.toString());
}
assertNotNull("throwable should not be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceDumpStack(option)
*/
public void testTraceFile03() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceDumpStack("/debug"); //$NON-NLS-1$
debugTrace.traceDumpStack("/notset"); //$NON-NLS-1$
debugTrace.traceDumpStack("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceDumpStack(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile03", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Trace message is not a stack dump", traceOutput[0].getMessage().startsWith("Thread Stack dump: ")); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile03", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Trace message is not a stack dump", traceOutput[1].getMessage().startsWith("Thread Stack dump: ")); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option)
*/
public void testTraceFile04() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug"); //$NON-NLS-1$
debugTrace.traceEntry("/notset"); //$NON-NLS-1$
debugTrace.traceEntry("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile04", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with no parameters", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile04", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with no parameters", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option, methodArgument)
*/
public void testTraceFile05() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug", new String("arg1")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceEntry("/notset", new String("arg2")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceEntry("/debug", new String("arg3")); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option, methodArgument)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile05", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg1)", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile05", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg3)", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option, methodArgument[])
*/
public void testTraceFile06() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug", new String[] {"arg1", "arg2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
debugTrace.traceEntry("/notset", new String[] {"arg3", "arg4"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
debugTrace.traceEntry("/debug", new String[] {"arg5", "arg6"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option, methodArgument[])' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile06", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg1 arg2)", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile06", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg5 arg6)", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceExit(option)
*/
public void testTraceFile07() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceExit("/debug"); //$NON-NLS-1$
debugTrace.traceExit("/notset"); //$NON-NLS-1$
debugTrace.traceExit("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceExit(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile07", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with a void return", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile07", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with a void return", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceExit(option, result)
*/
public void testTraceFile08() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceExit("/debug", new String("returnValue1")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceExit("/notset", new String("returnValue2")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceExit("/debug", new String("returnValue3")); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceExit(option, result)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile08", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with result: returnValue1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile08", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with result: returnValue3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* tests DebugTrace.trace(option, message) where the 'option' and 'message contain a '|' character (the delimiter).
*/
public void testTraceFile09() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
debugOptions.setOption(getName() + "/debug|path", "true");
TraceEntry[] traceOutput = null;
try {
debugTrace.trace("/debug|path", "A message with a | character.");
debugTrace.trace("/debug|path", "|A message with | multiple || characters.|");
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of entries", 2, traceOutput.length);
String optionPath = decodeString(traceOutput[0].getOptionPath());
String message = decodeString(traceOutput[0].getMessage());
assertEquals("option-path value is incorrect", "/debug|path", optionPath); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "A message with a | character.", message); //$NON-NLS-1$ //$NON-NLS-2$
optionPath = decodeString(traceOutput[1].getOptionPath());
message = decodeString(traceOutput[1].getMessage());
assertEquals("option-path value is incorrect", "/debug|path", optionPath); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "|A message with | multiple || characters.|", message); //$NON-NLS-1$ //$NON-NLS-2$
// delete the trace file
traceFile.delete();
}
private static String decodeString(final String inputString) {
if (inputString == null || inputString.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED) < 0)
return inputString;
final StringBuffer tempBuffer = new StringBuffer(inputString);
int currentIndex = tempBuffer.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED);
while (currentIndex >= 0) {
tempBuffer.replace(currentIndex, currentIndex + TRACE_ELEMENT_DELIMITER_ENCODED.length(), TRACE_ELEMENT_DELIMITER);
currentIndex = tempBuffer.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED);
}
return tempBuffer.toString();
}
private TraceEntry[] readTraceFile(File traceFile) throws InvalidTraceEntry {
Reader traceReader = null;
List traceEntries = new ArrayList();
try {
traceReader = new BufferedReader(new InputStreamReader(new FileInputStream(traceFile), "UTF-8")); //$NON-NLS-1$
TraceEntry entry = null;
while ((entry = this.readMessage(traceReader)) != null) {
traceEntries.add(entry);
}
} catch (IOException ex) {
fail("Failed to read trace file", ex); //$NON-NLS-1$
} finally {
if (traceReader != null) {
try {
traceReader.close();
} catch (Exception ex) {
// do nothing
}
}
}
return (TraceEntry[]) traceEntries.toArray(new TraceEntry[traceEntries.size()]);
}
private TraceEntry readMessage(final Reader traceReader) throws IOException, InvalidTraceEntry {
TraceEntry result = null;
int input = traceReader.read();
while (input != -1) {
char inputChar = (char) input;
if (inputChar == '#') {
while ((inputChar != '\n') && (inputChar != '\r')) {
// do nothing
inputChar = (char) traceReader.read();
}
}
if (inputChar == DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
// first entry - thread name
final String threadName = this.readEntry(traceReader);
if ((threadName == null) || (threadName.length() == 0)) {
throw new InvalidTraceEntry("The thread name in a trace entry is null or empty", threadName); //$NON-NLS-1$
}
// read the next character
final String date = this.readEntry(traceReader);
if ((date == null) || (date.length() == 0)) {
throw new InvalidTraceEntry("The timestamp in a trace entry is null or empty", date); //$NON-NLS-1$
}
long timestamp = 0;
try {
timestamp = DebugOptionsTestCase.TRACE_FILE_DATE_FORMATTER.parse(date).getTime();
} catch (ParseException parseEx) {
throw new InvalidTraceEntry("The date in a trace entry '" + date + "' could not be parsed.", date); //$NON-NLS-1$ //$NON-NLS-2$
}
// third entry - bundle symbolic name
final String symbolicName = this.readEntry(traceReader);
if ((symbolicName == null) || (symbolicName.length() == 0)) {
throw new InvalidTraceEntry("The bundle symbolic name in a trace entry is null or empty", symbolicName); //$NON-NLS-1$
}
// fourth entry - option path
final String optionPath = this.readEntry(traceReader);
if ((optionPath == null) || (optionPath.length() == 0)) {
throw new InvalidTraceEntry("The option-path in a trace entry is null or empty", optionPath); //$NON-NLS-1$
}
// fifth entry - class name
final String className = this.readEntry(traceReader);
if ((className == null) || (className.length() == 0)) {
throw new InvalidTraceEntry("The class name in a trace entry is null or empty", className); //$NON-NLS-1$
}
// sixth entry - method name
final String methodName = this.readEntry(traceReader);
if ((methodName == null) || (methodName.length() == 0)) {
throw new InvalidTraceEntry("The method name in a trace entry is null or empty", methodName); //$NON-NLS-1$
}
// seventh entry - line number
final String lineNumberString = this.readEntry(traceReader);
if ((lineNumberString == null) || (lineNumberString.length() == 0)) {
throw new InvalidTraceEntry("The line number in a trace entry is null or empty", lineNumberString); //$NON-NLS-1$
}
final int lineNumber = Integer.valueOf(lineNumberString).intValue();
// eighth entry - message
final String message = this.readEntry(traceReader);
// read in the next character. if it is \r or \n then the throwable was not supplied
traceReader.mark(1);
inputChar = (char) traceReader.read();
String throwable = null;
if (inputChar != '\n' && inputChar != '\r') {
traceReader.reset();
// ninth entry (optional) - throwable
throwable = this.readEntry(traceReader);
if ((throwable == null) || (throwable.length() == 0)) {
throw new InvalidTraceEntry("The throwable in a trace entry is null or empty", throwable); //$NON-NLS-1$
}
}
// create the entry
result = new TraceEntry(threadName, timestamp, symbolicName, optionPath, className, methodName, lineNumber, message, throwable);
break; // no point in reading any more information since the TraceEntry is created
}
// read the next character
input = traceReader.read();
}
return result;
}
private String readEntry(final Reader traceReader) throws IOException {
char inputChar = (char) traceReader.read();
StringBuffer buffer = new StringBuffer();
while (inputChar != DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
inputChar = (char) traceReader.read();
if (inputChar != DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
buffer.append(inputChar);
}
}
return buffer.toString().trim();
}
static public class TraceEntry {
/** If a bundles symbolic name is not specified then the default value of /debug can be used */
public final static String DEFAULT_OPTION_PATH = "/debug"; //$NON-NLS-1$
/**
* The name of the thread executing the code
*/
private final String threadName;
/**
* The date and time when the trace occurred.
*
*/
private final long timestamp;
/**
* The trace option-path
*/
private final String optionPath;
/**
* The symbolic name of the bundle being traced
*/
private final String bundleSymbolicName;
/**
* The class being traced
*/
private final String className;
/**
* The method being traced
*/
private String methodName = null;
/**
* The line number
*/
private final int lineNumber;
/**
* The trace message
*/
private final String message;
/**
* The trace exception
*/
private final String throwableText;
public TraceEntry(final String traceThreadName, final long traceTimestamp, final String traceBundleName, final String traceOptionPath, final String traceClassName, final String traceMethodName, final int traceLineNumber, final String traceMessage) {
this.threadName = traceThreadName;
this.bundleSymbolicName = traceBundleName;
this.optionPath = traceOptionPath;
this.className = traceClassName;
this.methodName = traceMethodName;
this.lineNumber = traceLineNumber;
this.message = traceMessage;
this.timestamp = traceTimestamp;
this.throwableText = null;
}
public TraceEntry(final String traceThreadName, final long traceTimestamp, final String traceBundleName, final String traceOptionPath, final String traceClassName, final String traceMethodName, final int traceLineNumber, final String traceMessage, final String traceThrowable) {
this.threadName = traceThreadName;
this.bundleSymbolicName = traceBundleName;
this.optionPath = traceOptionPath;
this.className = traceClassName;
this.methodName = traceMethodName;
this.lineNumber = traceLineNumber;
this.message = traceMessage;
this.timestamp = traceTimestamp;
this.throwableText = traceThrowable;
}
public final String getThreadName() {
return threadName;
}
public final long getTimestamp() {
return timestamp;
}
public final String getBundleSymbolicName() {
return bundleSymbolicName;
}
public final String getMessage() {
return message;
}
public final String getThrowableText() {
return throwableText;
}
public final String getClassName() {
return className;
}
public final String getMethodName() {
return methodName;
}
public final String getOptionPath() {
return optionPath;
}
public final int getLineNumber() {
return lineNumber;
}
}
static class InvalidTraceEntry extends Exception {
private static final long serialVersionUID = -63837787081750344L;
public InvalidTraceEntry(String message, String actual) {
super(message);
this.actualValue = actual;
}
public final String getActualValue() {
return this.actualValue;
}
String actualValue;
String expectedValue;
}
static class TestDebugTrace implements DebugTrace {
private final DebugTrace wrapped;
public TestDebugTrace(DebugTrace wrapped) {
this.wrapped = wrapped;
}
public void trace(String option, String message) {
wrapped.trace(option, message);
}
public void trace(String option, String message, Throwable error) {
wrapped.trace(option, message, error);
}
public void traceDumpStack(String option) {
wrapped.traceDumpStack(option);
}
public void traceEntry(String option) {
wrapped.traceEntry(option);
}
public void traceEntry(String option, Object methodArgument) {
wrapped.traceEntry(option, methodArgument);
}
public void traceEntry(String option, Object[] methodArguments) {
wrapped.traceEntry(option, methodArguments);
}
public void traceExit(String option) {
wrapped.traceExit(option);
}
public void traceExit(String option, Object result) {
wrapped.traceExit(option, result);
}
}
class TestDebugOptionsListener implements DebugOptionsListener {
boolean called = false;
String incorrectValue;
Map checkValues;
public void optionsChanged(DebugOptions options) {
called = true;
if (checkValues == null)
return;
for (Iterator entries = checkValues.entrySet().iterator(); entries.hasNext();) {
Map.Entry entry = (Entry) entries.next();
String debugValue = options.getOption((String) entry.getKey());
String error = "Value is incorrect for key: " + entry.getKey() + " " + debugValue; //$NON-NLS-1$//$NON-NLS-2$
if (debugValue == null) {
if (entry.getValue() != null) {
incorrectValue = error;
return;
}
continue;
}
if (!debugValue.equals(entry.getValue())) {
incorrectValue = error;
return;
}
}
}
public boolean gotCalled() {
return called;
}
public void clear() {
called = false;
checkValues = null;
incorrectValue = null;
}
public void setCheckValues(Map checkValues) {
this.checkValues = checkValues;
}
public String getIncorrectValue() {
return incorrectValue;
}
}
}
| UTF-8 | Java | 54,723 | java | 9_db713726472adcd138fc55bddfab2e69b0efcb7a_DebugOptionsTestCase_t.java | Java | [
{
"context": " \t\t// create a new key to add.\n \t\tString testKey = getName() + \"/debug/disableCheck\";\n \t\t// set its value to '",
"end": 11036,
"score": 0.7575178146362305,
"start": 11027,
"tag": "KEY",
"value": "getName()"
},
{
"context": " a new key to add.\n \t\tString test... | null | [] | /*******************************************************************************
* Copyright (c) 2009, 2010 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.osgi.tests.debugoptions;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.tests.harness.CoreTest;
import org.eclipse.osgi.framework.debug.FrameworkDebugTraceEntry;
import org.eclipse.osgi.service.debug.*;
import org.eclipse.osgi.tests.OSGiTestsActivator;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
public class DebugOptionsTestCase extends CoreTest {
public static Test suite() {
return new TestSuite(DebugOptionsTestCase.class);
}
DebugOptions debugOptions;
ServiceReference ref;
Dictionary props = null;
TestDebugOptionsListener listener = null;
ServiceRegistration reg = null;
private final static String TRACE_ELEMENT_DELIMITER = "|"; //$NON-NLS-1$ // this value needs to match EclipseDebugTrace#TRACE_ELEMENT_DELIMITER
private final static String TRACE_ELEMENT_DELIMITER_ENCODED = "|"; //$NON-NLS-1$ // this value needs to match EclipseDebugTrace#TRACE_ELEMENT_DELIMITER_ENCODED
private final static SimpleDateFormat TRACE_FILE_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //$NON-NLS-1$
private final static String LINE_SEPARATOR;
static {
String s = System.getProperty("line.separator"); //$NON-NLS-1$
LINE_SEPARATOR = s == null ? "\n" : s; //$NON-NLS-1$
}
private final static String TAB_CHARACTER = "\t"; //$NON-NLS-1$
protected void setUp() throws Exception {
ref = OSGiTestsActivator.getContext().getServiceReference(DebugOptions.class.getName());
assertNotNull("DebugOptions service is not available", ref); //$NON-NLS-1$
debugOptions = (DebugOptions) OSGiTestsActivator.getContext().getService(ref);
assertNotNull("DebugOptions service is not available", debugOptions); //$NON-NLS-1$
props = new Hashtable();
props.put(DebugOptions.LISTENER_SYMBOLICNAME, getName());
listener = new TestDebugOptionsListener();
reg = OSGiTestsActivator.getContext().registerService(DebugOptionsListener.class.getName(), listener, props);
}
protected void tearDown() throws Exception {
if (debugOptions == null)
return;
debugOptions.setDebugEnabled(false);
debugOptions = null;
OSGiTestsActivator.getContext().ungetService(ref);
if (reg != null)
reg.unregister();
}
public void testRegistration01() {
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
}
/**
* Test that a new {@link FrameworkDebugTraceEntry} object created without a trace class
* has 'org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase' as the class name and
* 'testTracingEntry01' as the method name that it determined as the caller of it.
*
* This test mimics the tracing framework to ensure that the correct class name and method name
* are returned and written to the trace file.
*/
public void testTracingEntry01() {
String bundleName = OSGiTestsActivator.getContext().getBundle().getSymbolicName();
String optionPath = "/debug"; //$NON-NLS-1$
String message = "Test message"; //$NON-NLS-1$
FrameworkDebugTraceEntry traceEntry = new FrameworkDebugTraceEntry(bundleName, optionPath, message, null);
String correctClassName = "org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase"; //$NON-NLS-1$
String correctMethodName = "testTracingEntry01"; //$NON-NLS-1$
assertEquals("The class calling the trace API does not match the expected value.", correctClassName, traceEntry.getClassName()); //$NON-NLS-1$
assertEquals("The method calling the trace API does not match the expected value.", correctMethodName, traceEntry.getMethodName()); //$NON-NLS-1$
}
/**
* Test that a new {@link FrameworkDebugTraceEntry} object created with a trace class
* of 'org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase' has the correct class name and
* method name of the caller.
*
* This test mimics the tracing framework to ensure that the correct class name and method name
* are returned and written to the trace file.
*/
public void testTracingEntry02() {
String correctClassName = Runner1.class.getName();
String correctMethodName = "run"; //$NON-NLS-1$
FrameworkDebugTraceEntry traceEntry = new Runner1().run();
assertEquals("The class calling the trace API does not match the expected value.", correctClassName, traceEntry.getClassName()); //$NON-NLS-1$
assertEquals("The method calling the trace API does not match the expected value.", correctMethodName, traceEntry.getMethodName()); //$NON-NLS-1$
}
static class Runner1 {
public FrameworkDebugTraceEntry run() {
return new Runner2().run();
}
}
static class Runner2 {
public FrameworkDebugTraceEntry run() {
String bundleName = OSGiTestsActivator.getContext().getBundle().getSymbolicName();
String optionPath = "/debug"; //$NON-NLS-1$
String message = "Test message"; //$NON-NLS-1$
String tracingClass = this.getClass().getName();
return new FrameworkDebugTraceEntry(bundleName, optionPath, message, tracingClass);
}
}
public void testDyanmicEnablement01() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testDyanmicEnablement02() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "false"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNotNull("Should find bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testDyanmicEnablement03() {
listener.clear();
if (debugOptions.isDebugEnabled())
return; // cannot test
TestDebugOptionsListener anotherListener = new TestDebugOptionsListener();
Dictionary anotherProps = new Hashtable();
anotherProps.put(DebugOptions.LISTENER_SYMBOLICNAME, "anotherListener"); //$NON-NLS-1$
ServiceRegistration anotherReg = OSGiTestsActivator.getContext().registerService(DebugOptionsListener.class.getName(), anotherListener, anotherProps);
assertTrue("Not called", anotherListener.gotCalled()); //$NON-NLS-1$
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertFalse("Should not call wrong listener", anotherListener.gotCalled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
debugOptions.setOption("anotherListener/test", "blah"); //$NON-NLS-1$ //$NON-NLS-2$
assertFalse("Listener should not have been called", listener.gotCalled()); //$NON-NLS-1$
assertTrue("Another listener should have been called", anotherListener.gotCalled()); //$NON-NLS-1$
listener.clear();
anotherListener.clear();
anotherProps.put(DebugOptions.LISTENER_SYMBOLICNAME, getName());
anotherReg.setProperties(anotherProps);
debugOptions.setOption(getName() + "/debug", "false"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertTrue("Another listener did not get called", anotherListener.gotCalled()); //$NON-NLS-1$
anotherReg.unregister();
}
public void testDyanmicEnablement04() {
if (debugOptions.isDebugEnabled())
return; // cannot test
debugOptions.setDebugEnabled(true);
listener.clear();
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
Map checkValues = new HashMap();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
checkValues.put(getName() + "/debug", null); //$NON-NLS-1$
listener.setCheckValues(checkValues);
debugOptions.setDebugEnabled(false);
assertFalse("Debug is enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
listener.clear();
checkValues.put(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
listener.setCheckValues(checkValues);
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
assertTrue("Listener did not get called", listener.gotCalled()); //$NON-NLS-1$
assertNull("Found bad value: " + listener.getIncorrectValue(), listener.getIncorrectValue()); //$NON-NLS-1$
}
public void testSetOptionsWhenDisabled() {
// enable tracing initially.
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/disableCheck";
// set its value to 'ok'
debugOptions.setOption(testKey, "ok");
// make sure the right value is added
String actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The correct option value was not returned from the debug option: " + testKey, "ok", actualValue);
// disable tracing
debugOptions.setDebugEnabled(false);
// check for the value
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The 'default' value supplied was not returned when tracing is disabled.", "not ok", actualValue);
// try setting the value to "ok" (this should be a no-op and return the 'default' value)
debugOptions.setOption(testKey, "ok");
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The 'default' value supplied was not returned when tracing is disabled.", "not ok", actualValue);
// remove the option and check for the value (it should still exist after re-enabling tracing)
debugOptions.removeOption(testKey);
// re-enable tracing
debugOptions.setDebugEnabled(true);
// check that the value is still the initial "ok"
actualValue = debugOptions.getOption(testKey, "not ok");
assertEquals("The value after re-enabling tracing is invalid.", "ok", actualValue);
}
public void testStringValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/stringValue";
// set its value to 'test'
debugOptions.setOption(testKey, "test");
// check to make sure the value returned is correct
String actualValue = debugOptions.getOption(testKey, "default");
assertEquals("The correct option value was not returned from the debug option: " + testKey, "test", actualValue);
// remove the option and check for the value (it should not exist so the default value should be returned)
debugOptions.removeOption(testKey);
actualValue = debugOptions.getOption(testKey, "default");
assertEquals("The 'default' value supplied was not returned when the key does not exist in the DebugOptions.", "default", actualValue);
}
public void testIntegerValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
// create a new key to add.
String testKey = getName() + "/debug/intValue";
// set its value to 42.
debugOptions.setOption(testKey, "42");
// check to make sure the value returned is correct
int actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The correct option value was not returned from the debug option: " + testKey, 42, actualValue);
// set the value of this key so that a NumberFormatException will occur
debugOptions.setOption(testKey, "test");
actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The 'default' value supplied was not returned when a NumberFormatException occurs.", 0, actualValue);
// remove the option and check for the value (it should not exist so the default value should be returned)
debugOptions.removeOption(testKey);
actualValue = debugOptions.getIntegerOption(testKey, 0);
assertEquals("The 'default' value supplied was not returned when the key does not exist in the DebugOptions.", 0, actualValue);
}
public void testBooleanValues() {
if (!debugOptions.isDebugEnabled()) {
debugOptions.setDebugEnabled(true);
}
String testKey = getName() + "/debug";
boolean testValue = debugOptions.getBooleanOption(testKey, false);
assertFalse(testKey + " is true", testValue);
debugOptions.setOption(testKey, "false");
testValue = debugOptions.getBooleanOption(testKey, true);
assertFalse(testKey + " is true", testValue);
debugOptions.setOption(testKey, "true");
testValue = debugOptions.getBooleanOption(testKey, false);
assertTrue(testKey + " is false", testValue);
testValue = debugOptions.getBooleanOption(testKey, true);
assertTrue(testKey + " is false", testValue);
}
private TestDebugTrace createDebugTrace(final File traceFile) {
TestDebugTrace debugTrace = null;
if (!debugOptions.isDebugEnabled()) {
/** Setup the DebugOptions */
debugOptions.setDebugEnabled(true);
assertTrue("Debug is not enabled", debugOptions.isDebugEnabled()); //$NON-NLS-1$
}
debugOptions.setOption(getName() + "/debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
debugOptions.setFile(traceFile);
DebugTrace wrapped = debugOptions.newDebugTrace(getName(), TestDebugTrace.class);
debugTrace = new TestDebugTrace(wrapped);
return debugTrace;
}
/**
* test DebugTrace.trace(option, message);
*/
public void testTraceFile01() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.trace("/debug", "testing 1"); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/notset", "testing 2"); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/debug", "testing 3"); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile01", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile01", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.trace(option, message, Throwable)
*/
public void testTraceFile02() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
final String exceptionMessage1 = "An error 1"; //$NON-NLS-1$
final String exceptionMessage2 = "An error 2"; //$NON-NLS-1$
final String exceptionMessage3 = "An error 3"; //$NON-NLS-1$
try {
debugTrace.trace("/debug", "testing 1", new Exception(exceptionMessage1)); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/notset", "testing 2", new Exception(exceptionMessage2)); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.trace("/debug", "testing 3", new Exception(exceptionMessage3)); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message, Throwable)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
final StringBuffer expectedThrowableText1 = new StringBuffer("java.lang.Exception: "); //$NON-NLS-1$
expectedThrowableText1.append(exceptionMessage1);
expectedThrowableText1.append(DebugOptionsTestCase.LINE_SEPARATOR);
expectedThrowableText1.append(DebugOptionsTestCase.TAB_CHARACTER);
expectedThrowableText1.append("at org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase.testTraceFile02(DebugOptionsTestCase.java:"); //$NON-NLS-1$
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile02", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNotNull("throwable text should not be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
if (!traceOutput[0].getThrowableText().startsWith(expectedThrowableText1.toString())) {
final StringBuffer errorMessage = new StringBuffer("The expected throwable text does not start with the actual throwable text."); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Expected"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(expectedThrowableText1.toString());
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Actual"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(traceOutput[0].getThrowableText());
fail(errorMessage.toString());
}
assertNotNull("throwable should not be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
final StringBuffer expectedThrowableText2 = new StringBuffer("java.lang.Exception: "); //$NON-NLS-1$
expectedThrowableText2.append(exceptionMessage3);
expectedThrowableText2.append(DebugOptionsTestCase.LINE_SEPARATOR);
expectedThrowableText2.append(DebugOptionsTestCase.TAB_CHARACTER);
expectedThrowableText2.append("at org.eclipse.osgi.tests.debugoptions.DebugOptionsTestCase.testTraceFile02(DebugOptionsTestCase.java:"); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile02", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("trace message is incorrect", "testing 3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNotNull("throwable text should not be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
if (!traceOutput[1].getThrowableText().startsWith(expectedThrowableText2.toString())) {
final StringBuffer errorMessage = new StringBuffer("The expected throwable text does not start with the actual throwable text."); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Expected"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(expectedThrowableText2.toString());
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("Actual"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append("--------"); //$NON-NLS-1$
errorMessage.append(DebugOptionsTestCase.LINE_SEPARATOR);
errorMessage.append(traceOutput[1].getThrowableText());
fail(errorMessage.toString());
}
assertNotNull("throwable should not be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceDumpStack(option)
*/
public void testTraceFile03() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceDumpStack("/debug"); //$NON-NLS-1$
debugTrace.traceDumpStack("/notset"); //$NON-NLS-1$
debugTrace.traceDumpStack("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceDumpStack(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile03", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Trace message is not a stack dump", traceOutput[0].getMessage().startsWith("Thread Stack dump: ")); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile03", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertTrue("Trace message is not a stack dump", traceOutput[1].getMessage().startsWith("Thread Stack dump: ")); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option)
*/
public void testTraceFile04() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug"); //$NON-NLS-1$
debugTrace.traceEntry("/notset"); //$NON-NLS-1$
debugTrace.traceEntry("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile04", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with no parameters", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile04", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with no parameters", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option, methodArgument)
*/
public void testTraceFile05() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug", new String("arg1")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceEntry("/notset", new String("arg2")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceEntry("/debug", new String("arg3")); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option, methodArgument)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile05", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg1)", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile05", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg3)", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceEntry(option, methodArgument[])
*/
public void testTraceFile06() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceEntry("/debug", new String[] {"arg1", "arg2"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
debugTrace.traceEntry("/notset", new String[] {"arg3", "arg4"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
debugTrace.traceEntry("/debug", new String[] {"arg5", "arg6"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceEntry(option, methodArgument[])' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile06", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg1 arg2)", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile06", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Entering method with parameters: (arg5 arg6)", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceExit(option)
*/
public void testTraceFile07() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceExit("/debug"); //$NON-NLS-1$
debugTrace.traceExit("/notset"); //$NON-NLS-1$
debugTrace.traceExit("/debug"); //$NON-NLS-1$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceExit(option)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile07", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with a void return", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile07", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with a void return", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* test DebugTrace.traceExit(option, result)
*/
public void testTraceFile08() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
TraceEntry[] traceOutput = null;
try {
debugTrace.traceExit("/debug", new String("returnValue1")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceExit("/notset", new String("returnValue2")); //$NON-NLS-1$ //$NON-NLS-2$
debugTrace.traceExit("/debug", new String("returnValue3")); //$NON-NLS-1$ //$NON-NLS-2$
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.traceExit(option, result)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of trace entries", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[0].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[0].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[0].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[0].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile08", traceOutput[0].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with result: returnValue1", traceOutput[0].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[0].getThrowableText()); //$NON-NLS-1$
assertEquals("Wrong number of trace entries for trace without an exception", 2, traceOutput.length); //$NON-NLS-1$
assertEquals("Thread name is incorrect", Thread.currentThread().getName(), traceOutput[1].getThreadName()); //$NON-NLS-1$
assertEquals("Bundle name is incorrect", getName(), traceOutput[1].getBundleSymbolicName()); //$NON-NLS-1$
assertEquals("option-path value is incorrect", "/debug", traceOutput[1].getOptionPath()); //$NON-NLS-1$//$NON-NLS-2$
assertEquals("class name value is incorrect", DebugOptionsTestCase.class.getName(), traceOutput[1].getClassName()); //$NON-NLS-1$
assertEquals("method name value is incorrect", "testTraceFile08", traceOutput[1].getMethodName()); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "Exiting method with result: returnValue3", traceOutput[1].getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
assertNull("throwable should be null", traceOutput[1].getThrowableText()); //$NON-NLS-1$
// delete the trace file
traceFile.delete();
}
/**
* tests DebugTrace.trace(option, message) where the 'option' and 'message contain a '|' character (the delimiter).
*/
public void testTraceFile09() {
final File traceFile = OSGiTestsActivator.getContext().getDataFile(getName() + ".trace"); //$NON-NLS-1$
TestDebugTrace debugTrace = this.createDebugTrace(traceFile);
debugOptions.setOption(getName() + "/debug|path", "true");
TraceEntry[] traceOutput = null;
try {
debugTrace.trace("/debug|path", "A message with a | character.");
debugTrace.trace("/debug|path", "|A message with | multiple || characters.|");
traceOutput = readTraceFile(traceFile); // Note: this call will also delete the trace file
} catch (InvalidTraceEntry invalidEx) {
fail("Failed 'DebugTrace.trace(option, message)' test as an invalid trace entry was found. Actual Value: '" + invalidEx.getActualValue() + "'.", invalidEx); //$NON-NLS-1$ //$NON-NLS-2$
}
assertEquals("Wrong number of entries", 2, traceOutput.length);
String optionPath = decodeString(traceOutput[0].getOptionPath());
String message = decodeString(traceOutput[0].getMessage());
assertEquals("option-path value is incorrect", "/debug|path", optionPath); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "A message with a | character.", message); //$NON-NLS-1$ //$NON-NLS-2$
optionPath = decodeString(traceOutput[1].getOptionPath());
message = decodeString(traceOutput[1].getMessage());
assertEquals("option-path value is incorrect", "/debug|path", optionPath); //$NON-NLS-1$ //$NON-NLS-2$
assertEquals("Trace message is not correct", "|A message with | multiple || characters.|", message); //$NON-NLS-1$ //$NON-NLS-2$
// delete the trace file
traceFile.delete();
}
private static String decodeString(final String inputString) {
if (inputString == null || inputString.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED) < 0)
return inputString;
final StringBuffer tempBuffer = new StringBuffer(inputString);
int currentIndex = tempBuffer.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED);
while (currentIndex >= 0) {
tempBuffer.replace(currentIndex, currentIndex + TRACE_ELEMENT_DELIMITER_ENCODED.length(), TRACE_ELEMENT_DELIMITER);
currentIndex = tempBuffer.indexOf(TRACE_ELEMENT_DELIMITER_ENCODED);
}
return tempBuffer.toString();
}
private TraceEntry[] readTraceFile(File traceFile) throws InvalidTraceEntry {
Reader traceReader = null;
List traceEntries = new ArrayList();
try {
traceReader = new BufferedReader(new InputStreamReader(new FileInputStream(traceFile), "UTF-8")); //$NON-NLS-1$
TraceEntry entry = null;
while ((entry = this.readMessage(traceReader)) != null) {
traceEntries.add(entry);
}
} catch (IOException ex) {
fail("Failed to read trace file", ex); //$NON-NLS-1$
} finally {
if (traceReader != null) {
try {
traceReader.close();
} catch (Exception ex) {
// do nothing
}
}
}
return (TraceEntry[]) traceEntries.toArray(new TraceEntry[traceEntries.size()]);
}
private TraceEntry readMessage(final Reader traceReader) throws IOException, InvalidTraceEntry {
TraceEntry result = null;
int input = traceReader.read();
while (input != -1) {
char inputChar = (char) input;
if (inputChar == '#') {
while ((inputChar != '\n') && (inputChar != '\r')) {
// do nothing
inputChar = (char) traceReader.read();
}
}
if (inputChar == DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
// first entry - thread name
final String threadName = this.readEntry(traceReader);
if ((threadName == null) || (threadName.length() == 0)) {
throw new InvalidTraceEntry("The thread name in a trace entry is null or empty", threadName); //$NON-NLS-1$
}
// read the next character
final String date = this.readEntry(traceReader);
if ((date == null) || (date.length() == 0)) {
throw new InvalidTraceEntry("The timestamp in a trace entry is null or empty", date); //$NON-NLS-1$
}
long timestamp = 0;
try {
timestamp = DebugOptionsTestCase.TRACE_FILE_DATE_FORMATTER.parse(date).getTime();
} catch (ParseException parseEx) {
throw new InvalidTraceEntry("The date in a trace entry '" + date + "' could not be parsed.", date); //$NON-NLS-1$ //$NON-NLS-2$
}
// third entry - bundle symbolic name
final String symbolicName = this.readEntry(traceReader);
if ((symbolicName == null) || (symbolicName.length() == 0)) {
throw new InvalidTraceEntry("The bundle symbolic name in a trace entry is null or empty", symbolicName); //$NON-NLS-1$
}
// fourth entry - option path
final String optionPath = this.readEntry(traceReader);
if ((optionPath == null) || (optionPath.length() == 0)) {
throw new InvalidTraceEntry("The option-path in a trace entry is null or empty", optionPath); //$NON-NLS-1$
}
// fifth entry - class name
final String className = this.readEntry(traceReader);
if ((className == null) || (className.length() == 0)) {
throw new InvalidTraceEntry("The class name in a trace entry is null or empty", className); //$NON-NLS-1$
}
// sixth entry - method name
final String methodName = this.readEntry(traceReader);
if ((methodName == null) || (methodName.length() == 0)) {
throw new InvalidTraceEntry("The method name in a trace entry is null or empty", methodName); //$NON-NLS-1$
}
// seventh entry - line number
final String lineNumberString = this.readEntry(traceReader);
if ((lineNumberString == null) || (lineNumberString.length() == 0)) {
throw new InvalidTraceEntry("The line number in a trace entry is null or empty", lineNumberString); //$NON-NLS-1$
}
final int lineNumber = Integer.valueOf(lineNumberString).intValue();
// eighth entry - message
final String message = this.readEntry(traceReader);
// read in the next character. if it is \r or \n then the throwable was not supplied
traceReader.mark(1);
inputChar = (char) traceReader.read();
String throwable = null;
if (inputChar != '\n' && inputChar != '\r') {
traceReader.reset();
// ninth entry (optional) - throwable
throwable = this.readEntry(traceReader);
if ((throwable == null) || (throwable.length() == 0)) {
throw new InvalidTraceEntry("The throwable in a trace entry is null or empty", throwable); //$NON-NLS-1$
}
}
// create the entry
result = new TraceEntry(threadName, timestamp, symbolicName, optionPath, className, methodName, lineNumber, message, throwable);
break; // no point in reading any more information since the TraceEntry is created
}
// read the next character
input = traceReader.read();
}
return result;
}
private String readEntry(final Reader traceReader) throws IOException {
char inputChar = (char) traceReader.read();
StringBuffer buffer = new StringBuffer();
while (inputChar != DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
inputChar = (char) traceReader.read();
if (inputChar != DebugOptionsTestCase.TRACE_ELEMENT_DELIMITER.charAt(0)) {
buffer.append(inputChar);
}
}
return buffer.toString().trim();
}
static public class TraceEntry {
/** If a bundles symbolic name is not specified then the default value of /debug can be used */
public final static String DEFAULT_OPTION_PATH = "/debug"; //$NON-NLS-1$
/**
* The name of the thread executing the code
*/
private final String threadName;
/**
* The date and time when the trace occurred.
*
*/
private final long timestamp;
/**
* The trace option-path
*/
private final String optionPath;
/**
* The symbolic name of the bundle being traced
*/
private final String bundleSymbolicName;
/**
* The class being traced
*/
private final String className;
/**
* The method being traced
*/
private String methodName = null;
/**
* The line number
*/
private final int lineNumber;
/**
* The trace message
*/
private final String message;
/**
* The trace exception
*/
private final String throwableText;
public TraceEntry(final String traceThreadName, final long traceTimestamp, final String traceBundleName, final String traceOptionPath, final String traceClassName, final String traceMethodName, final int traceLineNumber, final String traceMessage) {
this.threadName = traceThreadName;
this.bundleSymbolicName = traceBundleName;
this.optionPath = traceOptionPath;
this.className = traceClassName;
this.methodName = traceMethodName;
this.lineNumber = traceLineNumber;
this.message = traceMessage;
this.timestamp = traceTimestamp;
this.throwableText = null;
}
public TraceEntry(final String traceThreadName, final long traceTimestamp, final String traceBundleName, final String traceOptionPath, final String traceClassName, final String traceMethodName, final int traceLineNumber, final String traceMessage, final String traceThrowable) {
this.threadName = traceThreadName;
this.bundleSymbolicName = traceBundleName;
this.optionPath = traceOptionPath;
this.className = traceClassName;
this.methodName = traceMethodName;
this.lineNumber = traceLineNumber;
this.message = traceMessage;
this.timestamp = traceTimestamp;
this.throwableText = traceThrowable;
}
public final String getThreadName() {
return threadName;
}
public final long getTimestamp() {
return timestamp;
}
public final String getBundleSymbolicName() {
return bundleSymbolicName;
}
public final String getMessage() {
return message;
}
public final String getThrowableText() {
return throwableText;
}
public final String getClassName() {
return className;
}
public final String getMethodName() {
return methodName;
}
public final String getOptionPath() {
return optionPath;
}
public final int getLineNumber() {
return lineNumber;
}
}
static class InvalidTraceEntry extends Exception {
private static final long serialVersionUID = -63837787081750344L;
public InvalidTraceEntry(String message, String actual) {
super(message);
this.actualValue = actual;
}
public final String getActualValue() {
return this.actualValue;
}
String actualValue;
String expectedValue;
}
static class TestDebugTrace implements DebugTrace {
private final DebugTrace wrapped;
public TestDebugTrace(DebugTrace wrapped) {
this.wrapped = wrapped;
}
public void trace(String option, String message) {
wrapped.trace(option, message);
}
public void trace(String option, String message, Throwable error) {
wrapped.trace(option, message, error);
}
public void traceDumpStack(String option) {
wrapped.traceDumpStack(option);
}
public void traceEntry(String option) {
wrapped.traceEntry(option);
}
public void traceEntry(String option, Object methodArgument) {
wrapped.traceEntry(option, methodArgument);
}
public void traceEntry(String option, Object[] methodArguments) {
wrapped.traceEntry(option, methodArguments);
}
public void traceExit(String option) {
wrapped.traceExit(option);
}
public void traceExit(String option, Object result) {
wrapped.traceExit(option, result);
}
}
class TestDebugOptionsListener implements DebugOptionsListener {
boolean called = false;
String incorrectValue;
Map checkValues;
public void optionsChanged(DebugOptions options) {
called = true;
if (checkValues == null)
return;
for (Iterator entries = checkValues.entrySet().iterator(); entries.hasNext();) {
Map.Entry entry = (Entry) entries.next();
String debugValue = options.getOption((String) entry.getKey());
String error = "Value is incorrect for key: " + entry.getKey() + " " + debugValue; //$NON-NLS-1$//$NON-NLS-2$
if (debugValue == null) {
if (entry.getValue() != null) {
incorrectValue = error;
return;
}
continue;
}
if (!debugValue.equals(entry.getValue())) {
incorrectValue = error;
return;
}
}
}
public boolean gotCalled() {
return called;
}
public void clear() {
called = false;
checkValues = null;
incorrectValue = null;
}
public void setCheckValues(Map checkValues) {
this.checkValues = checkValues;
}
public String getIncorrectValue() {
return incorrectValue;
}
}
}
| 54,723 | 0.701551 | 0.688961 | 1,053 | 50.967712 | 44.778351 | 281 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.979107 | false | false | 13 |
0d3e27a03eee8d43be3418ed69aa40ee0d33a043 | 10,685,878,675,337 | 65625df689bc01f16f5522d3bdb9d79ede22e38e | /changecalculator/src/main/java/org/msstate/cse/changecalculator/diff/DiffParser.java | 77902ffb85540e0243eae408202a8f681bea237e | [] | no_license | DonaldHesler/codereview | https://github.com/DonaldHesler/codereview | 3acc3f3e436b1d2bba81fe5815c32af162202704 | 7f54683adcc99509f652473edf58375448f6e7e7 | refs/heads/master | 2019-12-01T00:01:52.558000 | 2016-04-04T04:20:53 | 2016-04-04T04:20:53 | 55,172,095 | 0 | 0 | null | true | 2016-03-31T19:16:15 | 2016-03-31T18:03:26 | 2016-03-31T18:03:27 | 2016-03-31T19:16:15 | 25 | 0 | 0 | 1 | Java | null | null | package org.msstate.cse.changecalculator.diff;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class DiffParser {
public static List<String> getChangedFiles(String diffContent) { //AJAY-NOTE: Change return from list<string> set<string>
if (diffContent != null && !diffContent.isEmpty()) {
List<String> changedFileList = new ArrayList<String>();
InputStream in = new ByteArrayInputStream(diffContent.getBytes());
Reader unbufferedReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(unbufferedReader);
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
if (currentLine.startsWith("Index:")) {
String[] splitStr = currentLine.split("Index:");
if (splitStr.length == 2 && splitStr[1] != null
&& !splitStr[1].isEmpty()) {
changedFileList.add(splitStr[1].trim());
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (unbufferedReader != null)
unbufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return changedFileList;
}
return null;
}
}
| UTF-8 | Java | 1,448 | java | DiffParser.java | Java | [] | null | [] | package org.msstate.cse.changecalculator.diff;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
public class DiffParser {
public static List<String> getChangedFiles(String diffContent) { //AJAY-NOTE: Change return from list<string> set<string>
if (diffContent != null && !diffContent.isEmpty()) {
List<String> changedFileList = new ArrayList<String>();
InputStream in = new ByteArrayInputStream(diffContent.getBytes());
Reader unbufferedReader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(unbufferedReader);
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
if (currentLine.startsWith("Index:")) {
String[] splitStr = currentLine.split("Index:");
if (splitStr.length == 2 && splitStr[1] != null
&& !splitStr[1].isEmpty()) {
changedFileList.add(splitStr[1].trim());
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null)
reader.close();
if (unbufferedReader != null)
unbufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return changedFileList;
}
return null;
}
}
| 1,448 | 0.655387 | 0.652624 | 48 | 28.166666 | 23.502954 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.229167 | false | false | 13 |
0482dc1842a38e75cce1ffaf01e2b3448a24a4a5 | 18,966,575,583,970 | 719ae162602df7ff301e4e7dd5e3fd2a52effd41 | /src/sin/item/Item.java | 892e417d8572a1696d0236a79060e695308371f6 | [] | no_license | pettta/singame | https://github.com/pettta/singame | 8362e0f278d7f5e64a4fbc74cbc1a08e959375e4 | d31efed3cdb85ab2608f04a400c5812340125714 | refs/heads/master | 2023-06-02T23:11:24.582000 | 2021-06-21T03:04:07 | 2021-06-21T03:04:07 | 378,786,913 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package sin.item;
import sin.Game;
import sin.Registry;
import sin.lib.Lib;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Name: Item.java
* Purpose: Serves as the base class for all items and manages their universal functionality.
* Last Updated: 6/1/2021
* Author: Zacharia Bridgers
* Dependencies: None
*/
public class Item {
public int maxStack;
public BufferedImage image;
public ItemType type;
String name;
public Item(String name, int maxStack, ItemType type) {
this.name = name;
this.type = type;
this.maxStack = maxStack;
this.image = Lib.getImage("src/resources/items/" + name + ".png");
}
public Item(String name, int maxStack) {
this(name, maxStack, ItemType.Resource);
}
public String getName() {
return name;
}
public Item(String name, ItemType type) {
this(name, 99, type);
}
}
| UTF-8 | Java | 987 | java | Item.java | Java | [
{
"context": "unctionality.\n * Last Updated: 6/1/2021\n * Author: Zacharia Bridgers\n * Dependencies: None\n */\npublic class Item {\n\n ",
"end": 366,
"score": 0.9991219639778137,
"start": 349,
"tag": "NAME",
"value": "Zacharia Bridgers"
}
] | null | [] | package sin.item;
import sin.Game;
import sin.Registry;
import sin.lib.Lib;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Name: Item.java
* Purpose: Serves as the base class for all items and manages their universal functionality.
* Last Updated: 6/1/2021
* Author: <NAME>
* Dependencies: None
*/
public class Item {
public int maxStack;
public BufferedImage image;
public ItemType type;
String name;
public Item(String name, int maxStack, ItemType type) {
this.name = name;
this.type = type;
this.maxStack = maxStack;
this.image = Lib.getImage("src/resources/items/" + name + ".png");
}
public Item(String name, int maxStack) {
this(name, maxStack, ItemType.Resource);
}
public String getName() {
return name;
}
public Item(String name, ItemType type) {
this(name, 99, type);
}
}
| 976 | 0.657548 | 0.649443 | 45 | 20.933332 | 20.120085 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 13 |
030ff6b2aa2ad06c0d343a9c45491df6ac50b897 | 11,321,533,801,831 | b9d5551b3883d3a77cf4bdc962c08bca2c80de8c | /Proyecto Fase 2/hotelCentroamerica/Hotel.java | 87e8a76bc0aad15aa504c871c27c03babda54f7b | [] | no_license | miltonXD/IPC1A_2S_201314014 | https://github.com/miltonXD/IPC1A_2S_201314014 | 5acbbd1befc8bf5074a93aea19c10d1903374f2c | 79af1a2e7d7ea440a73661e52beeba78def62b8f | refs/heads/master | 2020-12-24T15:14:38.276000 | 2020-08-29T02:42:48 | 2020-08-29T02:42:48 | 26,456,610 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package hotelCentroamerica;
public class Hotel {
Hotel siguiente;
Hotel anterior;
int id;
String nombre;
String pais;
String direccion;
String telefono;
String estado;
ListaHabitacion listaHabitacion = new ListaHabitacion();
ListaCliente listCliente = new ListaCliente();
ListaReservacion listaReservacion = new ListaReservacion();
ListaRestaurante listarestaurante = new ListaRestaurante();
ListaServicio listaservicio = new ListaServicio();
ListaEspera listaespera = new ListaEspera();
ListaCobro cobro = new ListaCobro();
ListaPromocion promocion = new ListaPromocion();
public Hotel(){
this.siguiente = null;
this.anterior = null;
}
public Hotel(int id, String nombre, String pais,
String direccion, String telefono) {
this.id=id;
this.nombre = nombre;
this.pais = pais;
this.direccion = direccion;
this.telefono = telefono;
this.estado = "libre";
this.siguiente = null;
this.anterior = null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| UTF-8 | Java | 1,564 | java | Hotel.java | Java | [] | null | [] | package hotelCentroamerica;
public class Hotel {
Hotel siguiente;
Hotel anterior;
int id;
String nombre;
String pais;
String direccion;
String telefono;
String estado;
ListaHabitacion listaHabitacion = new ListaHabitacion();
ListaCliente listCliente = new ListaCliente();
ListaReservacion listaReservacion = new ListaReservacion();
ListaRestaurante listarestaurante = new ListaRestaurante();
ListaServicio listaservicio = new ListaServicio();
ListaEspera listaespera = new ListaEspera();
ListaCobro cobro = new ListaCobro();
ListaPromocion promocion = new ListaPromocion();
public Hotel(){
this.siguiente = null;
this.anterior = null;
}
public Hotel(int id, String nombre, String pais,
String direccion, String telefono) {
this.id=id;
this.nombre = nombre;
this.pais = pais;
this.direccion = direccion;
this.telefono = telefono;
this.estado = "libre";
this.siguiente = null;
this.anterior = null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getPais() {
return pais;
}
public void setPais(String pais) {
this.pais = pais;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| 1,564 | 0.751279 | 0.751279 | 73 | 20.424658 | 15.914944 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.917808 | false | false | 13 |
1c81614e1831751c2fa22f55d15eac35061ee09a | 8,839,042,705,093 | 63fc9cc074f8526d9f07b8a2656799d7e155bd1d | /app/src/main/java/com/keruiyun/saike/HomeActivity.java | 7043e07a4372fb3cf36dcc3a319e4bc7953fb2ce | [] | no_license | fushengmeng/SaiKe_android_20170608 | https://github.com/fushengmeng/SaiKe_android_20170608 | a46a8a4726c5f821f24e1ab2d05ff2f9df30f39f | 00870c74d97e8d6c01c307b78e0fcae4d3896f96 | refs/heads/master | 2021-01-06T03:56:32.880000 | 2018-03-16T10:14:05 | 2018-03-16T10:14:05 | 124,332,792 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.keruiyun.saike;
import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import com.keruiyun.saike.main.MainApplication;
public class HomeActivity extends BaseActivity
{
private ViewPager mPageVp;
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
private FragmentAdapter mFragmentAdapter;
static public MainActivity _mainFragment;
private AirActivity _airFragment;
BroadcastReceiver _receiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MainApplication.getInstance()._activity = this;
findById();
init();
registerBroadcast();
}
@Override
public int loadContentView() {
return R.layout.activity_home;
}
@Override
protected void onDestroy()
{
super.onDestroy();
removeBroadcast();
}
private void findById()
{
mPageVp = (ViewPager)this.findViewById(R.id.id_page_vp);
}
private void init()
{
_mainFragment = new MainActivity();
_airFragment = new AirActivity();
mFragmentList.add(_mainFragment);
mFragmentList.add(_airFragment);
mFragmentAdapter = new FragmentAdapter(
this.getSupportFragmentManager(), mFragmentList);
mPageVp.setAdapter(mFragmentAdapter);
mPageVp.setCurrentItem(0);
mPageVp.setOnPageChangeListener(new OnPageChangeListener()
{
@Override
public void onPageScrollStateChanged(int state)
{
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels)
{
}
@Override
public void onPageSelected(int position)
{
try
{
if (0 == position)
{
//_airFragment.zoomView.zoomTo(1.0f, 0.0f, 0.0f);
}
else
{
//_mainFragment.zoomView.zoomTo(1.0f, 0.0f, 0.0f);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
}
private void registerBroadcast()
{
_receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if ("com.keruiyun.saike.gotohomepage".equals(action))
{
mPageVp.setCurrentItem(0, true);
}
else if ("com.keruiyun.saike.gotoairpage".equals(action))
{
mPageVp.setCurrentItem(1, true);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.keruiyun.saike.gotohomepage");
filter.addAction("com.keruiyun.saike.gotoairpage");
registerReceiver(_receiver, filter);
}
private void removeBroadcast()
{
unregisterReceiver(_receiver);
}
}
| UTF-8 | Java | 2,850 | java | HomeActivity.java | Java | [] | null | [] | package com.keruiyun.saike;
import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import com.keruiyun.saike.main.MainApplication;
public class HomeActivity extends BaseActivity
{
private ViewPager mPageVp;
private List<Fragment> mFragmentList = new ArrayList<Fragment>();
private FragmentAdapter mFragmentAdapter;
static public MainActivity _mainFragment;
private AirActivity _airFragment;
BroadcastReceiver _receiver;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MainApplication.getInstance()._activity = this;
findById();
init();
registerBroadcast();
}
@Override
public int loadContentView() {
return R.layout.activity_home;
}
@Override
protected void onDestroy()
{
super.onDestroy();
removeBroadcast();
}
private void findById()
{
mPageVp = (ViewPager)this.findViewById(R.id.id_page_vp);
}
private void init()
{
_mainFragment = new MainActivity();
_airFragment = new AirActivity();
mFragmentList.add(_mainFragment);
mFragmentList.add(_airFragment);
mFragmentAdapter = new FragmentAdapter(
this.getSupportFragmentManager(), mFragmentList);
mPageVp.setAdapter(mFragmentAdapter);
mPageVp.setCurrentItem(0);
mPageVp.setOnPageChangeListener(new OnPageChangeListener()
{
@Override
public void onPageScrollStateChanged(int state)
{
}
@Override
public void onPageScrolled(int position, float offset, int offsetPixels)
{
}
@Override
public void onPageSelected(int position)
{
try
{
if (0 == position)
{
//_airFragment.zoomView.zoomTo(1.0f, 0.0f, 0.0f);
}
else
{
//_mainFragment.zoomView.zoomTo(1.0f, 0.0f, 0.0f);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
}
private void registerBroadcast()
{
_receiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if ("com.keruiyun.saike.gotohomepage".equals(action))
{
mPageVp.setCurrentItem(0, true);
}
else if ("com.keruiyun.saike.gotoairpage".equals(action))
{
mPageVp.setCurrentItem(1, true);
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("com.keruiyun.saike.gotohomepage");
filter.addAction("com.keruiyun.saike.gotoairpage");
registerReceiver(_receiver, filter);
}
private void removeBroadcast()
{
unregisterReceiver(_receiver);
}
}
| 2,850 | 0.704561 | 0.697895 | 146 | 18.520548 | 19.880541 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.164384 | false | false | 13 |
79d379c1d19c14737872c8fa57744a132c74a529 | 8,839,042,706,759 | 4a5a7305a5e4b5836ab39cb9275c0dbcd2963f99 | /src/main/java/edu/calpoly/csc365/examples/webapp/controller/TransactionServlet.java | da5f6a5dd712f4a65c221fe589f9ffaf5f868b89 | [
"Apache-2.0"
] | permissive | tkuboi/csc365WebAppExample | https://github.com/tkuboi/csc365WebAppExample | 9dcbcf067da04baf2bc4733ad4dbc405596a80a7 | bd7fdb57052cfeec15a2e1887a30c68f19cdb7a7 | refs/heads/master | 2022-07-02T23:27:57.925000 | 2020-03-09T00:41:44 | 2020-03-09T00:41:44 | 189,266,348 | 1 | 1 | null | false | 2020-10-13T13:33:03 | 2019-05-29T17:02:58 | 2020-03-09T00:42:01 | 2020-10-13T13:33:02 | 31 | 1 | 0 | 2 | Java | false | false | package edu.calpoly.csc365.examples.webapp.controller;
import edu.calpoly.csc365.examples.webapp.dao.DaoCommand;
import edu.calpoly.csc365.examples.webapp.dao.DaoManager;
import edu.calpoly.csc365.examples.webapp.dao.DaoManagerFactory;
import edu.calpoly.csc365.examples.webapp.dao.TransactionDaoCommandImpl;
import edu.calpoly.csc365.examples.webapp.entity.Transaction;
import edu.calpoly.csc365.examples.webapp.service.AuthenticationService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
@WebServlet(name = "TransactionServlet", urlPatterns = "/transaction")
public class TransactionServlet extends HttpServlet {
private DaoManager dm;
public TransactionServlet() throws Exception {
this.dm = DaoManagerFactory.createDaoManager();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("transaction.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie loginCookie = AuthenticationService.getLoginCookie(request);
if (loginCookie == null) {
response.sendRedirect("login");
} else {
response.addCookie(loginCookie);
Integer customerId = Integer.parseInt(request.getParameter("cid"));
Integer cardNumber = Integer.parseInt(request.getParameter("card_number"));
Integer vendorId = Integer.parseInt(request.getParameter("vid"));
Date tdate = Date.valueOf(request.getParameter("date"));
System.out.println(tdate);
Double amount = Double.parseDouble(request.getParameter("amount"));
Transaction transaction = new Transaction();
transaction.setCustomerId(customerId);
transaction.setCardNumber(cardNumber);
transaction.setVendorId(vendorId);
transaction.setDate(tdate);
transaction.setAmount(amount);
DaoCommand daoCommand = new TransactionDaoCommandImpl(transaction);
Object result = daoCommand.execute(this.dm);
if (result != null) {
transaction = (Transaction) result;
}
PrintWriter out = response.getWriter();
out.println("The transaction has been successfully executed!");
out.println(transaction);
out.close();
}
}
}
| UTF-8 | Java | 2,609 | java | TransactionServlet.java | Java | [] | null | [] | package edu.calpoly.csc365.examples.webapp.controller;
import edu.calpoly.csc365.examples.webapp.dao.DaoCommand;
import edu.calpoly.csc365.examples.webapp.dao.DaoManager;
import edu.calpoly.csc365.examples.webapp.dao.DaoManagerFactory;
import edu.calpoly.csc365.examples.webapp.dao.TransactionDaoCommandImpl;
import edu.calpoly.csc365.examples.webapp.entity.Transaction;
import edu.calpoly.csc365.examples.webapp.service.AuthenticationService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
@WebServlet(name = "TransactionServlet", urlPatterns = "/transaction")
public class TransactionServlet extends HttpServlet {
private DaoManager dm;
public TransactionServlet() throws Exception {
this.dm = DaoManagerFactory.createDaoManager();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("transaction.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie loginCookie = AuthenticationService.getLoginCookie(request);
if (loginCookie == null) {
response.sendRedirect("login");
} else {
response.addCookie(loginCookie);
Integer customerId = Integer.parseInt(request.getParameter("cid"));
Integer cardNumber = Integer.parseInt(request.getParameter("card_number"));
Integer vendorId = Integer.parseInt(request.getParameter("vid"));
Date tdate = Date.valueOf(request.getParameter("date"));
System.out.println(tdate);
Double amount = Double.parseDouble(request.getParameter("amount"));
Transaction transaction = new Transaction();
transaction.setCustomerId(customerId);
transaction.setCardNumber(cardNumber);
transaction.setVendorId(vendorId);
transaction.setDate(tdate);
transaction.setAmount(amount);
DaoCommand daoCommand = new TransactionDaoCommandImpl(transaction);
Object result = daoCommand.execute(this.dm);
if (result != null) {
transaction = (Transaction) result;
}
PrintWriter out = response.getWriter();
out.println("The transaction has been successfully executed!");
out.println(transaction);
out.close();
}
}
}
| 2,609 | 0.762361 | 0.754312 | 63 | 40.412697 | 28.107298 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.746032 | false | false | 13 |
24803c357c8ff2382ef2265d532a7ae597738794 | 9,423,158,257,544 | 77c64db50bf44b7fdc89c2a16dcc3e35cc260b0e | /Android/app/src/main/java/fashiome/android/fragments/ProductReviewFragment.java | d41c35bba60ea033022b4353e89b6932dd7e6065 | [] | no_license | deborshisaha/LocalChoyce | https://github.com/deborshisaha/LocalChoyce | 09b33e77a3335fb4d6b4aafe3fa1d6c582b3f859 | 28776bb75e8d67428e92594bb725c5373fa22ac0 | refs/heads/master | 2021-05-04T11:31:28.694000 | 2016-04-07T19:27:50 | 2016-04-07T19:27:50 | 52,942,499 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fashiome.android.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.parse.FindCallback;
import com.parse.ParseException;
import java.util.List;
import fashiome.android.R;
import fashiome.android.v2.adapters.ProductReviewRecyclerViewAdapter;
import fashiome.android.models.Product;
import fashiome.android.models.ProductReview;
public class ProductReviewFragment extends Fragment {
private RecyclerView mRecyclerView;
private ProductReviewRecyclerViewAdapter mProductReviewRecyclerViewAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean mReviewLoading = false;
private Product mProduct = null;
public static ProductReviewFragment newInstance(Product product) {
ProductReviewFragment fragment = new ProductReviewFragment();
Bundle args = new Bundle();
args.putParcelable(Product.PRODUCT_KEY, product);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mProduct = (Product) getActivity().getIntent().getExtras().getParcelable(Product.PRODUCT_KEY);
if (mProduct != null) {
loadProductReviews(mProduct);
}
}
private void loadProductReviews (final Product product) {
if (mReviewLoading == true) {
swipeRefreshLayout.setEnabled(false);
return;
}
mReviewLoading = true;
ProductReview.fetchProductReview(product, new FindCallback<ProductReview>() {
@Override
public void done(List<ProductReview> productReviews, ParseException e) {
swipeRefreshLayout.setRefreshing(false);
mReviewLoading = false;
if (e == null) {
mProductReviewRecyclerViewAdapter.setProductReviews(productReviews);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recyclerview_conversations, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rvConversations);
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
R.color.colorPrimary,
R.color.colorPrimary,
R.color.colorPrimary);
Context context = view.getContext();
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mProductReviewRecyclerViewAdapter = new ProductReviewRecyclerViewAdapter();
mRecyclerView.setAdapter(mProductReviewRecyclerViewAdapter);
swipeRefreshLayout.setRefreshing(true);
loadProductReviews(mProduct);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
loadProductReviews(mProduct);
}
});
return view;
}
}
| UTF-8 | Java | 3,534 | java | ProductReviewFragment.java | Java | [] | null | [] | package fashiome.android.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.parse.FindCallback;
import com.parse.ParseException;
import java.util.List;
import fashiome.android.R;
import fashiome.android.v2.adapters.ProductReviewRecyclerViewAdapter;
import fashiome.android.models.Product;
import fashiome.android.models.ProductReview;
public class ProductReviewFragment extends Fragment {
private RecyclerView mRecyclerView;
private ProductReviewRecyclerViewAdapter mProductReviewRecyclerViewAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private boolean mReviewLoading = false;
private Product mProduct = null;
public static ProductReviewFragment newInstance(Product product) {
ProductReviewFragment fragment = new ProductReviewFragment();
Bundle args = new Bundle();
args.putParcelable(Product.PRODUCT_KEY, product);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mProduct = (Product) getActivity().getIntent().getExtras().getParcelable(Product.PRODUCT_KEY);
if (mProduct != null) {
loadProductReviews(mProduct);
}
}
private void loadProductReviews (final Product product) {
if (mReviewLoading == true) {
swipeRefreshLayout.setEnabled(false);
return;
}
mReviewLoading = true;
ProductReview.fetchProductReview(product, new FindCallback<ProductReview>() {
@Override
public void done(List<ProductReview> productReviews, ParseException e) {
swipeRefreshLayout.setRefreshing(false);
mReviewLoading = false;
if (e == null) {
mProductReviewRecyclerViewAdapter.setProductReviews(productReviews);
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recyclerview_conversations, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.rvConversations);
swipeRefreshLayout = (SwipeRefreshLayout)view.findViewById(R.id.swipeContainer);
swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
R.color.colorPrimary,
R.color.colorPrimary,
R.color.colorPrimary);
Context context = view.getContext();
mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
mProductReviewRecyclerViewAdapter = new ProductReviewRecyclerViewAdapter();
mRecyclerView.setAdapter(mProductReviewRecyclerViewAdapter);
swipeRefreshLayout.setRefreshing(true);
loadProductReviews(mProduct);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
loadProductReviews(mProduct);
}
});
return view;
}
}
| 3,534 | 0.694114 | 0.692699 | 103 | 33.31068 | 27.950382 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.592233 | false | false | 13 |
c7d44730a65d1467ffdc821bb972279e64e90e61 | 13,228,499,284,853 | c734f4cf8b18516aa49e921676cf3d202b360709 | /app/src/main/java/com/example/nicky/assignment/datasource/PlanetDataSourceFactory.java | 2a3c5fe5edd177f244ba312474508015129f6bc4 | [] | no_license | nickyk2407/Assignment | https://github.com/nickyk2407/Assignment | f9ccc53321b792c6ffcaff240d7e030db600e0d7 | be509c20c451c40e388ba7782beff202cef73956 | refs/heads/master | 2020-03-28T16:24:30.519000 | 2019-07-15T05:32:00 | 2019-07-15T05:32:00 | 148,691,507 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.nicky.assignment.datasource;
import android.arch.lifecycle.MutableLiveData;
import android.arch.paging.DataSource;
import com.example.nicky.assignment.network.Planets;
import javax.inject.Inject;
/**
* Created by NICKY on 13-09-2018.
*/
public class PlanetDataSourceFactory extends DataSource.Factory<Integer, Planets> {
private final PlanetDataSource planetDataSource;
private final MutableLiveData<PlanetDataSource> planetDataSourceLiveData;
@Inject
public PlanetDataSourceFactory(PlanetDataSource planetDataSource) {
this.planetDataSource = planetDataSource;
planetDataSourceLiveData = new MutableLiveData<>();
}
@Override
public DataSource<Integer, Planets> create() {
planetDataSourceLiveData.postValue(planetDataSource);
return planetDataSource;
}
public PlanetDataSource getPlanetDataSource() {
return planetDataSource;
}
}
| UTF-8 | Java | 943 | java | PlanetDataSourceFactory.java | Java | [
{
"context": "s;\n\nimport javax.inject.Inject;\n\n/**\n * Created by NICKY on 13-09-2018.\n */\n\npublic class PlanetDataSource",
"end": 244,
"score": 0.9988049864768982,
"start": 239,
"tag": "NAME",
"value": "NICKY"
}
] | null | [] | package com.example.nicky.assignment.datasource;
import android.arch.lifecycle.MutableLiveData;
import android.arch.paging.DataSource;
import com.example.nicky.assignment.network.Planets;
import javax.inject.Inject;
/**
* Created by NICKY on 13-09-2018.
*/
public class PlanetDataSourceFactory extends DataSource.Factory<Integer, Planets> {
private final PlanetDataSource planetDataSource;
private final MutableLiveData<PlanetDataSource> planetDataSourceLiveData;
@Inject
public PlanetDataSourceFactory(PlanetDataSource planetDataSource) {
this.planetDataSource = planetDataSource;
planetDataSourceLiveData = new MutableLiveData<>();
}
@Override
public DataSource<Integer, Planets> create() {
planetDataSourceLiveData.postValue(planetDataSource);
return planetDataSource;
}
public PlanetDataSource getPlanetDataSource() {
return planetDataSource;
}
}
| 943 | 0.757158 | 0.748674 | 35 | 25.942858 | 26.509235 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
a0254487fae15d3edbb7df1771693a43386260a4 | 22,711,787,073,570 | 44e082b233a2e44212422514fa9225cf1b6358d2 | /Archiv/GL Prog 2018 BB - Aufgabe 9/ZweitlaengsteStrings.java | a5f109db31642acfe985c6d4c009fd63cc4fdfec | [] | no_license | fhbgraceb/VerbundA-SS20 | https://github.com/fhbgraceb/VerbundA-SS20 | b3af20000e1a4b6efe768156ad415dbf67e16be0 | 7e672445bb785386af2ff65d3526f89c67882a71 | refs/heads/master | 2022-12-28T05:56:20.158000 | 2020-10-10T23:20:18 | 2020-10-10T23:20:18 | 238,525,365 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aufgabe09;
/*
* zweitlaengsteStrings:
*
* Schreiben Sie ein Unterprogramm an das
* eine beliebige Anzahl von Strings übergeben werden kann und
* das die Strings mit der zweitgrößten Länge zurückliefert
* (dies können auch mehrere sein).
*
* Beispiel:
* zweitlaengsteStrings("ABCD", "ABCDE", "QWER", "QWERT")
* liefert als Ergebnis ein Array mit den Elementen “ABCD“ und “QWER“,
* weil das die Strings mit der zweitgrößten Länge (4) sind.
*
* Die Lösung basiert auf einer Idee von Herrn Auer (PIT-Student, 2012).
*/
public class ZweitlaengsteStrings
{
public static String[] zweitlaengsteStrings(String[] worte)
{
String[] ergebnis;
int laenge = 0;
int laengste = 0;
int zweitlaengste = 0;
int anzahl;
int position;
// zweitgrößte Länge suchen
for (int i = 0; i < worte.length; i++)
{
laenge = worte[i].length();
if (laenge > laengste)
{
zweitlaengste = laengste;
laengste = laenge;
}
else if ((laenge < laengste) && (laenge > zweitlaengste))
{
zweitlaengste = laenge;
}
}
// Anzahl der Strings mit der zweitgrößten Länge suchen
anzahl = 0;
for (int i = 0; i < worte.length; i++)
{
if (worte[i].length() == zweitlaengste)
{
anzahl++;
}
}
// Das Ergebnis-Array auf die richtige Größe bringen
ergebnis = new String[anzahl];
// Die zweitlängsten Strings in das Array einfüllen
position = 0;
for (int i = 0; i < worte.length; i++)
{
if (worte[i].length() == zweitlaengste)
{
ergebnis[position] = worte[i];
position++;
}
}
return ergebnis;
}
public static void main(String[] args)
{
String[][] daten;
String[] ergebnis;
// Testdaten:
daten = new String[][]{{"ABCD", "ABCDE", "QWER", "QWERTY"}, // "ABCDE"
{"ABCD", "ABCDE", "QWER", "QWERT", "ABCDEF"}, // "ABCDE" und "QWERT"
{"ASDF", "QWER", "YXCV"}}; // Alle gleich lang - kein zweitlängstes - keine Ausgabe
for (int i = 0; i < daten.length; i++)
{
for (int j = 0; j < daten[i].length; j++)
{
System.out.print(daten[i][j] + " ");
}
System.out.println(":");
ergebnis = zweitlaengsteStrings(daten[i]);
for (int j = 0; j < ergebnis.length; j++)
{
System.out.print(ergebnis[j] + " ");
}
System.out.println();
System.out.println();
}
}
}
| WINDOWS-1252 | Java | 2,356 | java | ZweitlaengsteStrings.java | Java | [
{
"context": " sind.\n *\n * Die Lösung basiert auf einer Idee von Herrn Auer (PIT-Student, 2012).\n */\npublic class Zweitlaengs",
"end": 518,
"score": 0.9923459887504578,
"start": 508,
"tag": "NAME",
"value": "Herrn Auer"
}
] | null | [] | package aufgabe09;
/*
* zweitlaengsteStrings:
*
* Schreiben Sie ein Unterprogramm an das
* eine beliebige Anzahl von Strings übergeben werden kann und
* das die Strings mit der zweitgrößten Länge zurückliefert
* (dies können auch mehrere sein).
*
* Beispiel:
* zweitlaengsteStrings("ABCD", "ABCDE", "QWER", "QWERT")
* liefert als Ergebnis ein Array mit den Elementen “ABCD“ und “QWER“,
* weil das die Strings mit der zweitgrößten Länge (4) sind.
*
* Die Lösung basiert auf einer Idee von <NAME> (PIT-Student, 2012).
*/
public class ZweitlaengsteStrings
{
public static String[] zweitlaengsteStrings(String[] worte)
{
String[] ergebnis;
int laenge = 0;
int laengste = 0;
int zweitlaengste = 0;
int anzahl;
int position;
// zweitgrößte Länge suchen
for (int i = 0; i < worte.length; i++)
{
laenge = worte[i].length();
if (laenge > laengste)
{
zweitlaengste = laengste;
laengste = laenge;
}
else if ((laenge < laengste) && (laenge > zweitlaengste))
{
zweitlaengste = laenge;
}
}
// Anzahl der Strings mit der zweitgrößten Länge suchen
anzahl = 0;
for (int i = 0; i < worte.length; i++)
{
if (worte[i].length() == zweitlaengste)
{
anzahl++;
}
}
// Das Ergebnis-Array auf die richtige Größe bringen
ergebnis = new String[anzahl];
// Die zweitlängsten Strings in das Array einfüllen
position = 0;
for (int i = 0; i < worte.length; i++)
{
if (worte[i].length() == zweitlaengste)
{
ergebnis[position] = worte[i];
position++;
}
}
return ergebnis;
}
public static void main(String[] args)
{
String[][] daten;
String[] ergebnis;
// Testdaten:
daten = new String[][]{{"ABCD", "ABCDE", "QWER", "QWERTY"}, // "ABCDE"
{"ABCD", "ABCDE", "QWER", "QWERT", "ABCDEF"}, // "ABCDE" und "QWERT"
{"ASDF", "QWER", "YXCV"}}; // Alle gleich lang - kein zweitlängstes - keine Ausgabe
for (int i = 0; i < daten.length; i++)
{
for (int j = 0; j < daten[i].length; j++)
{
System.out.print(daten[i][j] + " ");
}
System.out.println(":");
ergebnis = zweitlaengsteStrings(daten[i]);
for (int j = 0; j < ergebnis.length; j++)
{
System.out.print(ergebnis[j] + " ");
}
System.out.println();
System.out.println();
}
}
}
| 2,352 | 0.608079 | 0.600344 | 100 | 22.27 | 22.633982 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.59 | false | false | 13 |
ec7230499af65ec31a6bec13a1986c6791951544 | 22,711,787,074,970 | d17fa39e26489e3e4d63253bd8fc933b4449d193 | /src/com/scsvision/gather/middleware/sqlserver/model/rowmapper/CmsRowMapper.java | eed22224c8d142c3b5832a7f1ddcbd7ab6e7ed54 | [] | no_license | maninyellow/gather-middleware | https://github.com/maninyellow/gather-middleware | 24420fc64d7fe3dc176415a683d07bdfb5c228b3 | 972aa917e67bd46bfde7c44e4e1c8cd39475cb24 | refs/heads/master | 2021-01-10T07:50:47.716000 | 2016-01-25T06:55:30 | 2016-01-25T06:55:30 | 50,332,229 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.scsvision.gather.middleware.sqlserver.model.rowmapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.springframework.jdbc.core.RowMapper;
import com.scsvision.gather.middleware.sqlserver.model.Cms;
/**
* CmsRowMapper
*
* @author wangbinyu
* <p />
* Create at 2014 下午2:01:03
*/
public class CmsRowMapper implements RowMapper {
private static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
@Override
public Cms mapRow(ResultSet rs, int rowNum) throws SQLException {
Cms cms = new Cms();
cms.setStandardNumber(rs.getString("DeviceID"));
cms.setStatus(rs.getInt("iStatus"));
cms.setFaultMessage(rs.getString("iFaultMessage"));
cms.setDispText(rs.getString("PlayItemText"));
cms.setRecTime(rs.getTimestamp("ChgDate") != null ? sdf.format(rs
.getTimestamp("ChgDate")) : sdf.format(new Timestamp(System
.currentTimeMillis())));
cms.setFontName(rs.getString("FontName"));
cms.setSize(rs.getInt("FontSize"));
cms.setDispTime(rs.getInt("Stay") + "");
cms.setColor(rs.getInt("ForeColor"));
return cms;
}
}
| UTF-8 | Java | 1,183 | java | CmsRowMapper.java | Java | [
{
"context": "ver.model.Cms;\n\n/**\n * CmsRowMapper\n * \n * @author wangbinyu\n * <p />\n * Create at 2014 下午2:01",
"end": 342,
"score": 0.9982202053070068,
"start": 333,
"tag": "USERNAME",
"value": "wangbinyu"
}
] | null | [] | package com.scsvision.gather.middleware.sqlserver.model.rowmapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import org.springframework.jdbc.core.RowMapper;
import com.scsvision.gather.middleware.sqlserver.model.Cms;
/**
* CmsRowMapper
*
* @author wangbinyu
* <p />
* Create at 2014 下午2:01:03
*/
public class CmsRowMapper implements RowMapper {
private static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
@Override
public Cms mapRow(ResultSet rs, int rowNum) throws SQLException {
Cms cms = new Cms();
cms.setStandardNumber(rs.getString("DeviceID"));
cms.setStatus(rs.getInt("iStatus"));
cms.setFaultMessage(rs.getString("iFaultMessage"));
cms.setDispText(rs.getString("PlayItemText"));
cms.setRecTime(rs.getTimestamp("ChgDate") != null ? sdf.format(rs
.getTimestamp("ChgDate")) : sdf.format(new Timestamp(System
.currentTimeMillis())));
cms.setFontName(rs.getString("FontName"));
cms.setSize(rs.getInt("FontSize"));
cms.setDispTime(rs.getInt("Stay") + "");
cms.setColor(rs.getInt("ForeColor"));
return cms;
}
}
| 1,183 | 0.725191 | 0.717557 | 40 | 28.475 | 22.179932 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.425 | false | false | 13 |
aaa762ede660a53eabf53186adc0cdd51f470552 | 25,065,429,152,039 | 887f9d64b64d8c77c1ac1631936fa66d5326c2ff | /src/main/java/com/users/angular/service/UserServiceImpl.java | f29dee99d916e31ff3a0891d3e911aae214834a1 | [] | no_license | mangelino997/app1Full-backend | https://github.com/mangelino997/app1Full-backend | bac476846eb9b1980fd3812bcbe75efd1daf6a9d | af92b7694012b3108de970b5f5c4238942bb7f89 | refs/heads/master | 2022-11-27T22:04:57.945000 | 2020-08-08T02:14:18 | 2020-08-08T02:14:18 | 285,955,761 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.users.angular.service;
/**
*
* @author Marcio
*/
import com.users.angular.dao.IRolDAO;
import com.users.angular.dao.IUsuarioDAO;
import com.users.angular.model.Rol;
import com.users.angular.model.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;
@Service("userDetailsService")
@Transactional // con esto nos aseguramos que la consulta al repo usuario nos traiga los roles (que habiamos declarados como lazy)
public class UserServiceImpl implements UserService {
@Autowired
private IRolDAO roleRepository;
@Autowired
private IUsuarioDAO userRepository;
// sobreescribe el metodo de UserDetails para agregarle roles, y demás info del usuario
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Set grantList = new HashSet();
/* busca al usuario en la DB y si no lo encuentra lanza la excepcion 'UsernameNotFoundException' */
Usuario usuario = userRepository.findByUsername(username);
if (usuario == null) {
throw new UsernameNotFoundException("Invalid username or password");
}
usuario.getRoles().forEach(role -> {
grantList.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
});
return new User(usuario.getUsername(), usuario.getPassword(), grantList);
}
// METODOS ABSTRACTOS QU SOLICITA LA CLASE
@Override
public Usuario getUser(long id) {
return userRepository.findById(id);
}
@Override
public Usuario save(Usuario user) {
Rol userRole = roleRepository.findByName("USER");
Set<Rol> roles = new HashSet<>();
roles.add(userRole);
Usuario userToSave = Usuario.builder().username(user.getUsername()).password(user.getPassword()).roles(roles).build();
return userRepository.save(userToSave);
}
}
| UTF-8 | Java | 2,340 | java | UserServiceImpl.java | Java | [
{
"context": "ckage com.users.angular.service;\n/**\n *\n * @author Marcio\n */\nimport com.users.angular.dao.IRolDAO;\nimport ",
"end": 59,
"score": 0.9997656941413879,
"start": 53,
"tag": "NAME",
"value": "Marcio"
},
{
"context": " Usuario userToSave = Usuario.builder().username(u... | null | [] | package com.users.angular.service;
/**
*
* @author Marcio
*/
import com.users.angular.dao.IRolDAO;
import com.users.angular.dao.IUsuarioDAO;
import com.users.angular.model.Rol;
import com.users.angular.model.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;
@Service("userDetailsService")
@Transactional // con esto nos aseguramos que la consulta al repo usuario nos traiga los roles (que habiamos declarados como lazy)
public class UserServiceImpl implements UserService {
@Autowired
private IRolDAO roleRepository;
@Autowired
private IUsuarioDAO userRepository;
// sobreescribe el metodo de UserDetails para agregarle roles, y demás info del usuario
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Set grantList = new HashSet();
/* busca al usuario en la DB y si no lo encuentra lanza la excepcion 'UsernameNotFoundException' */
Usuario usuario = userRepository.findByUsername(username);
if (usuario == null) {
throw new UsernameNotFoundException("Invalid username or password");
}
usuario.getRoles().forEach(role -> {
grantList.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
});
return new User(usuario.getUsername(), usuario.getPassword(), grantList);
}
// METODOS ABSTRACTOS QU SOLICITA LA CLASE
@Override
public Usuario getUser(long id) {
return userRepository.findById(id);
}
@Override
public Usuario save(Usuario user) {
Rol userRole = roleRepository.findByName("USER");
Set<Rol> roles = new HashSet<>();
roles.add(userRole);
Usuario userToSave = Usuario.builder().username(user.getUsername()).password(<PASSWORD>()).roles(roles).build();
return userRepository.save(userToSave);
}
}
| 2,334 | 0.733219 | 0.733219 | 62 | 36.725807 | 32.550789 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
ff30a3a6efd621b38d5c0d57ef3e8dad2d95336b | 12,910,671,710,524 | f61e8e84f4ff6fa86eb66378aff3baf549fe888e | /Song.java | fdf4bee8201137a57da36cbd9951af2a811090e6 | [] | no_license | carlfsmithiii/java_console_song_playlist | https://github.com/carlfsmithiii/java_console_song_playlist | 0b60da882829d8a97175a830ebde0b43381cbbb4 | 39deb53f4911a1dfa936d131abaf26b897572480 | refs/heads/master | 2020-04-17T19:16:51.423000 | 2019-01-22T17:52:03 | 2019-01-22T17:52:03 | 166,860,353 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.time.Duration;
import java.util.Objects;
public class Song {
private String title;
private Duration duration;
public Song(String title, Duration duration) {
this.title = title;
this.duration = duration;
}
public Song(String title, int minutes, int seconds) {
this(title, Duration.ofMinutes(minutes).plusSeconds(seconds));
}
public String getTitle() {
return this.title;
}
public Duration getDuration() {
return this.duration;
}
public void display() {
System.out.printf("Song title: %s\t\tDuration: %d:%02d\n", this.title, this.duration.toMinutesPart(),
this.duration.toSecondsPart());
}
@Override
public boolean equals(Object otherObj) {
if (otherObj == this)
return true;
if (otherObj == null) {
return false;
}
if (getClass() != otherObj.getClass()) {
return false;
}
Song otherSong = (Song) otherObj;
return Objects.equals(title, otherSong.title) && (this.duration.toMillis() == otherSong.duration.toMillis());
}
@Override
public int hashCode() {
return Objects.hash(title, duration.toMillis());
}
} | UTF-8 | Java | 1,260 | java | Song.java | Java | [] | null | [] | import java.time.Duration;
import java.util.Objects;
public class Song {
private String title;
private Duration duration;
public Song(String title, Duration duration) {
this.title = title;
this.duration = duration;
}
public Song(String title, int minutes, int seconds) {
this(title, Duration.ofMinutes(minutes).plusSeconds(seconds));
}
public String getTitle() {
return this.title;
}
public Duration getDuration() {
return this.duration;
}
public void display() {
System.out.printf("Song title: %s\t\tDuration: %d:%02d\n", this.title, this.duration.toMinutesPart(),
this.duration.toSecondsPart());
}
@Override
public boolean equals(Object otherObj) {
if (otherObj == this)
return true;
if (otherObj == null) {
return false;
}
if (getClass() != otherObj.getClass()) {
return false;
}
Song otherSong = (Song) otherObj;
return Objects.equals(title, otherSong.title) && (this.duration.toMillis() == otherSong.duration.toMillis());
}
@Override
public int hashCode() {
return Objects.hash(title, duration.toMillis());
}
} | 1,260 | 0.598413 | 0.596825 | 49 | 24.734694 | 25.52132 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.510204 | false | false | 13 |
be621a42aa9bfd492c4d7cb543b290ae1b7e3163 | 6,399,501,288,715 | 3982cc0a73455f8ce32dba330581b4a809988a17 | /platform/lang-impl/src/com/intellij/ide/projectView/impl/ShowModulesAction.java | 6430732021a7c1bc0c81f6b9ff30ee5a3574db7d | [
"Apache-2.0"
] | permissive | lshain-android-source/tools-idea | https://github.com/lshain-android-source/tools-idea | 56d754089ebadd689b7d0e6400ef3be4255f6bc6 | b37108d841684bcc2af45a2539b75dd62c4e283c | refs/heads/master | 2016-09-05T22:31:43.471000 | 2014-07-09T07:58:59 | 2014-07-09T07:58:59 | 16,572,470 | 3 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.intellij.ide.projectView.impl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.PlatformUtils;
/**
* Created by IntelliJ IDEA.
* User: anna
* Date: 8/5/11
* Time: 9:33 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class ShowModulesAction extends ToggleAction {
private final Project myProject;
public ShowModulesAction(Project project) {
super(IdeBundle.message("action.show.modules"), IdeBundle.message("action.description.show.modules"),
AllIcons.ObjectBrowser.ShowModules);
myProject = project;
}
@Override
public boolean isSelected(AnActionEvent event) {
return ProjectView.getInstance(myProject).isShowModules(getId());
}
protected abstract String getId();
@Override
public void setSelected(AnActionEvent event, boolean flag) {
final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject);
projectView.setShowModules(flag, getId());
}
@Override
public void update(AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject);
presentation.setVisible(hasModules() && Comparing.strEqual(projectView.getCurrentViewId(), getId()));
}
private static boolean hasModules() {
return PlatformUtils.isIdea() ||
PlatformUtils.isCommunity() ||
PlatformUtils.isFlexIde();
}
}
| UTF-8 | Java | 1,826 | java | ShowModulesAction.java | Java | [
{
"context": "ormUtils;\n\n/**\n* Created by IntelliJ IDEA.\n* User: anna\n* Date: 8/5/11\n* Time: 9:33 PM\n* To change this t",
"end": 504,
"score": 0.9989765286445618,
"start": 500,
"tag": "USERNAME",
"value": "anna"
}
] | null | [] | package com.intellij.ide.projectView.impl;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.util.PlatformUtils;
/**
* Created by IntelliJ IDEA.
* User: anna
* Date: 8/5/11
* Time: 9:33 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class ShowModulesAction extends ToggleAction {
private final Project myProject;
public ShowModulesAction(Project project) {
super(IdeBundle.message("action.show.modules"), IdeBundle.message("action.description.show.modules"),
AllIcons.ObjectBrowser.ShowModules);
myProject = project;
}
@Override
public boolean isSelected(AnActionEvent event) {
return ProjectView.getInstance(myProject).isShowModules(getId());
}
protected abstract String getId();
@Override
public void setSelected(AnActionEvent event, boolean flag) {
final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject);
projectView.setShowModules(flag, getId());
}
@Override
public void update(AnActionEvent e) {
super.update(e);
final Presentation presentation = e.getPresentation();
final ProjectViewImpl projectView = (ProjectViewImpl)ProjectView.getInstance(myProject);
presentation.setVisible(hasModules() && Comparing.strEqual(projectView.getCurrentViewId(), getId()));
}
private static boolean hasModules() {
return PlatformUtils.isIdea() ||
PlatformUtils.isCommunity() ||
PlatformUtils.isFlexIde();
}
}
| 1,826 | 0.761227 | 0.757393 | 55 | 32.200001 | 28.166647 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.6 | false | false | 13 |
b46857398fc58878ec61b3d9dc2f35df14e33f00 | 5,892,695,147,558 | e5cc1ac9dfbd4daced627143375171dc263cff7b | /src/dao/DeckTextDao.java | b5d03973e3fd8a2601d57b9b7b52e580ca30805a | [] | no_license | alpenmilch/MScIT_TeamProject | https://github.com/alpenmilch/MScIT_TeamProject | c70f7d6aa60880fb0d61e03b8c462f9d19637f90 | f152943bf770f798401aa44f6fd42bb4e07c1139 | refs/heads/master | 2020-12-14T13:05:48.385000 | 2020-02-16T20:57:23 | 2020-02-16T20:57:23 | 234,753,480 | 0 | 4 | null | false | 2020-02-16T19:02:14 | 2020-01-18T15:16:24 | 2020-02-16T16:51:09 | 2020-02-16T19:02:13 | 538 | 0 | 4 | 0 | Java | false | false | package dao;
import game.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class DeckTextDao{
String filename;
FileReader fileReader;
public DeckTextDao(String filename){
this.filename = filename;
}
public void initialize() {
try {
this.fileReader = new FileReader(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public DeckModel readDeck(DeckModel deck) {
Scanner scanner = new Scanner(fileReader);
deck.setCategory(readCategory(scanner));
while(scanner.hasNextLine()){
deck.addCard(readCard(scanner));
}
return deck;
}
private String[] readCategory(Scanner scanner){
String[] spl = scanner.nextLine().split(" ");
String[] cate = new String[spl.length-1];
System.arraycopy(spl,1,cate ,0, spl.length-1);
return cate;
}
private CardModel readCard(Scanner scanner){
String name = scanner.next();
int[] values = new int[5];
values[0] = scanner.nextInt();
values[1] = scanner.nextInt();
values[2] = scanner.nextInt();
values[3] = scanner.nextInt();
values[4] = scanner.nextInt();
if(scanner.hasNextLine()){
scanner.nextLine();
}
CardModel card = new Card(name, values);
return card;
}
public void close() {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,637 | java | DeckTextDao.java | Java | [] | null | [] | package dao;
import game.*;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class DeckTextDao{
String filename;
FileReader fileReader;
public DeckTextDao(String filename){
this.filename = filename;
}
public void initialize() {
try {
this.fileReader = new FileReader(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public DeckModel readDeck(DeckModel deck) {
Scanner scanner = new Scanner(fileReader);
deck.setCategory(readCategory(scanner));
while(scanner.hasNextLine()){
deck.addCard(readCard(scanner));
}
return deck;
}
private String[] readCategory(Scanner scanner){
String[] spl = scanner.nextLine().split(" ");
String[] cate = new String[spl.length-1];
System.arraycopy(spl,1,cate ,0, spl.length-1);
return cate;
}
private CardModel readCard(Scanner scanner){
String name = scanner.next();
int[] values = new int[5];
values[0] = scanner.nextInt();
values[1] = scanner.nextInt();
values[2] = scanner.nextInt();
values[3] = scanner.nextInt();
values[4] = scanner.nextInt();
if(scanner.hasNextLine()){
scanner.nextLine();
}
CardModel card = new Card(name, values);
return card;
}
public void close() {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,637 | 0.581552 | 0.575443 | 63 | 24.984127 | 17.287937 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
1e28da13254550b16c1f62e0ebcaad2ebf96f15e | 31,361,851,205,533 | a8b49d64121ab2e54cd8480a03a56fd616b654a3 | /app/src/main/java/com/doublesp/coherence/fragments/GoalPreviewFragment.java | 130780f4dd6b0b4e5e32e3ea13c58c0ba53ff9eb | [
"Apache-2.0"
] | permissive | leoliudeprecated/Coherence | https://github.com/leoliudeprecated/Coherence | 32fb728b0375d3cef93657e72aa9b249b9e965b2 | c3b74afa86141ec8f7d6227433197d8787004741 | refs/heads/master | 2022-05-02T06:46:23.489000 | 2016-12-15T02:26:20 | 2016-12-15T02:26:20 | 77,299,627 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.doublesp.coherence.fragments;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.doublesp.coherence.R;
import com.doublesp.coherence.adapters.IdeasArrayAdapter;
import com.doublesp.coherence.databinding.FragmentGoalPreviewBinding;
import com.doublesp.coherence.interfaces.domain.IdeaInteractorInterface;
import com.doublesp.coherence.interfaces.presentation.GoalDetailActionHandlerInterface;
import com.doublesp.coherence.interfaces.presentation.GoalInteractorInterface;
import com.doublesp.coherence.interfaces.presentation.InjectorInterface;
import com.doublesp.coherence.interfaces.presentation.ViewState;
import com.doublesp.coherence.utils.ImageUtils;
import com.doublesp.coherence.viewmodels.Goal;
import android.content.Context;
import android.content.res.ColorStateList;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import javax.inject.Inject;
import rx.Observer;
public class GoalPreviewFragment extends Fragment {
static final String IDEA_PREVIEW_FRAGMENT_INDEX = "IDEA_PREVIEW_FRAGMENT_INDEX";
FragmentGoalPreviewBinding binding;
int mPos;
@Inject
GoalDetailActionHandlerInterface mActionHandler;
@Inject
GoalInteractorInterface mGoalInteractor;
@Inject
IdeaInteractorInterface mIdeaInteractor;
IdeasArrayAdapter mIdeasArrayAdapter;
public GoalPreviewFragment() {
// Required empty public constructor
}
public static GoalPreviewFragment newInstance(int pos) {
GoalPreviewFragment fragment = new GoalPreviewFragment();
Bundle args = new Bundle();
args.putInt(IDEA_PREVIEW_FRAGMENT_INDEX, pos);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPos = getArguments().getInt(IDEA_PREVIEW_FRAGMENT_INDEX);
Goal goal = mGoalInteractor.getGoalAtPos(mPos);
mIdeasArrayAdapter = new IdeasArrayAdapter(mIdeaInteractor, goal.getId());
mGoalInteractor.loadDetailsForGoalAtPos(mPos);
mGoalInteractor.subscribeToGoalStateChange(new Observer<ViewState>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ViewState viewState) {
switch (viewState.getState()) {
case R.id.state_loaded:
switch (viewState.getOperation()) {
case UPDATE:
if (viewState.getStart() != -1) {
return;
}
Goal updatedGoal = mGoalInteractor.getGoalAtPos(mPos);
mIdeasArrayAdapter.setGoalId(updatedGoal.getId());
mIdeasArrayAdapter.notifyDataSetChanged();
binding.setViewModel(updatedGoal);
binding.executePendingBindings();
}
}
}
});
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goal_preview, container,
false);
binding.setHandler(mActionHandler);
binding.rvGoalPreviewIdeas.setLayoutManager(new LinearLayoutManager(getContext()));
binding.rvGoalPreviewIdeas.setAdapter(mIdeasArrayAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL);
dividerItemDecoration.setDrawable(
ContextCompat.getDrawable(getContext(), R.drawable.line_divider_edge_to_edge));
binding.rvGoalPreviewIdeas.addItemDecoration(dividerItemDecoration);
binding.nsvGoalPreviewIdeasContainer.setNestedScrollingEnabled(false);
return binding.getRoot();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Goal viewModel = mGoalInteractor.getGoalAtPos(mPos);
binding.setPos(mPos);
binding.setViewModel(viewModel);
if (viewModel.getSubTitle() == null) {
binding.ivGoalPreviewSubTitle.setAlpha(0.0f);
binding.tvGoalPreviewSubTitle.setAlpha(0.0f);
} else {
binding.ivGoalPreviewSubTitle.setAlpha(0.5f);
binding.tvGoalPreviewSubTitle.setAlpha(1.0f);
}
SimpleTarget target = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap,
GlideAnimation<? super Bitmap> glideAnimation) {
// insert the bitmap into the image view
binding.ivIdeaBackgroundImage.setImageBitmap(bitmap);
// Use generate() method from the Palette API to get the vibrant color from the
// bitmap
// Set the result as the background color
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// Get the "vibrant" color swatch based on the bitmap
Palette.Swatch vibrant = palette.getVibrantSwatch();
if (vibrant != null) {
int color = vibrant.getRgb();
int colorWithAlpha = ImageUtils.getTransparentColor(color);
ColorStateList colorStateList = ColorStateList.valueOf(color);
binding.tvGoalIndex.setBackgroundTintList(colorStateList);
binding.tvTitle.setTextColor(color);
binding.tvGoalPreviewSubTitle.setTextColor(colorWithAlpha);
binding.ivGoalPreviewSubTitle.setImageTintList(colorStateList);
}
}
});
}
};
if (viewModel.getImageUrl() != null) {
Glide.with(binding.ivIdeaBackgroundImage.getContext())
.load(viewModel.getImageUrl())
.asBitmap()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(target);
}
binding.executePendingBindings();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof InjectorInterface) {
InjectorInterface injector = (InjectorInterface) context;
injector.inject(this);
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDetach() {
super.onDetach();
}
}
| UTF-8 | Java | 7,837 | java | GoalPreviewFragment.java | Java | [] | null | [] | package com.doublesp.coherence.fragments;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.doublesp.coherence.R;
import com.doublesp.coherence.adapters.IdeasArrayAdapter;
import com.doublesp.coherence.databinding.FragmentGoalPreviewBinding;
import com.doublesp.coherence.interfaces.domain.IdeaInteractorInterface;
import com.doublesp.coherence.interfaces.presentation.GoalDetailActionHandlerInterface;
import com.doublesp.coherence.interfaces.presentation.GoalInteractorInterface;
import com.doublesp.coherence.interfaces.presentation.InjectorInterface;
import com.doublesp.coherence.interfaces.presentation.ViewState;
import com.doublesp.coherence.utils.ImageUtils;
import com.doublesp.coherence.viewmodels.Goal;
import android.content.Context;
import android.content.res.ColorStateList;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import javax.inject.Inject;
import rx.Observer;
public class GoalPreviewFragment extends Fragment {
static final String IDEA_PREVIEW_FRAGMENT_INDEX = "IDEA_PREVIEW_FRAGMENT_INDEX";
FragmentGoalPreviewBinding binding;
int mPos;
@Inject
GoalDetailActionHandlerInterface mActionHandler;
@Inject
GoalInteractorInterface mGoalInteractor;
@Inject
IdeaInteractorInterface mIdeaInteractor;
IdeasArrayAdapter mIdeasArrayAdapter;
public GoalPreviewFragment() {
// Required empty public constructor
}
public static GoalPreviewFragment newInstance(int pos) {
GoalPreviewFragment fragment = new GoalPreviewFragment();
Bundle args = new Bundle();
args.putInt(IDEA_PREVIEW_FRAGMENT_INDEX, pos);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPos = getArguments().getInt(IDEA_PREVIEW_FRAGMENT_INDEX);
Goal goal = mGoalInteractor.getGoalAtPos(mPos);
mIdeasArrayAdapter = new IdeasArrayAdapter(mIdeaInteractor, goal.getId());
mGoalInteractor.loadDetailsForGoalAtPos(mPos);
mGoalInteractor.subscribeToGoalStateChange(new Observer<ViewState>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(ViewState viewState) {
switch (viewState.getState()) {
case R.id.state_loaded:
switch (viewState.getOperation()) {
case UPDATE:
if (viewState.getStart() != -1) {
return;
}
Goal updatedGoal = mGoalInteractor.getGoalAtPos(mPos);
mIdeasArrayAdapter.setGoalId(updatedGoal.getId());
mIdeasArrayAdapter.notifyDataSetChanged();
binding.setViewModel(updatedGoal);
binding.executePendingBindings();
}
}
}
});
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goal_preview, container,
false);
binding.setHandler(mActionHandler);
binding.rvGoalPreviewIdeas.setLayoutManager(new LinearLayoutManager(getContext()));
binding.rvGoalPreviewIdeas.setAdapter(mIdeasArrayAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL);
dividerItemDecoration.setDrawable(
ContextCompat.getDrawable(getContext(), R.drawable.line_divider_edge_to_edge));
binding.rvGoalPreviewIdeas.addItemDecoration(dividerItemDecoration);
binding.nsvGoalPreviewIdeasContainer.setNestedScrollingEnabled(false);
return binding.getRoot();
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Goal viewModel = mGoalInteractor.getGoalAtPos(mPos);
binding.setPos(mPos);
binding.setViewModel(viewModel);
if (viewModel.getSubTitle() == null) {
binding.ivGoalPreviewSubTitle.setAlpha(0.0f);
binding.tvGoalPreviewSubTitle.setAlpha(0.0f);
} else {
binding.ivGoalPreviewSubTitle.setAlpha(0.5f);
binding.tvGoalPreviewSubTitle.setAlpha(1.0f);
}
SimpleTarget target = new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap,
GlideAnimation<? super Bitmap> glideAnimation) {
// insert the bitmap into the image view
binding.ivIdeaBackgroundImage.setImageBitmap(bitmap);
// Use generate() method from the Palette API to get the vibrant color from the
// bitmap
// Set the result as the background color
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
@Override
public void onGenerated(Palette palette) {
// Get the "vibrant" color swatch based on the bitmap
Palette.Swatch vibrant = palette.getVibrantSwatch();
if (vibrant != null) {
int color = vibrant.getRgb();
int colorWithAlpha = ImageUtils.getTransparentColor(color);
ColorStateList colorStateList = ColorStateList.valueOf(color);
binding.tvGoalIndex.setBackgroundTintList(colorStateList);
binding.tvTitle.setTextColor(color);
binding.tvGoalPreviewSubTitle.setTextColor(colorWithAlpha);
binding.ivGoalPreviewSubTitle.setImageTintList(colorStateList);
}
}
});
}
};
if (viewModel.getImageUrl() != null) {
Glide.with(binding.ivIdeaBackgroundImage.getContext())
.load(viewModel.getImageUrl())
.asBitmap()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(target);
}
binding.executePendingBindings();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof InjectorInterface) {
InjectorInterface injector = (InjectorInterface) context;
injector.inject(this);
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDetach() {
super.onDetach();
}
}
| 7,837 | 0.624856 | 0.62307 | 194 | 39.396908 | 27.368658 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.520619 | false | false | 13 |
22a46464c837227a4f956a9d579bb3f98345b3e9 | 3,616,362,481,108 | 855596c47ee135ab414c9c877886df26a97cce2e | /src/main/java/com/diluv/confluencia/database/record/FileProcessingStatus.java | 36b765c5ba1d8c5db1637c101ec1be8a7b819996 | [] | no_license | Diluv/Confluencia | https://github.com/Diluv/Confluencia | ea52d473e08d579975fa3e22fea26dbd02759422 | e862beef2b9083b9aa7069510818cc8dfa2f77d9 | refs/heads/main | 2023-03-10T04:46:46.321000 | 2023-03-05T00:54:24 | 2023-03-05T00:54:24 | 234,034,351 | 0 | 0 | null | false | 2023-03-01T17:57:00 | 2020-01-15T08:29:21 | 2021-08-06T10:58:37 | 2023-03-01T17:56:56 | 945 | 0 | 0 | 7 | Java | false | false | package com.diluv.confluencia.database.record;
public enum FileProcessingStatus {
PENDING,
RUNNING,
SUCCESS,
FAILED_UNSPECIFIED,
FAILED_INTERNAL_SERVER_ERROR,
FAILED_MALWARE_DETECTED,
FAILED_MALWARE_SCAN_TIMEOUT,
FAILED_INVALID_FILE
}
| UTF-8 | Java | 268 | java | FileProcessingStatus.java | Java | [] | null | [] | package com.diluv.confluencia.database.record;
public enum FileProcessingStatus {
PENDING,
RUNNING,
SUCCESS,
FAILED_UNSPECIFIED,
FAILED_INTERNAL_SERVER_ERROR,
FAILED_MALWARE_DETECTED,
FAILED_MALWARE_SCAN_TIMEOUT,
FAILED_INVALID_FILE
}
| 268 | 0.727612 | 0.727612 | 12 | 21.333334 | 13.53596 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 13 |
3293fa6a38d7b38d9da4ea165a85516f04194c88 | 9,869,834,858,609 | cbff6cf61924a0b7d13051b94e7723916b13bec8 | /app/src/main/java/tw/binary/dipper/provider/GAEContentProvider.java | 6a731dc09dda2f5d9442b1540123130938c0abf7 | [] | no_license | arasu007/Campfile | https://github.com/arasu007/Campfile | af89bc7498a0cb6f3dbdac608b3f5cd40af2aeff | ca5f64a4a83862cd93303a8da29289ab74473b5a | refs/heads/master | 2018-01-14T15:56:09.441000 | 2015-06-17T02:27:47 | 2015-06-17T02:27:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package tw.binary.dipper.provider;/* Created by eason on 2015/5/20. */
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import tw.binary.dipper.api.myResourceApi.MyResourceApi;
import tw.binary.dipper.api.myResourceApi.model.CollectionResponseMyResource;
import tw.binary.dipper.api.myResourceApi.model.MyResource;
/**
* Created by eason on 2015/5/7.
*/
public class GAEContentProvider extends ContentProvider {
public static final Uri CONTENT_URI_MYRESOURCE = Uri.parse("content://tw.binary.dipper.api/myresource");
private static final int MYRESOURCE_ALLROWS = 1;
private static final int MYRESOURCE_ONEROW = 2;
private static final UriMatcher uriMatcher;
private MyResourceApi myApiService = null;
private String nextPageToken = "";
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("tw.binary.dipper.api", "myresource", MYRESOURCE_ALLROWS);
uriMatcher.addURI("tw.binary.dipper.api", "myresource/#", MYRESOURCE_ONEROW);
}
@Override
public boolean onCreate() {
if (myApiService == null) { // Only do this once
MyResourceApi.Builder builder = new MyResourceApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2:8080 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("https://graceful-design-89523.appspot.com/_ah/api/")
//.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
myApiService = builder.build();
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
ArrayList<MyResource> myResources;
ArrayList<MyResource> myMergeResources = new ArrayList<>();
MatrixCursor myResourceCursor = null;
switch (uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
try {
for (String selectionArg : selectionArgs) {
MyResourceApi.ListByUser api = myApiService.listByUser(selectionArg);
//api.setCursor(nextPageToken);
int pageLimit = 100;
api.setLimit(pageLimit); //設定最大讀取筆數
CollectionResponseMyResource feed = api.execute();
myResources = (ArrayList<MyResource>) feed.getItems();
nextPageToken = feed.getNextPageToken(); //TODO 是否可再續查?
if (myResources != null)
myMergeResources.addAll(myResources); //結果Merge在一起
}
} catch (IOException e) {
e.getMessage();
}
break;
case MYRESOURCE_ONEROW:
//Log.i("TAG", "selectionArgs = " + selectionArgs[0]);
//讀取資料
try {
MyResourceApi.ListByUser api = myApiService.listByUser(uri.getLastPathSegment());
api.setCursor(nextPageToken);
int pageLimit = 100;
api.setLimit(pageLimit); //設定最大讀取筆數
CollectionResponseMyResource feed = api.execute();
myMergeResources = (ArrayList<MyResource>) feed.getItems();
nextPageToken = feed.getNextPageToken();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
//產生Cursor所需欄位
//這個cursor只有兩個欄位,一個是_id,一個是Json String
String[] columns = new String[]{"_id", "myresource"};//ListView需要一個固定欄位_id
//Field[] fields = MyResource.class.getDeclaredFields();
//利用class的Attribute作為欄位
/*for (Field field : fields) {
columns.add(field.getName());
//field.getType().getSimpleName()
}*/
//產生值
//Param1 欄位資料, Param2 row的筆數
if (myMergeResources != null) {
//設定欄位名稱
//一個固定Object欄位名稱,看有幾筆Object
myResourceCursor = new MatrixCursor(columns);//, myMergeResources.size());
for (int i = 0; i < myMergeResources.size(); i++) {
myResourceCursor.addRow(new Object[]{i + 1, new Gson().toJson(myMergeResources.get(i))});
}
myResourceCursor.setNotificationUri(getContext().getContentResolver(), uri);
return myResourceCursor;
} else {
return null;
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Field[] fields = MyResource.class.getDeclaredFields();
MyResource myResource = new MyResource();
//產生ObjectRelationMapping所需資料
for (Field field : fields) {
myResource.put(field.getName(), values.get(field.getName()));
}
switch (uriMatcher.match(uri)) {
//多筆更新
case MYRESOURCE_ALLROWS:
//單筆更新
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Insert api = myApiService.insert(myResource);
api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
Uri insertUri = ContentUris.withAppendedId(uri, 0);
getContext().getContentResolver().notifyChange(insertUri, null);
return insertUri;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Field[] fields = MyResource.class.getDeclaredFields();
MyResource myResource = new MyResource();
MyResource result = null;
//產生ObjectRelationMapping所需資料
for (Field field : fields) {
myResource.put(field.getName(), values.get(field.getName()));
}
switch (uriMatcher.match(uri)) {
//多筆更新
case MYRESOURCE_ALLROWS:
try {
MyResourceApi.Update api = myApiService.update(selectionArgs[0], myResource);
result = api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
//單筆更新
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Update api = myApiService.update(uri.getLastPathSegment(), myResource);
result = api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
//一般程序
getContext().getContentResolver().notifyChange(uri, null);
return result != null ? 1 : 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
switch (uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
try {
for (String selectionArg : selectionArgs) {
MyResourceApi.Remove api = myApiService.remove(selectionArg);
api.execute();
}
} catch (IOException e) {
e.getMessage();
}
break;
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Remove api = myApiService.remove(uri.getLastPathSegment());
api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return uriMatcher.match(uri) == MYRESOURCE_ALLROWS ? selectionArgs.length : 1;
}
/*private String getTableName(Uri uri) {
switch(uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
case MYRESOURCE_ONEROW:
return "MyResource";
}
return null;
}*/
@Override
public String getType(Uri uri) {
return null;
}
}
/*
String[] columns = new String[] { "_id", "item", "description" };
MatrixCursor matrixCursor= new MatrixCursor(columns);
startManagingCursor(matrixCursor); //调用这个方法,就是将获得的Cursor对象交与Activity 来管理,这样Cursor对象的生命周期便能与当前的Activity自动同步
matrixCursor.addRow(new Object[] { 1, "Item A", "...." });
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.layout_row, matrixCursor, ...);
setListAdapter(adapter);
*/ | UTF-8 | Java | 10,424 | java | GAEContentProvider.java | Java | [
{
"context": "package tw.binary.dipper.provider;/* Created by eason on 2015/5/20. */\n\nimport android.content.ContentP",
"end": 53,
"score": 0.965583324432373,
"start": 48,
"tag": "USERNAME",
"value": "eason"
},
{
"context": "myResourceApi.model.MyResource;\n\n/**\n * Created by eas... | null | [] | package tw.binary.dipper.provider;/* Created by eason on 2015/5/20. */
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import tw.binary.dipper.api.myResourceApi.MyResourceApi;
import tw.binary.dipper.api.myResourceApi.model.CollectionResponseMyResource;
import tw.binary.dipper.api.myResourceApi.model.MyResource;
/**
* Created by eason on 2015/5/7.
*/
public class GAEContentProvider extends ContentProvider {
public static final Uri CONTENT_URI_MYRESOURCE = Uri.parse("content://tw.binary.dipper.api/myresource");
private static final int MYRESOURCE_ALLROWS = 1;
private static final int MYRESOURCE_ONEROW = 2;
private static final UriMatcher uriMatcher;
private MyResourceApi myApiService = null;
private String nextPageToken = "";
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI("tw.binary.dipper.api", "myresource", MYRESOURCE_ALLROWS);
uriMatcher.addURI("tw.binary.dipper.api", "myresource/#", MYRESOURCE_ONEROW);
}
@Override
public boolean onCreate() {
if (myApiService == null) { // Only do this once
MyResourceApi.Builder builder = new MyResourceApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2:8080 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("https://graceful-design-89523.appspot.com/_ah/api/")
//.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
myApiService = builder.build();
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
ArrayList<MyResource> myResources;
ArrayList<MyResource> myMergeResources = new ArrayList<>();
MatrixCursor myResourceCursor = null;
switch (uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
try {
for (String selectionArg : selectionArgs) {
MyResourceApi.ListByUser api = myApiService.listByUser(selectionArg);
//api.setCursor(nextPageToken);
int pageLimit = 100;
api.setLimit(pageLimit); //設定最大讀取筆數
CollectionResponseMyResource feed = api.execute();
myResources = (ArrayList<MyResource>) feed.getItems();
nextPageToken = feed.getNextPageToken(); //TODO 是否可再續查?
if (myResources != null)
myMergeResources.addAll(myResources); //結果Merge在一起
}
} catch (IOException e) {
e.getMessage();
}
break;
case MYRESOURCE_ONEROW:
//Log.i("TAG", "selectionArgs = " + selectionArgs[0]);
//讀取資料
try {
MyResourceApi.ListByUser api = myApiService.listByUser(uri.getLastPathSegment());
api.setCursor(nextPageToken);
int pageLimit = 100;
api.setLimit(pageLimit); //設定最大讀取筆數
CollectionResponseMyResource feed = api.execute();
myMergeResources = (ArrayList<MyResource>) feed.getItems();
nextPageToken = feed.getNextPageToken();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
//產生Cursor所需欄位
//這個cursor只有兩個欄位,一個是_id,一個是Json String
String[] columns = new String[]{"_id", "myresource"};//ListView需要一個固定欄位_id
//Field[] fields = MyResource.class.getDeclaredFields();
//利用class的Attribute作為欄位
/*for (Field field : fields) {
columns.add(field.getName());
//field.getType().getSimpleName()
}*/
//產生值
//Param1 欄位資料, Param2 row的筆數
if (myMergeResources != null) {
//設定欄位名稱
//一個固定Object欄位名稱,看有幾筆Object
myResourceCursor = new MatrixCursor(columns);//, myMergeResources.size());
for (int i = 0; i < myMergeResources.size(); i++) {
myResourceCursor.addRow(new Object[]{i + 1, new Gson().toJson(myMergeResources.get(i))});
}
myResourceCursor.setNotificationUri(getContext().getContentResolver(), uri);
return myResourceCursor;
} else {
return null;
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Field[] fields = MyResource.class.getDeclaredFields();
MyResource myResource = new MyResource();
//產生ObjectRelationMapping所需資料
for (Field field : fields) {
myResource.put(field.getName(), values.get(field.getName()));
}
switch (uriMatcher.match(uri)) {
//多筆更新
case MYRESOURCE_ALLROWS:
//單筆更新
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Insert api = myApiService.insert(myResource);
api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
Uri insertUri = ContentUris.withAppendedId(uri, 0);
getContext().getContentResolver().notifyChange(insertUri, null);
return insertUri;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
Field[] fields = MyResource.class.getDeclaredFields();
MyResource myResource = new MyResource();
MyResource result = null;
//產生ObjectRelationMapping所需資料
for (Field field : fields) {
myResource.put(field.getName(), values.get(field.getName()));
}
switch (uriMatcher.match(uri)) {
//多筆更新
case MYRESOURCE_ALLROWS:
try {
MyResourceApi.Update api = myApiService.update(selectionArgs[0], myResource);
result = api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
//單筆更新
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Update api = myApiService.update(uri.getLastPathSegment(), myResource);
result = api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
//一般程序
getContext().getContentResolver().notifyChange(uri, null);
return result != null ? 1 : 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
switch (uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
try {
for (String selectionArg : selectionArgs) {
MyResourceApi.Remove api = myApiService.remove(selectionArg);
api.execute();
}
} catch (IOException e) {
e.getMessage();
}
break;
case MYRESOURCE_ONEROW:
try {
MyResourceApi.Remove api = myApiService.remove(uri.getLastPathSegment());
api.execute();
} catch (IOException e) {
e.getMessage();
}
break;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return uriMatcher.match(uri) == MYRESOURCE_ALLROWS ? selectionArgs.length : 1;
}
/*private String getTableName(Uri uri) {
switch(uriMatcher.match(uri)) {
case MYRESOURCE_ALLROWS:
case MYRESOURCE_ONEROW:
return "MyResource";
}
return null;
}*/
@Override
public String getType(Uri uri) {
return null;
}
}
/*
String[] columns = new String[] { "_id", "item", "description" };
MatrixCursor matrixCursor= new MatrixCursor(columns);
startManagingCursor(matrixCursor); //调用这个方法,就是将获得的Cursor对象交与Activity 来管理,这样Cursor对象的生命周期便能与当前的Activity自动同步
matrixCursor.addRow(new Object[] { 1, "Item A", "...." });
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.layout_row, matrixCursor, ...);
setListAdapter(adapter);
*/ | 10,424 | 0.573949 | 0.568497 | 259 | 37.953667 | 28.847986 | 127 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.583012 | false | false | 13 |
b5fd0a30423e402d3597f2cdbc26756bc00ebe3d | 34,265,249,096,098 | 02bb01cdb1ef712fd6d7ce16134eeee12793c448 | /mumu-data/mumu-data-service/src/main/java/com/lovecws/mumu/data/area/dao/impl/DataAreaRegionDaoImpl.java | 3f09b9adadabaf9e6b6426910861c85156024e28 | [
"Apache-2.0"
] | permissive | lnSmallsix/mumu | https://github.com/lnSmallsix/mumu | 6eae62b98fb4e3ac85facf57173d9f69421d0674 | 1c7e609189da04412731c52bfae9788de690ff38 | refs/heads/master | 2021-01-14T00:09:21.960000 | 2019-03-09T02:59:38 | 2019-03-09T02:59:38 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lovecws.mumu.data.area.dao.impl;
import com.lovecws.mumu.common.core.dao.impl.BaseDaoImpl;
import com.lovecws.mumu.data.area.dao.DataAreaRegionDao;
import com.lovecws.mumu.data.area.entity.DataAreaRegion;
import org.springframework.stereotype.Repository;
@Repository
public class DataAreaRegionDaoImpl extends BaseDaoImpl<DataAreaRegion> implements DataAreaRegionDao{
}
| UTF-8 | Java | 385 | java | DataAreaRegionDaoImpl.java | Java | [] | null | [] | package com.lovecws.mumu.data.area.dao.impl;
import com.lovecws.mumu.common.core.dao.impl.BaseDaoImpl;
import com.lovecws.mumu.data.area.dao.DataAreaRegionDao;
import com.lovecws.mumu.data.area.entity.DataAreaRegion;
import org.springframework.stereotype.Repository;
@Repository
public class DataAreaRegionDaoImpl extends BaseDaoImpl<DataAreaRegion> implements DataAreaRegionDao{
}
| 385 | 0.844156 | 0.844156 | 11 | 34 | 32 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.454545 | false | false | 13 |
dff38219d335837239e6057a5dbe3917c3a3618f | 18,107,582,133,857 | d28a9e940b4deab1a25d5735c183d5ae6666be4f | /demo.dubbo/client/test/main/java/com/dubbo/client/test/ClientTests.java | ca6e5c8659b9eba2f490130e14bec3da031243bb | [] | no_license | lzy369/demo.mongodb | https://github.com/lzy369/demo.mongodb | b7c65771def279ecc13cf1e91bf4e127f1d4b2c5 | 804b6aa159b63b25e7cf0196bd180e87b67c8d8e | refs/heads/master | 2018-01-05T09:21:02.492000 | 2016-10-12T10:58:09 | 2016-10-12T10:58:09 | 70,691,171 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dubbo.client.test;
import com.lzy.demo.main.DubboClient;
import interfaces.DubboInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Dell on 2016/10/2.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class ClientTests {
@Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
DubboClient d = (DubboClient) ac.getBean("dubboClient");
String say =d.getDubboInterface().say("zhangsan");
System.out.println(say);
String hi = d.getDubboInterface().hi("lisi");
System.out.println(hi);
}
}
| UTF-8 | Java | 975 | java | ClientTests.java | Java | [
{
"context": "junit4.SpringJUnit4ClassRunner;\n\n/**\n * Created by Dell on 2016/10/2.\n */\n@RunWith(SpringJUnit4ClassRunne",
"end": 446,
"score": 0.9439241886138916,
"start": 442,
"tag": "USERNAME",
"value": "Dell"
}
] | null | [] | package com.dubbo.client.test;
import com.lzy.demo.main.DubboClient;
import interfaces.DubboInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Dell on 2016/10/2.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class ClientTests {
@Test
public void test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
DubboClient d = (DubboClient) ac.getBean("dubboClient");
String say =d.getDubboInterface().say("zhangsan");
System.out.println(say);
String hi = d.getDubboInterface().hi("lisi");
System.out.println(hi);
}
}
| 975 | 0.756923 | 0.746667 | 30 | 31.5 | 26.147976 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 13 |
82f94dc5d5a8c2fd7b9a20bd7acd6591c056d957 | 34,866,544,513,096 | 62e334192393326476756dfa89dce9f0f08570d4 | /tk_code/tiku-essay-app/essay-common/src/main/java/com/huatu/tiku/essay/entity/EssayTeacher.java | 3c70106131f72244129ba0f14d216216651acbff | [] | no_license | JellyB/code_back | https://github.com/JellyB/code_back | 4796d5816ba6ff6f3925fded9d75254536a5ddcf | f5cecf3a9efd6851724a1315813337a0741bd89d | refs/heads/master | 2022-07-16T14:19:39.770000 | 2019-11-22T09:22:12 | 2019-11-22T09:22:12 | 223,366,837 | 1 | 2 | null | false | 2022-06-30T20:21:38 | 2019-11-22T09:15:50 | 2022-01-05T09:12:18 | 2022-06-30T20:21:38 | 12,894 | 1 | 2 | 10 | Java | false | false | package com.huatu.tiku.essay.entity;
import com.huatu.tiku.essay.essayEnum.DepartmentEnum;
import com.huatu.tiku.essay.essayEnum.TeacherLevelEnum;
import com.huatu.tiku.essay.essayEnum.TeacherStatusEnum;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by duanxiangchao on 2019/7/9
*/
@Entity
@Data
@Builder
@Table(name="v_essay_teacher")
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate
@DynamicInsert
public class EssayTeacher extends BaseEntity implements Serializable {
private String realName;
private String nickName;
private String phoneNum;
private String email;
/**
* 1.名师 2.VIP总监 3.总监 4.高级
*/
private Integer teacherLevel;
/**
* 1.使用 2.考核 3.正式 4.离职
*/
private Integer teacherStatus;
/**
* 1.人大 2.党群 3.政协 4.综合
*/
private Integer department;
private Long areaId;
private Date entryDate;
private String correctType;
/**
* 教师评分
*/
private BigDecimal teacherScore;
private String bankName;
private String bankBranch;
private String bankAddress;
private String idCard;
private String bankUserName;
private String bankNum;
/**
* 权限中心username
*/
private String uCenterName;
/**
* 权限中心用户id
*/
private Long uCenterId;
}
| UTF-8 | Java | 1,651 | java | EssayTeacher.java | Java | [
{
"context": "Decimal;\nimport java.util.Date;\n\n/**\n * Created by duanxiangchao on 2019/7/9\n */\n@Entity\n@Data\n@Builder\n@Table(nam",
"end": 497,
"score": 0.999534547328949,
"start": 484,
"tag": "USERNAME",
"value": "duanxiangchao"
}
] | null | [] | package com.huatu.tiku.essay.entity;
import com.huatu.tiku.essay.essayEnum.DepartmentEnum;
import com.huatu.tiku.essay.essayEnum.TeacherLevelEnum;
import com.huatu.tiku.essay.essayEnum.TeacherStatusEnum;
import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by duanxiangchao on 2019/7/9
*/
@Entity
@Data
@Builder
@Table(name="v_essay_teacher")
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
@DynamicUpdate
@DynamicInsert
public class EssayTeacher extends BaseEntity implements Serializable {
private String realName;
private String nickName;
private String phoneNum;
private String email;
/**
* 1.名师 2.VIP总监 3.总监 4.高级
*/
private Integer teacherLevel;
/**
* 1.使用 2.考核 3.正式 4.离职
*/
private Integer teacherStatus;
/**
* 1.人大 2.党群 3.政协 4.综合
*/
private Integer department;
private Long areaId;
private Date entryDate;
private String correctType;
/**
* 教师评分
*/
private BigDecimal teacherScore;
private String bankName;
private String bankBranch;
private String bankAddress;
private String idCard;
private String bankUserName;
private String bankNum;
/**
* 权限中心username
*/
private String uCenterName;
/**
* 权限中心用户id
*/
private Long uCenterId;
}
| 1,651 | 0.698413 | 0.686984 | 84 | 17.75 | 16.44245 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.369048 | false | false | 13 |
c2138e5bf455f1866660bb298f25bc0cdb50c3fe | 16,716,012,763,202 | aa168494d968c1f6e5fa6981cd3f4c0bc081fa7e | /_src/lesson-3/src/main/java/readlearncode/session2/cats/Cougar.java | bcb1eb1451712d9652d7cbb05786225bdd579935 | [
"Apache-2.0"
] | permissive | paullewallencom/java-978-1-7882-9773-8 | https://github.com/paullewallencom/java-978-1-7882-9773-8 | 42f14fc52e8280df3801f0772e6c0da91c398f85 | 7c5f2d2ada7c1a4560e271c872e962d985969838 | refs/heads/main | 2023-02-07T13:57:06.281000 | 2020-12-28T04:20:30 | 2020-12-28T04:20:30 | 319,404,253 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package readlearncode.session2.cats;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class Cougar extends Puma {
public String type(){
return "Cougar";
}
public void printChildType() {
System.out.println("Child type is: " + type());
}
public static void main(String... args){
Cougar cougar = new Cougar();
cougar.printChildType();
cougar.printParentType();
}
public Cougar(){
super("Black");
}
public void roar(){
System.out.println("Roars");
}
public void eat(){}
public boolean eat(String food){ return true;}
public void eat(int calories){}
public void eat(long calories){}
public void eat(Integer calories){}
public void eat(Leopard leopard, float calories){}
public String eat(boolean hungry){ return "Eaten";}
public void eat(Leopard leopard){}
public void eat(Panthera panthera){}
public void eat(Cat cat){}
} | UTF-8 | Java | 1,035 | java | Cougar.java | Java | [
{
"context": "ode.session2.cats;\n\n/**\n * Source code github.com/readlearncode\n *\n * @author Alex Theedom www.readlearncode.com\n",
"end": 81,
"score": 0.9991949200630188,
"start": 68,
"tag": "USERNAME",
"value": "readlearncode"
},
{
"context": "Source code github.com/readlearnco... | null | [] | package readlearncode.session2.cats;
/**
* Source code github.com/readlearncode
*
* @author <NAME> www.readlearncode.com
* @version 1.0
*/
public class Cougar extends Puma {
public String type(){
return "Cougar";
}
public void printChildType() {
System.out.println("Child type is: " + type());
}
public static void main(String... args){
Cougar cougar = new Cougar();
cougar.printChildType();
cougar.printParentType();
}
public Cougar(){
super("Black");
}
public void roar(){
System.out.println("Roars");
}
public void eat(){}
public boolean eat(String food){ return true;}
public void eat(int calories){}
public void eat(long calories){}
public void eat(Integer calories){}
public void eat(Leopard leopard, float calories){}
public String eat(boolean hungry){ return "Eaten";}
public void eat(Leopard leopard){}
public void eat(Panthera panthera){}
public void eat(Cat cat){}
} | 1,029 | 0.627053 | 0.624155 | 46 | 21.52174 | 18.430527 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.23913 | false | false | 13 |
7afac8dca5be0c20f8e2385023474a464cbe93d1 | 8,753,143,374,665 | 10695b9bac02eeb917e1a1cef20070aa971e34b4 | /main-application/core/core-ejb/src/main/java/com/r2r/core/profile/ProfileEjb.java | c5aa5405f5a2ea0e2a2f45dda45713f0097321a8 | [] | no_license | byosonet/bookstore | https://github.com/byosonet/bookstore | 0274f9594bad32461589a2a79b7b12942346c0c7 | 07c1f5a9f5650c240043dde300bc30e38f99d8e1 | refs/heads/master | 2016-09-14T06:05:35.645000 | 2016-05-25T01:15:15 | 2016-05-25T01:15:15 | 59,617,118 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.r2r.core.profile;
import com.r2r.core.common.EntityDaoEjb;
import com.r2r.core.db.entity.Usuario;
import com.r2r.core.db.entity.navegacion.Menu;
import com.r2r.core.db.entity.permisos.Perfil;
import com.r2r.core.db.entity.permisos.PerfilMenu;
import com.r2r.core.db.exception.DatabaseException;
import java.util.List;
import javax.ejb.Stateless;
/**
*
* @author Alan Arturo Hernandez Chichitz <alanarturohernandez@gmail.com>
*/
@Stateless
public class ProfileEjb extends EntityDaoEjb {
public List<Menu> getPerfilMenu(Perfil perfil) {
return entityManager.createQuery("SELECT m.menu FROM PerfilMenu m WHERE m.perfil = :perfil", Menu.class)
.setParameter("perfil", perfil)
.getResultList();
}
public List<Menu> getPerfilMenu(Integer id) {
return entityManager.createQuery("SELECT m.menu FROM PerfilMenu m WHERE m.perfil.id = :id", Menu.class)
.setParameter("id", id)
.getResultList();
}
public void removeMenus(Perfil perfil) {
entityManager.createQuery("DELETE FROM PerfilMenu m WHERE m.perfil = :perfil", Menu.class)
.setParameter("perfil", perfil)
.executeUpdate();
}
public void saveProfile(Perfil perfil, Usuario usuario) throws DatabaseException {
removeMenus(perfil);
saveNewEntity(perfil, usuario);
}
public void editProfile(Perfil perfil, Usuario usuario) throws DatabaseException {
removeMenus(perfil);
for (PerfilMenu perfilMenu : perfil.getMenus()) {
saveNewEntity(perfilMenu);
}
editEntity(perfil, usuario);
}
}
| UTF-8 | Java | 1,666 | java | ProfileEjb.java | Java | [
{
"context": "st;\nimport javax.ejb.Stateless;\n\n/**\n *\n * @author Alan Arturo Hernandez Chichitz <alanarturohernandez@gmail.com>\n */\n@Stateless\npu",
"end": 408,
"score": 0.9998958706855774,
"start": 378,
"tag": "NAME",
"value": "Alan Arturo Hernandez Chichitz"
},
{
"context": ... | null | [] | package com.r2r.core.profile;
import com.r2r.core.common.EntityDaoEjb;
import com.r2r.core.db.entity.Usuario;
import com.r2r.core.db.entity.navegacion.Menu;
import com.r2r.core.db.entity.permisos.Perfil;
import com.r2r.core.db.entity.permisos.PerfilMenu;
import com.r2r.core.db.exception.DatabaseException;
import java.util.List;
import javax.ejb.Stateless;
/**
*
* @author <NAME> <<EMAIL>>
*/
@Stateless
public class ProfileEjb extends EntityDaoEjb {
public List<Menu> getPerfilMenu(Perfil perfil) {
return entityManager.createQuery("SELECT m.menu FROM PerfilMenu m WHERE m.perfil = :perfil", Menu.class)
.setParameter("perfil", perfil)
.getResultList();
}
public List<Menu> getPerfilMenu(Integer id) {
return entityManager.createQuery("SELECT m.menu FROM PerfilMenu m WHERE m.perfil.id = :id", Menu.class)
.setParameter("id", id)
.getResultList();
}
public void removeMenus(Perfil perfil) {
entityManager.createQuery("DELETE FROM PerfilMenu m WHERE m.perfil = :perfil", Menu.class)
.setParameter("perfil", perfil)
.executeUpdate();
}
public void saveProfile(Perfil perfil, Usuario usuario) throws DatabaseException {
removeMenus(perfil);
saveNewEntity(perfil, usuario);
}
public void editProfile(Perfil perfil, Usuario usuario) throws DatabaseException {
removeMenus(perfil);
for (PerfilMenu perfilMenu : perfil.getMenus()) {
saveNewEntity(perfilMenu);
}
editEntity(perfil, usuario);
}
}
| 1,620 | 0.678872 | 0.67467 | 49 | 33 | 29.771236 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55102 | false | false | 13 |
5278834b98aa4b3b9e275c525613913478fca546 | 21,500,606,310,752 | c7f2ff5c527dabe9d4f9e80ea08abdb058c8e784 | /src/com/cuber/dif/demo/model/ModelF.java | cefa55b9bffaec0ab3e913f9858917435b71b2ad | [] | no_license | Cuber-Q/DIDemo | https://github.com/Cuber-Q/DIDemo | a26b58d7a490f850a0ebe138c7128163bd49d538 | 00f0eb54ed46b6c29a4800cfe4226fe63a3c0bd7 | refs/heads/master | 2021-01-20T19:39:49.328000 | 2016-06-04T12:58:06 | 2016-06-04T12:58:06 | 60,116,682 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cuber.dif.demo.model;
import com.cuber.dif.framework.basis.annotation.Inject;
@Inject
public class ModelF {
}
| UTF-8 | Java | 125 | java | ModelF.java | Java | [] | null | [] | package com.cuber.dif.demo.model;
import com.cuber.dif.framework.basis.annotation.Inject;
@Inject
public class ModelF {
}
| 125 | 0.776 | 0.776 | 8 | 14.625 | 19.019316 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 13 |
04fee8f87f576a57186be145786c076fffb2e54a | 27,410,481,310,777 | 94f1d12a7b544bd5d6cd0655c9bd700715dceade | /android-news-app/app/src/main/java/com/example/android/thenews/NewsLoader.java | a87488543f8467b28a9d53f6d33e9a3042175a1a | [
"Apache-2.0"
] | permissive | KESHARINANDANPRATAP/Android-Projects | https://github.com/KESHARINANDANPRATAP/Android-Projects | 75ee7fed9e35908ee428d3828fbb8a4570d8c969 | 5150809387a42b5a65f9c677d5c1303ded8bf7c1 | refs/heads/main | 2023-03-06T11:20:59.962000 | 2021-02-07T21:06:05 | 2021-02-07T21:06:05 | 332,149,651 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.android.thenews;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.AsyncTaskLoader;
import java.util.List;
class NewsLoader extends AsyncTaskLoader<List<News>> {
/** URL for querying the API */
private String newsCategory;
private List<News> mData;
NewsLoader(Context context, String newsCategory) {
super(context);
this.newsCategory = newsCategory;
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData); // Serve cache data
} else {
forceLoad(); // Data does not exist
}
}
@Override
public List<News> loadInBackground() {
// Exit early when no URL string is provided
if (newsCategory == null) {
return null;
}
// Query the API and return the list of top news stories
return NewsQueryUtils.fetchNews(newsCategory);
}
@Override
public void deliverResult(@Nullable List<News> data) {
mData = data; // Cache data
super.deliverResult(data);
}
}
| UTF-8 | Java | 1,011 | java | NewsLoader.java | Java | [] | null | [] | package com.example.android.thenews;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.content.AsyncTaskLoader;
import java.util.List;
class NewsLoader extends AsyncTaskLoader<List<News>> {
/** URL for querying the API */
private String newsCategory;
private List<News> mData;
NewsLoader(Context context, String newsCategory) {
super(context);
this.newsCategory = newsCategory;
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData); // Serve cache data
} else {
forceLoad(); // Data does not exist
}
}
@Override
public List<News> loadInBackground() {
// Exit early when no URL string is provided
if (newsCategory == null) {
return null;
}
// Query the API and return the list of top news stories
return NewsQueryUtils.fetchNews(newsCategory);
}
@Override
public void deliverResult(@Nullable List<News> data) {
mData = data; // Cache data
super.deliverResult(data);
}
}
| 1,011 | 0.724036 | 0.723046 | 45 | 21.466667 | 19.091127 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4 | false | false | 13 |
af7c2c207f9a5a7d6ba27f7b9a21ba0ee9649787 | 23,579,370,491,723 | f199b910b542f91e6cb06263624d012440391d7c | /src/com/smu/binhunt/action/QueryAction.java | 281cf330c55a7e797b2822b41ab7f6744e69cfc4 | [] | no_license | zoudabi/binhunt_portal | https://github.com/zoudabi/binhunt_portal | dec729af054fa41c8733335be1178724bf03118b | 102f60f9702d1cfc617266cfd8864ff33ffdeea6 | refs/heads/master | 2016-09-06T14:18:17.176000 | 2011-11-11T04:03:32 | 2011-11-11T04:03:32 | 2,753,641 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.smu.binhunt.action;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
import com.smu.binhunt.pojo.BinHuntResult;
import com.smu.binhunt.service.BinHuntService;
import com.smu.binhunt.service.NativeBinHuntService;
public class QueryAction extends ActionSupport
{
private String useremail;
private List reslist;
public List getReslist() {
return reslist;
}
public void setReslist(List reslist) {
this.reslist = reslist;
}
public String getUseremail() {
return useremail;
}
public void setUseremail(String useremail) {
this.useremail = useremail;
}
public void validate()
{
if(getUseremail().length() == 0)
{
addFieldError("useremail", getText("useremail.required"));
}
else
{
String check = "^([a-z0-9A-Z]+[-\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(getUseremail());
boolean isMatched = matcher.matches();
if(!isMatched)
{
addFieldError("useremail", getText("useremail.badformat"));
}
}
}
public String execute()
{
BinHuntService bhs = new NativeBinHuntService();
ArrayList<BinHuntResult> listres = bhs.getResult(useremail);
reslist = new ArrayList();
for(int i=0; i<listres.size(); ++i)
{
reslist.add(listres.get(i));
}
return SUCCESS;
}
}
| UTF-8 | Java | 1,550 | java | QueryAction.java | Java | [] | null | [] | package com.smu.binhunt.action;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.opensymphony.xwork2.ActionSupport;
import com.smu.binhunt.pojo.BinHuntResult;
import com.smu.binhunt.service.BinHuntService;
import com.smu.binhunt.service.NativeBinHuntService;
public class QueryAction extends ActionSupport
{
private String useremail;
private List reslist;
public List getReslist() {
return reslist;
}
public void setReslist(List reslist) {
this.reslist = reslist;
}
public String getUseremail() {
return useremail;
}
public void setUseremail(String useremail) {
this.useremail = useremail;
}
public void validate()
{
if(getUseremail().length() == 0)
{
addFieldError("useremail", getText("useremail.required"));
}
else
{
String check = "^([a-z0-9A-Z]+[-\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(getUseremail());
boolean isMatched = matcher.matches();
if(!isMatched)
{
addFieldError("useremail", getText("useremail.badformat"));
}
}
}
public String execute()
{
BinHuntService bhs = new NativeBinHuntService();
ArrayList<BinHuntResult> listres = bhs.getResult(useremail);
reslist = new ArrayList();
for(int i=0; i<listres.size(); ++i)
{
reslist.add(listres.get(i));
}
return SUCCESS;
}
}
| 1,550 | 0.652903 | 0.645161 | 65 | 22.846153 | 21.818996 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.307692 | false | false | 13 |
4d4d7dccbdeae5a516ab1878540e00653a60701b | 26,980,984,588,317 | f9eac807ccd1c87bf2b592c31c69224fac50237d | /src/main/java/com/jydy/pda/bean/CMSMQ.java | 1e46cd83df4ddd155aeb0b82372acdea772e4b79 | [] | no_license | zhangronggithub/JYDY | https://github.com/zhangronggithub/JYDY | 13f35c225c1ebaa7a505eabc23f06b295271fc57 | 4d0c2eaafeeae5ce1455fbaa904098d75cb95ed0 | refs/heads/master | 2021-01-20T10:10:25.015000 | 2017-06-08T06:00:16 | 2017-06-08T06:00:16 | 90,326,301 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jydy.pda.bean;
public class CMSMQ {
private String MQ001,MQ002;
public String getMQ001() {
return MQ001;
}
public void setMQ001(String mQ001) {
MQ001 = mQ001;
}
public String getMQ002() {
return MQ002;
}
public void setMQ002(String mQ002) {
MQ002 = mQ002;
}
}
| UTF-8 | Java | 297 | java | CMSMQ.java | Java | [] | null | [] | package com.jydy.pda.bean;
public class CMSMQ {
private String MQ001,MQ002;
public String getMQ001() {
return MQ001;
}
public void setMQ001(String mQ001) {
MQ001 = mQ001;
}
public String getMQ002() {
return MQ002;
}
public void setMQ002(String mQ002) {
MQ002 = mQ002;
}
}
| 297 | 0.673401 | 0.531987 | 23 | 11.913043 | 12.805953 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.086957 | false | false | 13 |
b8e0af3b8da558c9e034279082a947541ceb871c | 17,600,776,006,967 | 8a1720b71e7c589a02ce88826f06c13ddf205b1f | /EntrepriseTest.java | 8e1a564a696969de4ae7999759f0d6214c65d02b | [] | no_license | louis07/itr-2012 | https://github.com/louis07/itr-2012 | 5fd005ee4aec2ce1e3bbfe58e2bd6102106420a3 | 8b08ec0c82f1812e757b835383ca6af460175e92 | refs/heads/master | 2021-01-15T22:56:46.961000 | 2012-10-12T03:10:20 | 2012-10-12T03:10:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
/**
* @author louis
*
*/
public class EntrepriseTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Entreprise comac = new Entreprise("Comac");
Manager patron = new Manager("LI","Nicolas",true,1989,1,comac);
Manager m1 = new Manager("J.A","Ayrault",true,1988,2,comac);
Employe e1 = new Employe("D.","Boho",true,1990,3,comac);
Manager m2 = new Manager("G.","Pierre",true,1991,4,comac);
Manager m3 = new Manager("Fan","Sonia",false,1989,5,comac);
Employe e2 = new Employe("Liu","nIU",true,1988,6,comac);
Employe e3 = new Employe("Zhang","Xiao",true,1988,7,comac);
patron.ajouteEmploye(m1);
m1.ajouteEmploye(e1);
m1.ajouteEmploye(m2);
m2.ajouteEmploye(m3);
m3.ajouteEmploye(e2);
m3.ajouteEmploye(e3);
patron.afficheHierarchie();
System.out.println("------------------");
m1.afficheHierarchie();
System.out.println("------------------");
System.out.println(patron.nombreEmploye());
System.out.println(m3.nombreEmploye());
System.out.println("------------------");
System.out.println("------------------");
patron.afficheSubordonnees();
System.out.println(patron.nombreEmploye());
System.out.println(patron.nombreFemmes());
System.out.println(patron.pourcentFemme());
}
}
| UTF-8 | Java | 1,311 | java | EntrepriseTest.java | Java | [
{
"context": "/**\n * \n */\n\n/**\n * @author louis\n *\n */\npublic class EntrepriseTest {\n\n\t/**\n\t * @p",
"end": 33,
"score": 0.9969839453697205,
"start": 28,
"tag": "NAME",
"value": "louis"
},
{
"context": "reprise(\"Comac\");\n\t\tManager patron = new Manager(\"LI\",\"Nicola... | null | [] | /**
*
*/
/**
* @author louis
*
*/
public class EntrepriseTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Entreprise comac = new Entreprise("Comac");
Manager patron = new Manager("LI","Nicolas",true,1989,1,comac);
Manager m1 = new Manager("J.A","Ayrault",true,1988,2,comac);
Employe e1 = new Employe("D.","Boho",true,1990,3,comac);
Manager m2 = new Manager("G.","Pierre",true,1991,4,comac);
Manager m3 = new Manager("Fan","Sonia",false,1989,5,comac);
Employe e2 = new Employe("Liu","nIU",true,1988,6,comac);
Employe e3 = new Employe("Zhang","Xiao",true,1988,7,comac);
patron.ajouteEmploye(m1);
m1.ajouteEmploye(e1);
m1.ajouteEmploye(m2);
m2.ajouteEmploye(m3);
m3.ajouteEmploye(e2);
m3.ajouteEmploye(e3);
patron.afficheHierarchie();
System.out.println("------------------");
m1.afficheHierarchie();
System.out.println("------------------");
System.out.println(patron.nombreEmploye());
System.out.println(m3.nombreEmploye());
System.out.println("------------------");
System.out.println("------------------");
patron.afficheSubordonnees();
System.out.println(patron.nombreEmploye());
System.out.println(patron.nombreFemmes());
System.out.println(patron.pourcentFemme());
}
}
| 1,311 | 0.633867 | 0.592677 | 49 | 25.755102 | 21.500385 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.612245 | false | false | 13 |
e1df11f6f570cca59debcac397f31fc8874e1b57 | 9,079,560,925,711 | d7f7723df212e5d9cf9b432f1592b2d3d082dd94 | /src/main/java/com/scholar/desktop/ui/curriculum/AddCurriculumUI.java | fed9344dbef07ab6f24b14bfdb8d2aacb0a1ffbf | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Moverr/scholar-desktop | https://github.com/Moverr/scholar-desktop | 3de41c76b7c8f69454f26f5f1acaa01323a5e709 | 15bf46912499d3c731fb00b5428365fb9684bc4d | refs/heads/master | 2018-12-22T23:00:23.362000 | 2018-12-17T11:04:36 | 2018-12-17T11:04:36 | 116,261,303 | 0 | 1 | Apache-2.0 | false | 2019-06-06T19:39:33 | 2018-01-04T13:08:45 | 2019-06-06T18:20:28 | 2019-06-06T19:39:33 | 17,369 | 0 | 1 | 9 | Java | false | false | /*
* 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 main.java.com.scholar.desktop.ui.curriculum;
import com.scholar.desktop.engine.caller.api.v1.curriculum.request.Curriculum;
import com.scholar.desktop.engine.caller.api.v1.curriculum.response.CurriculumResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import main.java.com.scholar.desktop.config.entities.SchoolData;
import main.java.com.scholar.desktop.helper.exceptions.BadRequestException;
import main.java.com.scholar.desktop.services.curriculum.CurriculumService;
import main.java.com.scholar.desktop.ui.classes.AddClassUI;
/**
*
* @author mover
*/
public class AddCurriculumUI extends javax.swing.JPanel {
/**
* Creates new form AddCurriculumUI
*/
private static AddCurriculumUI instance;
private final SchoolData schoolData;
private CurriculumResponse curriculumResponse = null;
public AddCurriculumUI(SchoolData schoolData) {
this.schoolData = schoolData;
initComponents();
initData();
}
public void initData() {
curriculumResponse = null;
saveButton.setText("SAVE");
curriculumDescription.setLineWrap(true);
resetForm();
}
public static AddCurriculumUI getInstance(SchoolData schoolData) {
if (instance == null) {
instance = new AddCurriculumUI(schoolData);
}
return instance;
}
public void edit(CurriculumResponse curriculumResponse) {
this.curriculumResponse = curriculumResponse;
if (this.curriculumResponse != null) {
curriculumName.setText(this.curriculumResponse.getName());
curriculumCode.setText(this.curriculumResponse.getCode());
curriculumDescription.setText(this.curriculumResponse.getDescription());
saveButton.setText("EDIT");
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
curriculumCode = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
curriculumName = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
curriculumDescription = new javax.swing.JTextArea();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 255, 255));
jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel1.setText("Curriculum Information");
jSeparator1.setBackground(new java.awt.Color(153, 153, 153));
jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel2.setText("Code : *");
jLabel2.setToolTipText("");
jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel3.setText("Name : *");
jLabel3.setToolTipText("");
curriculumDescription.setColumns(20);
curriculumDescription.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
curriculumDescription.setRows(5);
curriculumDescription.setWrapStyleWord(true);
curriculumDescription.setAutoscrolls(false);
jScrollPane2.setViewportView(curriculumDescription);
jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel4.setText("Description : *");
jLabel4.setToolTipText("");
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jButton1.setText("CANCEL");
saveButton.setBackground(new java.awt.Color(255, 255, 255));
saveButton.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
saveButton.setText("SAVE");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(curriculumCode, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(curriculumName, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(143, 143, 143)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(166, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(curriculumName, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(curriculumCode, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(103, Short.MAX_VALUE))
);
jScrollPane1.setViewportView(jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
);
}// </editor-fold>//GEN-END:initComponents
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
try {
validateCurriculum();
String name = curriculumName.getText();
String code = curriculumCode.getText();
String description = curriculumDescription.getText();
//saveButton
Curriculum curriculum = getCurriculum(name, code, description);
String btnText = saveButton.getText();
submitData(btnText, curriculum);
} catch (IOException ex) {
Logger.getLogger(AddCurriculumUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}//GEN-LAST:event_saveButtonActionPerformed
protected void resetForm() {
curriculumName.setText("");
curriculumCode.setText("");
curriculumDescription.setText("");
}
protected void submitData(String btnText, Curriculum curriculum) throws IOException {
switch (btnText) {
case "SAVE":
saveCurriculum(curriculum);
break;
case "EDIT":
editCurriculum(curriculum);
break;
default:
break;
}
}
public void editCurriculum(Curriculum curriculum) throws IOException {
try {
if (curriculumResponse == null) {
throw new BadRequestException("Could update record, missing data");
}
curriculum.setId(curriculumResponse.getId());
CurriculumService.getInstance(schoolData).edit(curriculum, "logId");
JOptionPane.showMessageDialog(null, "Record saved succesfully");
resetForm();
} catch (IOException ex) {
Logger.getLogger(AddClassUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}
public void saveCurriculum(Curriculum curriculum) throws IOException {
try {
CurriculumService.getInstance(schoolData).create(curriculum, "logId");
JOptionPane.showMessageDialog(null, "Record saved succesfully");
resetForm();
} catch (IOException ex) {
Logger.getLogger(AddClassUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}
public Curriculum getCurriculum(String name, String code, String description) {
Curriculum curriculum = new Curriculum();
curriculum.setName(name);
curriculum.setCode(code);
curriculum.setDescription(description);
return curriculum;
}
protected void validateCurriculum() throws BadRequestException {
// TODO add your handling code here:
if (curriculumName.getText().isEmpty()) {
throw new BadRequestException("Curriculum Name is Mandatory");
}
if (curriculumCode.getText().isEmpty()) {
throw new BadRequestException("Curriculum Code is Mandatory");
}
if (curriculumDescription.getText().isEmpty()) {
throw new BadRequestException("Curriculum Description is Mandatory");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField curriculumCode;
private javax.swing.JTextArea curriculumDescription;
private javax.swing.JTextField curriculumName;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton saveButton;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 14,090 | java | AddCurriculumUI.java | Java | [
{
"context": ".desktop.ui.classes.AddClassUI;\n\n/**\n *\n * @author mover\n */\npublic class AddCurriculumUI extends javax.sw",
"end": 832,
"score": 0.9992145299911499,
"start": 827,
"tag": "USERNAME",
"value": "mover"
}
] | 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 main.java.com.scholar.desktop.ui.curriculum;
import com.scholar.desktop.engine.caller.api.v1.curriculum.request.Curriculum;
import com.scholar.desktop.engine.caller.api.v1.curriculum.response.CurriculumResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import main.java.com.scholar.desktop.config.entities.SchoolData;
import main.java.com.scholar.desktop.helper.exceptions.BadRequestException;
import main.java.com.scholar.desktop.services.curriculum.CurriculumService;
import main.java.com.scholar.desktop.ui.classes.AddClassUI;
/**
*
* @author mover
*/
public class AddCurriculumUI extends javax.swing.JPanel {
/**
* Creates new form AddCurriculumUI
*/
private static AddCurriculumUI instance;
private final SchoolData schoolData;
private CurriculumResponse curriculumResponse = null;
public AddCurriculumUI(SchoolData schoolData) {
this.schoolData = schoolData;
initComponents();
initData();
}
public void initData() {
curriculumResponse = null;
saveButton.setText("SAVE");
curriculumDescription.setLineWrap(true);
resetForm();
}
public static AddCurriculumUI getInstance(SchoolData schoolData) {
if (instance == null) {
instance = new AddCurriculumUI(schoolData);
}
return instance;
}
public void edit(CurriculumResponse curriculumResponse) {
this.curriculumResponse = curriculumResponse;
if (this.curriculumResponse != null) {
curriculumName.setText(this.curriculumResponse.getName());
curriculumCode.setText(this.curriculumResponse.getCode());
curriculumDescription.setText(this.curriculumResponse.getDescription());
saveButton.setText("EDIT");
}
}
/**
* 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() {
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jLabel2 = new javax.swing.JLabel();
curriculumCode = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
curriculumName = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
curriculumDescription = new javax.swing.JTextArea();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 255, 255));
jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
jLabel1.setText("Curriculum Information");
jSeparator1.setBackground(new java.awt.Color(153, 153, 153));
jLabel2.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel2.setText("Code : *");
jLabel2.setToolTipText("");
jLabel3.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel3.setText("Name : *");
jLabel3.setToolTipText("");
curriculumDescription.setColumns(20);
curriculumDescription.setFont(new java.awt.Font("Arial", 0, 13)); // NOI18N
curriculumDescription.setRows(5);
curriculumDescription.setWrapStyleWord(true);
curriculumDescription.setAutoscrolls(false);
jScrollPane2.setViewportView(curriculumDescription);
jLabel4.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
jLabel4.setText("Description : *");
jLabel4.setToolTipText("");
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
jButton1.setText("CANCEL");
saveButton.setBackground(new java.awt.Color(255, 255, 255));
saveButton.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N
saveButton.setText("SAVE");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel4)
.addComponent(jLabel2))
.addGap(4, 4, 4)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(curriculumCode, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(75, 75, 75)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(curriculumName, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(143, 143, 143)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(166, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(curriculumName, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(curriculumCode, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(103, Short.MAX_VALUE))
);
jScrollPane1.setViewportView(jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
);
}// </editor-fold>//GEN-END:initComponents
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
try {
validateCurriculum();
String name = curriculumName.getText();
String code = curriculumCode.getText();
String description = curriculumDescription.getText();
//saveButton
Curriculum curriculum = getCurriculum(name, code, description);
String btnText = saveButton.getText();
submitData(btnText, curriculum);
} catch (IOException ex) {
Logger.getLogger(AddCurriculumUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}//GEN-LAST:event_saveButtonActionPerformed
protected void resetForm() {
curriculumName.setText("");
curriculumCode.setText("");
curriculumDescription.setText("");
}
protected void submitData(String btnText, Curriculum curriculum) throws IOException {
switch (btnText) {
case "SAVE":
saveCurriculum(curriculum);
break;
case "EDIT":
editCurriculum(curriculum);
break;
default:
break;
}
}
public void editCurriculum(Curriculum curriculum) throws IOException {
try {
if (curriculumResponse == null) {
throw new BadRequestException("Could update record, missing data");
}
curriculum.setId(curriculumResponse.getId());
CurriculumService.getInstance(schoolData).edit(curriculum, "logId");
JOptionPane.showMessageDialog(null, "Record saved succesfully");
resetForm();
} catch (IOException ex) {
Logger.getLogger(AddClassUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}
public void saveCurriculum(Curriculum curriculum) throws IOException {
try {
CurriculumService.getInstance(schoolData).create(curriculum, "logId");
JOptionPane.showMessageDialog(null, "Record saved succesfully");
resetForm();
} catch (IOException ex) {
Logger.getLogger(AddClassUI.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, "Something went wrong, could not save class");
}
}
public Curriculum getCurriculum(String name, String code, String description) {
Curriculum curriculum = new Curriculum();
curriculum.setName(name);
curriculum.setCode(code);
curriculum.setDescription(description);
return curriculum;
}
protected void validateCurriculum() throws BadRequestException {
// TODO add your handling code here:
if (curriculumName.getText().isEmpty()) {
throw new BadRequestException("Curriculum Name is Mandatory");
}
if (curriculumCode.getText().isEmpty()) {
throw new BadRequestException("Curriculum Code is Mandatory");
}
if (curriculumDescription.getText().isEmpty()) {
throw new BadRequestException("Curriculum Description is Mandatory");
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField curriculumCode;
private javax.swing.JTextArea curriculumDescription;
private javax.swing.JTextField curriculumName;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JButton saveButton;
// End of variables declaration//GEN-END:variables
}
| 14,090 | 0.654507 | 0.636338 | 308 | 44.746754 | 33.817703 | 142 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.766234 | false | false | 13 |
87298c92722b06771f3bd26135f100627c8dbe74 | 14,147,622,313,942 | d8f866140eea099bd83d0e7322eb94c2205e13e6 | /src/client/view/View.java | 76974c1abfc1a48fe2b2532b773f73dc30f1b268 | [] | no_license | HBuczynski/Chat_Clients-Server | https://github.com/HBuczynski/Chat_Clients-Server | d0a23088a6603c2e43e4d9bba6c8c352b1f11a55 | 3e364f2a7ea795315819d62e19d3bc9ceb2473e1 | refs/heads/master | 2020-12-30T13:47:03.648000 | 2017-05-23T13:05:13 | 2017-05-23T13:05:13 | 91,258,730 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package client.view;
import java.awt.Color;
import java.util.Calendar;
import java.util.Vector;
import java.awt.Font;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
/**
* View consists components responsible for communication with user.
*
* @author HBuczynski
* @version 1.0
*/
public class View
{
private Gui guiObjects;
private GuiClientCreator guiCreator;
private String username;
private boolean connectionIsEstablished;
private Vector<String> usersVector;
public View()
{
initializeVariables();
initializeComponents();
createServerTab();
showMainWindow();
}
private void initializeVariables()
{
guiObjects = new Gui();
guiCreator = new GuiClientCreator(guiObjects);
usersVector = new Vector<String>();
connectionIsEstablished = false;
}
/**
* Initialize GUI and action listeners.
*/
private void initializeComponents()
{
guiCreator.initialize();
this.conversationButtonAcion();
}
/**
* Basic tab consists information from server.
*/
private void createServerTab()
{
addNewConversationTab("Server");
}
/**
* If new message is come, the new tab is created and the view is switched into this component.
* @param userName
*/
private void addNewConversationTab(String userName)
{
guiObjects.conversationMap.put(userName, new JTextArea());
guiObjects.conversationMap.get(userName).setLineWrap(true);
guiObjects.conversationMap.get(userName).setEditable(false);
guiObjects.conversationMap.get(userName).setFont(new Font("Arial", Font.PLAIN, 16));
guiObjects.conversationMap.get(userName).setBorder(BorderFactory.createLineBorder(Color.BLACK));
guiObjects.conversations.addTab(userName, new JScrollPane(guiObjects.conversationMap.get(userName)));
int index = guiObjects.conversations.indexOfTab(userName);
guiObjects.conversations.setSelectedIndex(index);
}
/**
* Method adds new users to vector.
* @param name
*/
public void addUsersToList(String name)
{
if(!name.equals(username))
{
usersVector.add(name);
addUsersToPanel();
}
}
/**
* Specific user is removed from users list.
* @param name
*/
public void removeUserFromList(String name)
{
int index = usersVector.indexOf(name);
usersVector.remove(index);
addUsersToPanel();
}
public void removeUsersList()
{
usersVector.removeAllElements();
}
public void clearUSerPanel()
{
guiObjects.usersPanel.removeAll();
guiObjects.usersPanel.revalidate();
guiObjects.usersPanel.repaint();
}
/**
* Users are added to panel situated on the left side of UI.
*/
private void addUsersToPanel()
{
MouseAdapterMod mouseAdapter = new MouseAdapterMod();
guiObjects.usersPanel.removeAll();
guiObjects.usersPanel.revalidate();
for(int i=0; i < usersVector.size(); ++i)
{
JLabel newUser = new JLabel(" # " + usersVector.get(i));
newUser.setName(usersVector.get(i));
newUser.setSize(140, 30);
newUser.addMouseListener(mouseAdapter);
newUser.setFont(new Font("Arial", Font.PLAIN, 20));
guiObjects.usersPanel.add(newUser);
}
guiObjects.usersPanel.repaint();
}
/**
* New message is added to conversation.
* @param message
* @param user
*/
public void setAppendMessage(String message, String user)
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
/**
* Check if the tab exists.
*/
if((guiObjects.conversationMap.get(user)==null) && !user.equals(username))
addNewConversationTab(user);
if(connectionIsEstablished)
{
if(user.equals(username))
{
guiObjects.conversationMap.get(name).append(" >> " + sdf.format(cal.getTime()) + " #" + user + "\n");
guiObjects.conversationMap.get(name).append(message + "\n");
}
else
{
guiObjects.conversationMap.get(user).append(" >> " + sdf.format(cal.getTime()) + " #" + user + "\n");
guiObjects.conversationMap.get(user).append(message + "\n");
}
}
else if (guiObjects.conversations.getSelectedIndex() == 0)
{
guiObjects.conversationMap.get("Server").append(" >> " + " Oh my dear, you cannot write with server !" + "\n");
}
else
{
setTextMessage(" >> Connection is not established. "+ "\n >> Please write your username and push the connect button.");
}
}
public void setTextMessage(String message)
{
guiObjects.conversationMap.get("Server").setText(message);
}
public String getMessage()
{
return guiObjects.sendArea.getText();
}
public void clearUserArea()
{
guiObjects.sendArea.setText("");
}
public String getUsername()
{
return guiObjects.usernameField.getText();
}
public String getHostName()
{
return guiObjects.hostField.getText();
}
public String getPortName()
{
return guiObjects.portField.getText();
}
public String destinationUser()
{
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
return name;
}
public void setUsername()
{
username = getUsername();
guiObjects.usernameField.setEditable(false);
guiObjects.hostField.setEditable(false);
guiObjects.portField.setEditable(false);
connectionIsEstablished = true;
guiObjects.disconnect.setEnabled(true);
}
public void disableConnection()
{
guiObjects.usernameField.setEditable(true);
connectionIsEstablished = false;
guiObjects.disconnect.setEnabled(true);
}
public void loggAgain()
{
guiObjects.usernameField.setEditable(true);
guiObjects.hostField.setEditable(true);
guiObjects.portField.setEditable(true);
guiObjects.usernameField.setText("");
guiObjects.disconnect.setEnabled(false);
}
public void showMainWindow()
{
guiObjects.mainFrame.setVisible(true);
}
private void conversationButtonAcion()
{
guiObjects.endConversation.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(guiObjects.conversations.getSelectedIndex() != guiObjects.conversations.indexOfTab("Server"))
{
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
guiObjects.conversationMap.remove(name);
guiObjects.conversations.remove(guiObjects.conversations.getSelectedIndex());
}
}
});
}
public void sendButtonListener(ActionListener listenForSendButton)
{
guiObjects.send.addActionListener(listenForSendButton);
}
public void connectButtonListener(ActionListener act)
{
guiObjects.connect.addActionListener(act);
}
public void disconnectButtonListener(ActionListener act)
{
guiObjects.disconnect.addActionListener(act);
}
private class MouseAdapterMod extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
if(!guiObjects.conversationMap.containsKey(label.getName()))
{
addNewConversationTab(label.getName());
}
}
}
}
| UTF-8 | Java | 7,209 | java | View.java | Java | [
{
"context": "nsible for communication with user.\n * \n * @author HBuczynski\n * @version 1.0\n */\n\npublic class View \n{\t\n\tpriva",
"end": 301,
"score": 0.9956396818161011,
"start": 291,
"tag": "NAME",
"value": "HBuczynski"
},
{
"context": ".conversationMap.get(user)==null) && ... | null | [] | package client.view;
import java.awt.Color;
import java.util.Calendar;
import java.util.Vector;
import java.awt.Font;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
/**
* View consists components responsible for communication with user.
*
* @author HBuczynski
* @version 1.0
*/
public class View
{
private Gui guiObjects;
private GuiClientCreator guiCreator;
private String username;
private boolean connectionIsEstablished;
private Vector<String> usersVector;
public View()
{
initializeVariables();
initializeComponents();
createServerTab();
showMainWindow();
}
private void initializeVariables()
{
guiObjects = new Gui();
guiCreator = new GuiClientCreator(guiObjects);
usersVector = new Vector<String>();
connectionIsEstablished = false;
}
/**
* Initialize GUI and action listeners.
*/
private void initializeComponents()
{
guiCreator.initialize();
this.conversationButtonAcion();
}
/**
* Basic tab consists information from server.
*/
private void createServerTab()
{
addNewConversationTab("Server");
}
/**
* If new message is come, the new tab is created and the view is switched into this component.
* @param userName
*/
private void addNewConversationTab(String userName)
{
guiObjects.conversationMap.put(userName, new JTextArea());
guiObjects.conversationMap.get(userName).setLineWrap(true);
guiObjects.conversationMap.get(userName).setEditable(false);
guiObjects.conversationMap.get(userName).setFont(new Font("Arial", Font.PLAIN, 16));
guiObjects.conversationMap.get(userName).setBorder(BorderFactory.createLineBorder(Color.BLACK));
guiObjects.conversations.addTab(userName, new JScrollPane(guiObjects.conversationMap.get(userName)));
int index = guiObjects.conversations.indexOfTab(userName);
guiObjects.conversations.setSelectedIndex(index);
}
/**
* Method adds new users to vector.
* @param name
*/
public void addUsersToList(String name)
{
if(!name.equals(username))
{
usersVector.add(name);
addUsersToPanel();
}
}
/**
* Specific user is removed from users list.
* @param name
*/
public void removeUserFromList(String name)
{
int index = usersVector.indexOf(name);
usersVector.remove(index);
addUsersToPanel();
}
public void removeUsersList()
{
usersVector.removeAllElements();
}
public void clearUSerPanel()
{
guiObjects.usersPanel.removeAll();
guiObjects.usersPanel.revalidate();
guiObjects.usersPanel.repaint();
}
/**
* Users are added to panel situated on the left side of UI.
*/
private void addUsersToPanel()
{
MouseAdapterMod mouseAdapter = new MouseAdapterMod();
guiObjects.usersPanel.removeAll();
guiObjects.usersPanel.revalidate();
for(int i=0; i < usersVector.size(); ++i)
{
JLabel newUser = new JLabel(" # " + usersVector.get(i));
newUser.setName(usersVector.get(i));
newUser.setSize(140, 30);
newUser.addMouseListener(mouseAdapter);
newUser.setFont(new Font("Arial", Font.PLAIN, 20));
guiObjects.usersPanel.add(newUser);
}
guiObjects.usersPanel.repaint();
}
/**
* New message is added to conversation.
* @param message
* @param user
*/
public void setAppendMessage(String message, String user)
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
/**
* Check if the tab exists.
*/
if((guiObjects.conversationMap.get(user)==null) && !user.equals(username))
addNewConversationTab(user);
if(connectionIsEstablished)
{
if(user.equals(username))
{
guiObjects.conversationMap.get(name).append(" >> " + sdf.format(cal.getTime()) + " #" + user + "\n");
guiObjects.conversationMap.get(name).append(message + "\n");
}
else
{
guiObjects.conversationMap.get(user).append(" >> " + sdf.format(cal.getTime()) + " #" + user + "\n");
guiObjects.conversationMap.get(user).append(message + "\n");
}
}
else if (guiObjects.conversations.getSelectedIndex() == 0)
{
guiObjects.conversationMap.get("Server").append(" >> " + " Oh my dear, you cannot write with server !" + "\n");
}
else
{
setTextMessage(" >> Connection is not established. "+ "\n >> Please write your username and push the connect button.");
}
}
public void setTextMessage(String message)
{
guiObjects.conversationMap.get("Server").setText(message);
}
public String getMessage()
{
return guiObjects.sendArea.getText();
}
public void clearUserArea()
{
guiObjects.sendArea.setText("");
}
public String getUsername()
{
return guiObjects.usernameField.getText();
}
public String getHostName()
{
return guiObjects.hostField.getText();
}
public String getPortName()
{
return guiObjects.portField.getText();
}
public String destinationUser()
{
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
return name;
}
public void setUsername()
{
username = getUsername();
guiObjects.usernameField.setEditable(false);
guiObjects.hostField.setEditable(false);
guiObjects.portField.setEditable(false);
connectionIsEstablished = true;
guiObjects.disconnect.setEnabled(true);
}
public void disableConnection()
{
guiObjects.usernameField.setEditable(true);
connectionIsEstablished = false;
guiObjects.disconnect.setEnabled(true);
}
public void loggAgain()
{
guiObjects.usernameField.setEditable(true);
guiObjects.hostField.setEditable(true);
guiObjects.portField.setEditable(true);
guiObjects.usernameField.setText("");
guiObjects.disconnect.setEnabled(false);
}
public void showMainWindow()
{
guiObjects.mainFrame.setVisible(true);
}
private void conversationButtonAcion()
{
guiObjects.endConversation.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(guiObjects.conversations.getSelectedIndex() != guiObjects.conversations.indexOfTab("Server"))
{
int index = guiObjects.conversations.getSelectedIndex();
String name = new String(guiObjects.conversations.getTitleAt(index));
guiObjects.conversationMap.remove(name);
guiObjects.conversations.remove(guiObjects.conversations.getSelectedIndex());
}
}
});
}
public void sendButtonListener(ActionListener listenForSendButton)
{
guiObjects.send.addActionListener(listenForSendButton);
}
public void connectButtonListener(ActionListener act)
{
guiObjects.connect.addActionListener(act);
}
public void disconnectButtonListener(ActionListener act)
{
guiObjects.disconnect.addActionListener(act);
}
private class MouseAdapterMod extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getSource();
if(!guiObjects.conversationMap.containsKey(label.getName()))
{
addNewConversationTab(label.getName());
}
}
}
}
| 7,209 | 0.70731 | 0.705507 | 293 | 23.604095 | 25.485329 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.904437 | false | false | 13 |
211e35c23edd06e52fc9122403c87c9e0c0a07cd | 5,179,730,561,053 | 6f7c5a6e183efea653b45c58ec5dab6be5dc7dd5 | /nb/src/com/ibase/web/testplan/domain/Testplan.java | 44a9ca4971d69a1dc55a2164102114972a3bca6d | [] | no_license | pzzbean/nb | https://github.com/pzzbean/nb | b0bacb12a3efb238b719ff49ae2a9e8aaaa6ba48 | 714a8272348226dc865a81b7d386ea8082fac8fd | refs/heads/master | 2021-04-06T08:19:37.193000 | 2018-03-11T02:18:48 | 2018-03-11T02:18:48 | 124,637,769 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ibase.web.testplan.domain;
import java.util.List;
public class Testplan {
private long testplanId; // 测试计划表id
private long userId; // 用户编号
private String testEngineer; // 测试工程师
private String testEngineerPhone;// 测试工程师电话
private String planCreator; // 计划创建人
private String planCreatorPhone;// 创建人电话
private String planCreateTime; // 计划创建时间
private String planReviser; // 计划修改人
private String planReviseTime; // 修改时间
private String state; // 当前计划的状态
private String testStartTime; // 测试开始时间
private String testEndTime; // 测试结束时间
private List<PlanAndStation> planAndStations;
public long getTestplanId() {
return testplanId;
}
public void setTestplanId(long testplanId) {
this.testplanId = testplanId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getTestEngineer() {
return testEngineer;
}
public void setTestEngineer(String testEngineer) {
this.testEngineer = testEngineer;
}
public String getTestEngineerPhone() {
return testEngineerPhone;
}
public void setTestEngineerPhone(String testEngineerPhone) {
this.testEngineerPhone = testEngineerPhone;
}
public String getPlanCreator() {
return planCreator;
}
public void setPlanCreator(String planCreator) {
this.planCreator = planCreator;
}
public String getPlanCreatorPhone() {
return planCreatorPhone;
}
public void setPlanCreatorPhone(String planCreatorPhone) {
this.planCreatorPhone = planCreatorPhone;
}
public String getPlanCreateTime() {
return planCreateTime;
}
public void setPlanCreateTime(String planCreateTime) {
this.planCreateTime = planCreateTime;
}
public String getPlanReviser() {
return planReviser;
}
public void setPlanReviser(String planReviser) {
this.planReviser = planReviser;
}
public String getPlanReviseTime() {
return planReviseTime;
}
public void setPlanReviseTime(String planReviseTime) {
this.planReviseTime = planReviseTime;
}
public String getStatus() {
return state;
}
public void setStatus(String status) {
this.state = status;
}
public String getTestStartTime() {
return testStartTime;
}
public void setTestStartTime(String testStartTime) {
this.testStartTime = testStartTime;
}
public String getTestEndTime() {
return testEndTime;
}
public void setTestEndTime(String testEndTime) {
this.testEndTime = testEndTime;
}
public List<PlanAndStation> getPlanAndStations() {
return planAndStations;
}
public void setPlanAndStations(List<PlanAndStation> planAndStations) {
this.planAndStations = planAndStations;
}
@Override
public String toString() {
return "Testplan [testplanId=" + testplanId + ", userId=" + userId + ", testEngineer=" + testEngineer
+ ", testEngineerPhone=" + testEngineerPhone + ", planCreator=" + planCreator + ", planCreatorPhone="
+ planCreatorPhone + ", planCreateTime=" + planCreateTime + ", planReviser=" + planReviser
+ ", planReviseTime=" + planReviseTime + ", status=" + state + ", testStartTime=" + testStartTime
+ ", testEndTime=" + testEndTime + ", planAndStations=" + planAndStations + "]";
}
} | UTF-8 | Java | 3,288 | java | Testplan.java | Java | [] | null | [] | package com.ibase.web.testplan.domain;
import java.util.List;
public class Testplan {
private long testplanId; // 测试计划表id
private long userId; // 用户编号
private String testEngineer; // 测试工程师
private String testEngineerPhone;// 测试工程师电话
private String planCreator; // 计划创建人
private String planCreatorPhone;// 创建人电话
private String planCreateTime; // 计划创建时间
private String planReviser; // 计划修改人
private String planReviseTime; // 修改时间
private String state; // 当前计划的状态
private String testStartTime; // 测试开始时间
private String testEndTime; // 测试结束时间
private List<PlanAndStation> planAndStations;
public long getTestplanId() {
return testplanId;
}
public void setTestplanId(long testplanId) {
this.testplanId = testplanId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getTestEngineer() {
return testEngineer;
}
public void setTestEngineer(String testEngineer) {
this.testEngineer = testEngineer;
}
public String getTestEngineerPhone() {
return testEngineerPhone;
}
public void setTestEngineerPhone(String testEngineerPhone) {
this.testEngineerPhone = testEngineerPhone;
}
public String getPlanCreator() {
return planCreator;
}
public void setPlanCreator(String planCreator) {
this.planCreator = planCreator;
}
public String getPlanCreatorPhone() {
return planCreatorPhone;
}
public void setPlanCreatorPhone(String planCreatorPhone) {
this.planCreatorPhone = planCreatorPhone;
}
public String getPlanCreateTime() {
return planCreateTime;
}
public void setPlanCreateTime(String planCreateTime) {
this.planCreateTime = planCreateTime;
}
public String getPlanReviser() {
return planReviser;
}
public void setPlanReviser(String planReviser) {
this.planReviser = planReviser;
}
public String getPlanReviseTime() {
return planReviseTime;
}
public void setPlanReviseTime(String planReviseTime) {
this.planReviseTime = planReviseTime;
}
public String getStatus() {
return state;
}
public void setStatus(String status) {
this.state = status;
}
public String getTestStartTime() {
return testStartTime;
}
public void setTestStartTime(String testStartTime) {
this.testStartTime = testStartTime;
}
public String getTestEndTime() {
return testEndTime;
}
public void setTestEndTime(String testEndTime) {
this.testEndTime = testEndTime;
}
public List<PlanAndStation> getPlanAndStations() {
return planAndStations;
}
public void setPlanAndStations(List<PlanAndStation> planAndStations) {
this.planAndStations = planAndStations;
}
@Override
public String toString() {
return "Testplan [testplanId=" + testplanId + ", userId=" + userId + ", testEngineer=" + testEngineer
+ ", testEngineerPhone=" + testEngineerPhone + ", planCreator=" + planCreator + ", planCreatorPhone="
+ planCreatorPhone + ", planCreateTime=" + planCreateTime + ", planReviser=" + planReviser
+ ", planReviseTime=" + planReviseTime + ", status=" + state + ", testStartTime=" + testStartTime
+ ", testEndTime=" + testEndTime + ", planAndStations=" + planAndStations + "]";
}
} | 3,288 | 0.741925 | 0.741925 | 133 | 22.751881 | 24.006392 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.443609 | false | false | 13 |
85b70ac833c0306e9c0b7bff71049ffa522a0e1b | 5,179,730,562,830 | b368c97335970fdb3967c308760950fd77f04450 | /org.eclipse.xtext.graphview.lib/src/org/eclipse/xtext/graphview/lib/layout/SpringAutoLayout.java | 6e17fdbad0f44aca9f79f9871f5ac7e664cf3ee1 | [] | no_license | athurn/Generic-Graph-View | https://github.com/athurn/Generic-Graph-View | 9c7d4c56f4c0c4326186d2ff609eb05f1966d4c0 | 2ebc6f1914e6ed407e28ed8fd0447e75bb0c4f7d | refs/heads/master | 2021-01-18T17:17:09.859000 | 2016-02-11T21:40:17 | 2016-02-11T21:40:17 | 8,881,263 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.eclipse.xtext.graphview.lib.layout;
///*******************************************************************************
// * Copyright (c) 2011 itemis AG (http://www.itemis.eu) and others.
// * All rights reserved. This program and the accompanying materials
// * are made available under the terms of the Eclipse Public License v1.0
// * which accompanies this distribution, and is available at
// * http://www.eclipse.org/legal/epl-v10.html
// *******************************************************************************/
//package org.eclipse.xtext.graphview.behavior.layout;
//
//import java.util.Map;
//
//import org.apache.log4j.Logger;
//import org.eclipse.draw2d.Connection;
//import org.eclipse.draw2d.ConnectionRouter;
//import org.eclipse.draw2d.IFigure;
//import org.eclipse.draw2d.Layer;
//import org.eclipse.draw2d.geometry.Dimension;
//import org.eclipse.draw2d.geometry.Rectangle;
//import org.eclipse.xtext.graphview.shape.FigureUtil;
//import org.eclipse.zest.layouts.InvalidLayoutConfiguration;
//import org.eclipse.zest.layouts.LayoutEntity;
//import org.eclipse.zest.layouts.LayoutRelationship;
//import org.eclipse.zest.layouts.LayoutStyles;
//import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm;
//import org.eclipse.zest.layouts.exampleStructures.SimpleNode;
//import org.eclipse.zest.layouts.exampleStructures.SimpleRelationship;
//
//import com.google.common.collect.Iterables;
//import com.google.common.collect.Maps;
//
//public class SpringAutoLayout extends AbstractAutoLayout {
//
// private double blankToNodeAreaRatio = 3.1;
//
// private double aspectRatio = 4. / 3.;
//
// private static final Logger LOG = Logger.getLogger(SpringAutoLayout.class);
//
// private int iterations = 200;
//
// public Rectangle layout(IFigure container) {
// SpringLayoutAlgorithm layoutAlgorithm = new SpringLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING);
// Map<ILayoutNode, LayoutEntity> childrenToNodes = Maps.newHashMap();
// Map<Connection, LayoutRelationship> connectionToEdges = Maps.newHashMap();
// for (Object child : container.getChildren()) {
// if (child instanceof ILayoutNode) {
// ILayoutNode childFigure = (ILayoutNode) child;
// Dimension childPreferredSize = childFigure.getPreferredSize();
// SimpleNode graphNode = new SimpleNode(childFigure, 0, 0, childPreferredSize.width, childPreferredSize.height);
// childrenToNodes.put(childFigure, graphNode);
// }
// }
// Layer connectionLayer = FigureUtil.getConnectionLayer(container);
// ConnectionRouter connectionRouter = getConnectionRouter(container);
// if (connectionLayer != null) {
// for (Object child : connectionLayer.getChildren()) {
// if (child instanceof Connection) {
// Connection connection = (Connection) child;
// connection.setConnectionRouter(connectionRouter);
// LayoutEntity sourceNode = childrenToNodes.get(connection.getSourceAnchor().getOwner());
// LayoutEntity targetNode = childrenToNodes.get(connection.getSourceAnchor().getOwner());
// if (targetNode != null && sourceNode != null) {
// SimpleRelationship edge = new SimpleRelationship(sourceNode, targetNode, false);
// connectionToEdges.put(connection, edge);
// }
// }
// }
// }
// try {
// Dimension estimatedSize = getPeferredSize(container);
// layoutAlgorithm.setIterations(getIterations());
// layoutAlgorithm.setRandom(false);
// layoutAlgorithm.applyLayout(Iterables.toArray(childrenToNodes.values(), LayoutEntity.class),
// Iterables.toArray(connectionToEdges.values(), LayoutRelationship.class), 0, 0, estimatedSize.width,
// estimatedSize.height, false, false);
// for (Map.Entry<ILayoutNode, LayoutEntity> entry : childrenToNodes.entrySet()) {
// LayoutEntity node = entry.getValue();
// ILayoutNode figure = entry.getKey();
// Rectangle bounds = new Rectangle((int) node.getXInLayout(), (int) node.getYInLayout(), (int) node.getWidthInLayout(),
// (int) node.getHeightInLayout());
// figure.setBounds(bounds);
// container.setConstraint((IFigure) figure, bounds);
// }
// return new Rectangle(0, 0, estimatedSize.width, estimatedSize.height);
// } catch (InvalidLayoutConfiguration e) {
// LOG.error("Error in layout config", e);
// return new Rectangle();
// }
// }
//
// protected Dimension getPeferredSize(IFigure container) {
// int area = 0;
// for (Object child : container.getChildren()) {
// if (child instanceof IFigure) {
// IFigure childFigure = (IFigure) child;
// area += childFigure.getPreferredSize().getArea();
// }
// }
// double completeArea = getBlankToNodeAreaRatio() * area;
// return new Dimension((int) Math.sqrt(completeArea * getAspectRatio()), (int) Math.sqrt(completeArea / getAspectRatio()));
// }
//
// public double getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(double aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public double getBlankToNodeAreaRatio() {
// return blankToNodeAreaRatio;
// }
//
// public void setBlankToNodeAreaRatio(double blankToNodeAreaRatio) {
// this.blankToNodeAreaRatio = blankToNodeAreaRatio;
// }
//
// public int getIterations() {
// return iterations;
// }
//
// public void setIterations(int iterations) {
// this.iterations = iterations;
// }
//}
| UTF-8 | Java | 5,311 | java | SpringAutoLayout.java | Java | [] | null | [] | package org.eclipse.xtext.graphview.lib.layout;
///*******************************************************************************
// * Copyright (c) 2011 itemis AG (http://www.itemis.eu) and others.
// * All rights reserved. This program and the accompanying materials
// * are made available under the terms of the Eclipse Public License v1.0
// * which accompanies this distribution, and is available at
// * http://www.eclipse.org/legal/epl-v10.html
// *******************************************************************************/
//package org.eclipse.xtext.graphview.behavior.layout;
//
//import java.util.Map;
//
//import org.apache.log4j.Logger;
//import org.eclipse.draw2d.Connection;
//import org.eclipse.draw2d.ConnectionRouter;
//import org.eclipse.draw2d.IFigure;
//import org.eclipse.draw2d.Layer;
//import org.eclipse.draw2d.geometry.Dimension;
//import org.eclipse.draw2d.geometry.Rectangle;
//import org.eclipse.xtext.graphview.shape.FigureUtil;
//import org.eclipse.zest.layouts.InvalidLayoutConfiguration;
//import org.eclipse.zest.layouts.LayoutEntity;
//import org.eclipse.zest.layouts.LayoutRelationship;
//import org.eclipse.zest.layouts.LayoutStyles;
//import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm;
//import org.eclipse.zest.layouts.exampleStructures.SimpleNode;
//import org.eclipse.zest.layouts.exampleStructures.SimpleRelationship;
//
//import com.google.common.collect.Iterables;
//import com.google.common.collect.Maps;
//
//public class SpringAutoLayout extends AbstractAutoLayout {
//
// private double blankToNodeAreaRatio = 3.1;
//
// private double aspectRatio = 4. / 3.;
//
// private static final Logger LOG = Logger.getLogger(SpringAutoLayout.class);
//
// private int iterations = 200;
//
// public Rectangle layout(IFigure container) {
// SpringLayoutAlgorithm layoutAlgorithm = new SpringLayoutAlgorithm(LayoutStyles.NO_LAYOUT_NODE_RESIZING);
// Map<ILayoutNode, LayoutEntity> childrenToNodes = Maps.newHashMap();
// Map<Connection, LayoutRelationship> connectionToEdges = Maps.newHashMap();
// for (Object child : container.getChildren()) {
// if (child instanceof ILayoutNode) {
// ILayoutNode childFigure = (ILayoutNode) child;
// Dimension childPreferredSize = childFigure.getPreferredSize();
// SimpleNode graphNode = new SimpleNode(childFigure, 0, 0, childPreferredSize.width, childPreferredSize.height);
// childrenToNodes.put(childFigure, graphNode);
// }
// }
// Layer connectionLayer = FigureUtil.getConnectionLayer(container);
// ConnectionRouter connectionRouter = getConnectionRouter(container);
// if (connectionLayer != null) {
// for (Object child : connectionLayer.getChildren()) {
// if (child instanceof Connection) {
// Connection connection = (Connection) child;
// connection.setConnectionRouter(connectionRouter);
// LayoutEntity sourceNode = childrenToNodes.get(connection.getSourceAnchor().getOwner());
// LayoutEntity targetNode = childrenToNodes.get(connection.getSourceAnchor().getOwner());
// if (targetNode != null && sourceNode != null) {
// SimpleRelationship edge = new SimpleRelationship(sourceNode, targetNode, false);
// connectionToEdges.put(connection, edge);
// }
// }
// }
// }
// try {
// Dimension estimatedSize = getPeferredSize(container);
// layoutAlgorithm.setIterations(getIterations());
// layoutAlgorithm.setRandom(false);
// layoutAlgorithm.applyLayout(Iterables.toArray(childrenToNodes.values(), LayoutEntity.class),
// Iterables.toArray(connectionToEdges.values(), LayoutRelationship.class), 0, 0, estimatedSize.width,
// estimatedSize.height, false, false);
// for (Map.Entry<ILayoutNode, LayoutEntity> entry : childrenToNodes.entrySet()) {
// LayoutEntity node = entry.getValue();
// ILayoutNode figure = entry.getKey();
// Rectangle bounds = new Rectangle((int) node.getXInLayout(), (int) node.getYInLayout(), (int) node.getWidthInLayout(),
// (int) node.getHeightInLayout());
// figure.setBounds(bounds);
// container.setConstraint((IFigure) figure, bounds);
// }
// return new Rectangle(0, 0, estimatedSize.width, estimatedSize.height);
// } catch (InvalidLayoutConfiguration e) {
// LOG.error("Error in layout config", e);
// return new Rectangle();
// }
// }
//
// protected Dimension getPeferredSize(IFigure container) {
// int area = 0;
// for (Object child : container.getChildren()) {
// if (child instanceof IFigure) {
// IFigure childFigure = (IFigure) child;
// area += childFigure.getPreferredSize().getArea();
// }
// }
// double completeArea = getBlankToNodeAreaRatio() * area;
// return new Dimension((int) Math.sqrt(completeArea * getAspectRatio()), (int) Math.sqrt(completeArea / getAspectRatio()));
// }
//
// public double getAspectRatio() {
// return aspectRatio;
// }
//
// public void setAspectRatio(double aspectRatio) {
// this.aspectRatio = aspectRatio;
// }
//
// public double getBlankToNodeAreaRatio() {
// return blankToNodeAreaRatio;
// }
//
// public void setBlankToNodeAreaRatio(double blankToNodeAreaRatio) {
// this.blankToNodeAreaRatio = blankToNodeAreaRatio;
// }
//
// public int getIterations() {
// return iterations;
// }
//
// public void setIterations(int iterations) {
// this.iterations = iterations;
// }
//}
| 5,311 | 0.707211 | 0.701751 | 127 | 40.818897 | 30.021099 | 125 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.464567 | false | false | 13 |
5e83a46a3b7d7ef65d9990bc40c96dc13de2c7f5 | 21,148,419,004,146 | 1fd9681ecaa80552c7b429aec751f2086aa82743 | /src/main/java/com/silita/biaodaa/disruptor/handler/zhaoBiao/ApplyAssureSumRemitHandler.java | ecea720e873b8fb80673cb278f3b69d3d4f158c5 | [] | no_license | janck13/notice-analysis | https://github.com/janck13/notice-analysis | 7ffac818ed9c8bef7460160eeafcab520e251afc | c6f7dd8e6f976a8f7eb0badc5982c5f8b88fa705 | refs/heads/master | 2020-05-23T16:56:58.822000 | 2018-12-14T03:32:55 | 2018-12-14T03:32:55 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.silita.biaodaa.disruptor.handler.zhaoBiao;
import com.silita.biaodaa.analysisRules.inter.SingleFieldAnalysis;
import com.silita.biaodaa.analysisRules.notice.zhaobiao.other.OtherApplyAssureSumRemit;
import com.silita.biaodaa.disruptor.handler.BaseAnalysisHandler;
import com.snatch.model.EsNotice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 保证金汇款方式
* Created by maofeng on 2018/3/19.
*/
@Component
public class ApplyAssureSumRemitHandler extends BaseAnalysisHandler {
@Autowired
OtherApplyAssureSumRemit otherApplySumRemit;
public ApplyAssureSumRemitHandler() {
this.fieldDesc = "保证金汇款方式";
}
private SingleFieldAnalysis routeRules(String source){
return otherApplySumRemit;
}
@Override
protected Object currentFieldValues(EsNotice esNotice) {
return esNotice.getDetail().getAssureSumRemit();
}
@Override
protected String executeAnalysis(String stringPart,EsNotice esNotice) throws Exception{
SingleFieldAnalysis analysis = routeRules(esNotice.getSource());
return analysis.analysis(stringPart,esNotice,null);
}
@Override
protected void saveResult(EsNotice esNotice, Object assureSumRemit) {
esNotice.getDetail().setAssureSumRemit((String)assureSumRemit);
}
}
| UTF-8 | Java | 1,395 | java | ApplyAssureSumRemitHandler.java | Java | [
{
"context": "tereotype.Component;\n\n/**\n * 保证金汇款方式\n * Created by maofeng on 2018/3/19.\n */\n@Component\npublic class ApplyAs",
"end": 459,
"score": 0.9996790289878845,
"start": 452,
"tag": "USERNAME",
"value": "maofeng"
}
] | null | [] | package com.silita.biaodaa.disruptor.handler.zhaoBiao;
import com.silita.biaodaa.analysisRules.inter.SingleFieldAnalysis;
import com.silita.biaodaa.analysisRules.notice.zhaobiao.other.OtherApplyAssureSumRemit;
import com.silita.biaodaa.disruptor.handler.BaseAnalysisHandler;
import com.snatch.model.EsNotice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 保证金汇款方式
* Created by maofeng on 2018/3/19.
*/
@Component
public class ApplyAssureSumRemitHandler extends BaseAnalysisHandler {
@Autowired
OtherApplyAssureSumRemit otherApplySumRemit;
public ApplyAssureSumRemitHandler() {
this.fieldDesc = "保证金汇款方式";
}
private SingleFieldAnalysis routeRules(String source){
return otherApplySumRemit;
}
@Override
protected Object currentFieldValues(EsNotice esNotice) {
return esNotice.getDetail().getAssureSumRemit();
}
@Override
protected String executeAnalysis(String stringPart,EsNotice esNotice) throws Exception{
SingleFieldAnalysis analysis = routeRules(esNotice.getSource());
return analysis.analysis(stringPart,esNotice,null);
}
@Override
protected void saveResult(EsNotice esNotice, Object assureSumRemit) {
esNotice.getDetail().setAssureSumRemit((String)assureSumRemit);
}
}
| 1,395 | 0.765911 | 0.76079 | 45 | 29.377777 | 29.186975 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 13 |
21b94484bbd8b7e85a74ce7de111b56b505ee76b | 27,307,402,106,456 | d01efa18b3452cc97c4c2bbc6383967bb1ec0805 | /bizcore/WEB-INF/bank_core_src/com/doublechain/bank/listaccess/ListAccessManagerException.java | b89f0765048b5b5d5cc37e96710a0bdca2288285 | [] | no_license | elfbobo/bank-biz-suite | https://github.com/elfbobo/bank-biz-suite | 02766aac25fab9306b541a50b472ec575b0ff6a5 | 03225e79ecd9e7467e6e7fbad21318c6e4db9625 | refs/heads/master | 2020-11-29T04:39:06.197000 | 2019-12-18T16:35:45 | 2019-12-18T16:35:45 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.doublechain.bank.listaccess;
//import com.doublechain.bank.EntityNotFoundException;
import com.doublechain.bank.BankException;
import com.doublechain.bank.Message;
import java.util.List;
public class ListAccessManagerException extends BankException {
private static final long serialVersionUID = 1L;
public ListAccessManagerException(String string) {
super(string);
}
public ListAccessManagerException(Message message) {
super(message);
}
public ListAccessManagerException(List<Message> messageList) {
super(messageList);
}
}
| UTF-8 | Java | 556 | java | ListAccessManagerException.java | Java | [] | null | [] |
package com.doublechain.bank.listaccess;
//import com.doublechain.bank.EntityNotFoundException;
import com.doublechain.bank.BankException;
import com.doublechain.bank.Message;
import java.util.List;
public class ListAccessManagerException extends BankException {
private static final long serialVersionUID = 1L;
public ListAccessManagerException(String string) {
super(string);
}
public ListAccessManagerException(Message message) {
super(message);
}
public ListAccessManagerException(List<Message> messageList) {
super(messageList);
}
}
| 556 | 0.805755 | 0.803957 | 19 | 28.105263 | 22.710754 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.157895 | false | false | 13 |
328f5aca9da232509f9bd376d265562322a3f280 | 16,879,221,512,765 | 139fc24d6b2b82890f725cfb39365970e6bad599 | /StringBuilder/src/pl/jg/Main.java | 7f8a1217fd8400141eb6910319b22e2e342e8822 | [] | no_license | JakubGajewski/JavaCheatSheet | https://github.com/JakubGajewski/JavaCheatSheet | ed7e539a490f9690112391c750eaba0522a2d9ab | 0610a80ff98419335f82fc40d472845dc7b86ced | refs/heads/master | 2020-03-26T09:47:17.938000 | 2018-10-23T10:02:14 | 2018-10-23T10:02:14 | 144,764,912 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.jg;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
StringBuilder Wojciech = new StringBuilder("hejże ho! ");
System.out.println(Wojciech);
Wojciech.reverse();
System.out.println(Wojciech);
Wojciech.reverse();
String[] dzieci = {"Kasia", "Basia", "Asia"};
Wojciech.append(Arrays.toString(dzieci)
.trim()
.replace("[","")
.replace("]","")
.replace(", ",""));
System.out.println(Wojciech);
System.out.println(Wojciech.reverse());
System.out.println(Wojciech.charAt(0));
String WojStr = Wojciech.toString();
System.out.println(WojStr.split("a"));
}
}
| UTF-8 | Java | 781 | java | Main.java | Java | [] | null | [] | package pl.jg;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
StringBuilder Wojciech = new StringBuilder("hejże ho! ");
System.out.println(Wojciech);
Wojciech.reverse();
System.out.println(Wojciech);
Wojciech.reverse();
String[] dzieci = {"Kasia", "Basia", "Asia"};
Wojciech.append(Arrays.toString(dzieci)
.trim()
.replace("[","")
.replace("]","")
.replace(", ",""));
System.out.println(Wojciech);
System.out.println(Wojciech.reverse());
System.out.println(Wojciech.charAt(0));
String WojStr = Wojciech.toString();
System.out.println(WojStr.split("a"));
}
}
| 781 | 0.544872 | 0.54359 | 37 | 20.081081 | 20.304943 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540541 | false | false | 13 |
d5a8bd1133e85b6c4f140d7d19befa6135ed79bc | 10,754,598,137,302 | e31efc8a826d4ddc9df93fb7056963a39b39aa7a | /family/src/main/java/com/chuxin/family/parse/been/CxReply.java | 9d46eec1fe3804a30d1b8949c714d1f5aece93af | [] | no_license | RyanTech/ProjectFamily | https://github.com/RyanTech/ProjectFamily | cdda8387fe9a66e3f87c2efbd5337cc1ca9778e0 | f1dc8901c827af70086c27e3e1efb3a055ff509e | refs/heads/master | 2018-05-13T04:12:17.123000 | 2014-10-29T07:59:04 | 2014-10-29T07:59:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chuxin.family.parse.been;
import com.chuxin.family.parse.been.data.FeedReply;
/**
* 回复
* @author shichao.wang
*
*/
public class CxReply extends CxParseBasic {
private FeedReply data;
public FeedReply getData() {
return data;
}
public void setData(FeedReply data) {
this.data = data;
}
}
| UTF-8 | Java | 322 | java | CxReply.java | Java | [
{
"context": "y.parse.been.data.FeedReply;\n\n/**\n * 回复\n * @author shichao.wang\n *\n */\npublic class CxReply extends CxP",
"end": 115,
"score": 0.8217522501945496,
"start": 113,
"tag": "NAME",
"value": "sh"
},
{
"context": "arse.been.data.FeedReply;\n\n/**\n * 回复\n * @author shic... | null | [] | package com.chuxin.family.parse.been;
import com.chuxin.family.parse.been.data.FeedReply;
/**
* 回复
* @author shichao.wang
*
*/
public class CxReply extends CxParseBasic {
private FeedReply data;
public FeedReply getData() {
return data;
}
public void setData(FeedReply data) {
this.data = data;
}
}
| 322 | 0.704403 | 0.704403 | 21 | 14.142858 | 16.362808 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 13 |
1de6f0aa83dcf513e21288ef75edd1fa3e1d70e4 | 17,119,739,708,806 | 04ff91227a1d1bffd3034858c80eea420249f815 | /commerceapp_v4.0/commerceapp/src/main/java/org/technological/commerce/model/entity/ScUser.java | c83bf0772b1540ea00560033af4dca7f0a39562b | [] | no_license | Sumerio/Version-Commerce | https://github.com/Sumerio/Version-Commerce | c8e24353776ff00defe72f9d556e5e1425e6ec71 | 891781e9c9c5735294a3be8e91648f7331b7096c | refs/heads/master | 2016-04-04T10:22:42.542000 | 2013-12-30T23:25:04 | 2013-12-30T23:25:04 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.technological.commerce.model.entity;
// Generated 23/11/2013 12:44:06 AM by Hibernate Tools 4.0.0
import java.util.Date;
/**
* ScUser generated by hbm2java
*/
public class ScUser implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long scUserId;
private String userLogin;
private String userPsw;
private String userName;
private Boolean isActive;
private Date expirationDate;
private String email;
public ScUser() {
}
public ScUser(long scUserId) {
this.scUserId = scUserId;
}
public ScUser(long scUserId, String userLogin, String userPsw,
String userName, Boolean isActive, Date expirationDate, String email) {
this.scUserId = scUserId;
this.userLogin = userLogin;
this.userPsw = userPsw;
this.userName = userName;
this.isActive = isActive;
this.expirationDate = expirationDate;
this.email = email;
}
public long getScUserId() {
return this.scUserId;
}
public void setScUserId(long scUserId) {
this.scUserId = scUserId;
}
public String getUserLogin() {
return this.userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
public String getUserPsw() {
return this.userPsw;
}
public void setUserPsw(String userPsw) {
this.userPsw = userPsw;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Boolean getIsActive() {
return this.isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Date getExpirationDate() {
return this.expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
| UTF-8 | Java | 1,856 | java | ScUser.java | Java | [
{
"context": "Login;\n\t\tthis.userPsw = userPsw;\n\t\tthis.userName = userName;\n\t\tthis.isActive = isActive;\n\t\tthis.expirationDat",
"end": 801,
"score": 0.9980356097221375,
"start": 793,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "d setUserName(String userName) {\n\... | null | [] | package org.technological.commerce.model.entity;
// Generated 23/11/2013 12:44:06 AM by Hibernate Tools 4.0.0
import java.util.Date;
/**
* ScUser generated by hbm2java
*/
public class ScUser implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private long scUserId;
private String userLogin;
private String userPsw;
private String userName;
private Boolean isActive;
private Date expirationDate;
private String email;
public ScUser() {
}
public ScUser(long scUserId) {
this.scUserId = scUserId;
}
public ScUser(long scUserId, String userLogin, String userPsw,
String userName, Boolean isActive, Date expirationDate, String email) {
this.scUserId = scUserId;
this.userLogin = userLogin;
this.userPsw = userPsw;
this.userName = userName;
this.isActive = isActive;
this.expirationDate = expirationDate;
this.email = email;
}
public long getScUserId() {
return this.scUserId;
}
public void setScUserId(long scUserId) {
this.scUserId = scUserId;
}
public String getUserLogin() {
return this.userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
public String getUserPsw() {
return this.userPsw;
}
public void setUserPsw(String userPsw) {
this.userPsw = userPsw;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Boolean getIsActive() {
return this.isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Date getExpirationDate() {
return this.expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
| 1,856 | 0.731142 | 0.720905 | 95 | 18.536842 | 17.967697 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.347368 | false | false | 13 |
9815e1bd7b7d2b334a47f8fb4bf0c0e71b117056 | 15,307,263,475,097 | c627379830af85fc86294b36e8119dbc315f9914 | /src/com/chipsetsv/multipaint/IceConnection.java | 0328e07acb256491dc0f58809a44da7524b82952 | [
"Apache-2.0"
] | permissive | ChipsetSV/MultiPaint | https://github.com/ChipsetSV/MultiPaint | 2e98e598fdba602b2ede4ad6c90c4d2001db06bc | a52833d6c6444f3d22cf048a0144100855f51722 | refs/heads/master | 2020-09-12T13:57:11.666000 | 2015-04-02T06:25:35 | 2015-04-02T06:25:35 | 33,292,766 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.chipsetsv.multipaint;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ice4j.Transport;
import org.ice4j.TransportAddress;
import org.ice4j.ice.Agent;
import org.ice4j.ice.Candidate;
import org.ice4j.ice.CandidatePair;
import org.ice4j.ice.CheckList;
import org.ice4j.ice.Component;
import org.ice4j.ice.IceMediaStream;
import org.ice4j.ice.IceProcessingState;
import org.ice4j.ice.LocalCandidate;
import org.ice4j.ice.harvest.StunCandidateHarvester;
import org.ice4j.ice.harvest.TurnCandidateHarvester;
import org.ice4j.pseudotcp.PseudoTcpSocket;
import org.ice4j.pseudotcp.PseudoTcpSocketFactory;
import org.ice4j.security.LongTermCredential;
public class IceConnection {
/**
* The logger.
*/
private static final Logger logger =
Logger.getLogger(CheckList.class.getName());
public static Logger getLogger() {
return logger;
}
private static long startTime;
public static long getStartTime() {
return startTime;
}
public static void setStartTime(long startTime) {
IceConnection.startTime = startTime;
}
/**
* Local job thread variable
*/
private static LocalPseudoTcpJob localJob = null;
static LocalPseudoTcpJob getLocalJob() {
return localJob;
}
/**
* Remote job thread variable
*/
private static RemotePseudoTcpJob remoteJob = null;
static RemotePseudoTcpJob getRemoteJob() {
return remoteJob;
}
/**
* Test data size
*/
private static final int TEST_BYTES_COUNT = 100;
/**
* Flag inidcates if STUN should be used
*/
private static final boolean USE_STUN = true;
/**
* Flag inidcates if TURN should be used
*/
private static final boolean USE_TURN = true;
/**
* Monitor object used to wait for remote agent to finish it's job
*/
private static final Object remoteAgentMonitor = new Object();
public static Object getRemoteAgentMonitor() {
return remoteAgentMonitor;
}
/**
* Monitor object used to wait for local agent to finish it's job
*/
private static final Object localAgentMonitor = new Object();
public static Object getLocalAgentMonitor() {
return localAgentMonitor;
}
/**
* Timeout for ICE discovery
*/
public static long agentJobTimeout = 15000;
protected static Agent createAgent(int pTcpPort)
throws Throwable
{
Agent agent = new Agent();
// STUN
if (USE_STUN)
{
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("sip-communicator.net",
3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("ipv6.sip-communicator.net",
3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv);
}
// TURN
if (USE_TURN)
{
String[] hostnames = new String[]
{
"130.79.90.150",
"2001:660:4701:1001:230:5ff:fe1a:805f"
};
int port = 3478;
LongTermCredential longTermCredential = new LongTermCredential(
"guest", "anonymouspower!!");
for (String hostname : hostnames)
{
agent.addCandidateHarvester(new TurnCandidateHarvester(
new TransportAddress(hostname, port,
Transport.UDP), longTermCredential));
}
}
//STREAM
createStream(pTcpPort, "data", agent);
return agent;
}
private static IceMediaStream createStream(int pTcpPort,
String streamName,
Agent agent)
throws Throwable
{
IceMediaStream stream = agent.createMediaStream(streamName);
long startTime = System.currentTimeMillis();
//udp component
agent.createComponent(
stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100);
long endTime = System.currentTimeMillis();
logger.log(Level.INFO,
"UDP Component created in " + (endTime - startTime) + " ms");
startTime = endTime;
return stream;
}
public static final class LocalIceProcessingListener
implements PropertyChangeListener
{
/**
* System.exit()s as soon as ICE processing enters a final state.
*
* @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing.
*/
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue();
logger.log(Level.INFO,
"Local agent entered the " + iceProcessingState + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED)
{
logger.log(Level.INFO,
"Local - Total ICE processing time: "
+ (processingEndTime - startTime) + "ms");
Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Local: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0);
CandidatePair selectedPair = udpComponent.getSelectedPair();
if (selectedPair != null)
{
LocalCandidate localCandidate = selectedPair.getLocalCandidate();
Candidate remoteCandidate = selectedPair.getRemoteCandidate();
logger.log(Level.INFO, "Local: " + localCandidate);
logger.log(Level.INFO, "Remote: " + remoteCandidate);
try
{
localJob = new LocalPseudoTcpJob(
localCandidate.getDatagramSocket());
}
catch (UnknownHostException ex)
{
logger.log(Level.SEVERE,
"Error while trying to create"
+ " local pseudotcp thread " + ex);
}
}
else
{
logger.log(Level.INFO, "Failed to select any candidate pair");
}
}
else
{
if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED)
{
/*
* Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for
* garbage collection.
*/
if (localJob != null
&& iceProcessingState == IceProcessingState.TERMINATED)
{
localJob.start();
}
synchronized (localAgentMonitor)
{
localAgentMonitor.notifyAll();
}
}
}
}
}
public static final class RemoteIceProcessingListener
implements PropertyChangeListener
{
/**
* System.exit()s as soon as ICE processing enters a final state.
*
* @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing.
*/
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue();
logger.log(Level.INFO,
"Remote agent entered the " + iceProcessingState + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED)
{
logger.log(Level.INFO,
"Remote: Total ICE processing time: "
+ (processingEndTime - startTime) + " ms ");
Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Remote: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0);
CandidatePair usedPair = udpComponent.getSelectedPair();
if (usedPair != null)
{
LocalCandidate localCandidate = usedPair.getLocalCandidate();
Candidate remoteCandidate = usedPair.getRemoteCandidate();
logger.log(Level.INFO,
"Remote: Local address " + localCandidate);
logger.log(Level.INFO,
"Remote: Peer address " + remoteCandidate);
try
{
remoteJob = new RemotePseudoTcpJob(
localCandidate.getDatagramSocket(),
remoteCandidate.getTransportAddress());
}
catch (UnknownHostException ex)
{
logger.log(Level.SEVERE,
"Error while trying to create"
+ " remote pseudotcp thread " + ex);
}
}
else
{
logger.log(Level.SEVERE,
"Remote: Failed to select any candidate pair");
}
}
else
{
if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED)
{
/*
* Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for
* garbage collection.
*/
if (remoteJob != null
&& iceProcessingState == IceProcessingState.TERMINATED)
{
remoteJob.start();
}
synchronized (remoteAgentMonitor)
{
remoteAgentMonitor.notifyAll();
}
}
}
}
}
public static class LocalPseudoTcpJob extends Thread implements Runnable
{
private DatagramSocket dgramSocket;
public LocalPseudoTcpJob(DatagramSocket socket)
throws UnknownHostException
{
this.dgramSocket = socket;
}
@Override
public void run()
{
logger.log(Level.FINEST, "Local pseudotcp worker started");
try
{
logger.log(Level.INFO,
"Local pseudotcp is using: "
+ dgramSocket.getLocalSocketAddress()+dgramSocket);
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket);
socket.setConversationID(1073741824);
//socket.setMTU(1500);
socket.setDebugName("L");
socket.accept(150000);
byte[] buffer = new byte[TEST_BYTES_COUNT];
int read = 0;
while (read != TEST_BYTES_COUNT)
{
read += socket.getInputStream().read(buffer);
logger.log(Level.FINEST, "Local job read: " + read);
}
//TODO: close when all received data is acked
//socket.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
logger.log(Level.FINEST, "Local pseudotcp worker finished");
}
}
public static class RemotePseudoTcpJob extends Thread implements Runnable
{
private DatagramSocket dgramSocket;
private InetSocketAddress peerAddr;
public RemotePseudoTcpJob(DatagramSocket socket,
InetSocketAddress peerAddr)
throws UnknownHostException
{
this.dgramSocket = socket;
this.peerAddr = peerAddr;
}
@Override
public void run()
{
logger.log(Level.FINEST, "Remote pseudotcp worker started");
try
{
logger.log(Level.INFO,
"Remote pseudotcp is using: " +
dgramSocket.getLocalSocketAddress()
+" and will comunicate with: " + peerAddr);
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket);
socket.setConversationID(1073741824);
//socket.setMTU(1500);
socket.setDebugName("R");
long start, end;
start = System.currentTimeMillis();
socket.connect(peerAddr, 150000);
byte[] buffer = new byte[TEST_BYTES_COUNT];
socket.getOutputStream().write(buffer);
socket.getOutputStream().flush();
//Socket will be closed by the iceAgent
//socket.close();
end = System.currentTimeMillis();
logger.log(Level.INFO,
"Transferred " + TEST_BYTES_COUNT
+ " bytes in " + ((end - start) / 1000) + " sec");
}
catch (IOException e)
{
throw new RuntimeException(e);
}
logger.log(Level.FINEST, "Remote pseudotcp worker finished");
}
}
}
| UTF-8 | Java | 14,227 | java | IceConnection.java | Java | [
{
"context": "mes = new String[]\n {\n \"130.79.90.150\",\n \"2001:660:4701:1001:230:5ff:fe1",
"end": 3381,
"score": 0.9997714161872864,
"start": 3368,
"tag": "IP_ADDRESS",
"value": "130.79.90.150"
},
{
"context": " \"130.79.90.... | null | [] | package com.chipsetsv.multipaint;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ice4j.Transport;
import org.ice4j.TransportAddress;
import org.ice4j.ice.Agent;
import org.ice4j.ice.Candidate;
import org.ice4j.ice.CandidatePair;
import org.ice4j.ice.CheckList;
import org.ice4j.ice.Component;
import org.ice4j.ice.IceMediaStream;
import org.ice4j.ice.IceProcessingState;
import org.ice4j.ice.LocalCandidate;
import org.ice4j.ice.harvest.StunCandidateHarvester;
import org.ice4j.ice.harvest.TurnCandidateHarvester;
import org.ice4j.pseudotcp.PseudoTcpSocket;
import org.ice4j.pseudotcp.PseudoTcpSocketFactory;
import org.ice4j.security.LongTermCredential;
public class IceConnection {
/**
* The logger.
*/
private static final Logger logger =
Logger.getLogger(CheckList.class.getName());
public static Logger getLogger() {
return logger;
}
private static long startTime;
public static long getStartTime() {
return startTime;
}
public static void setStartTime(long startTime) {
IceConnection.startTime = startTime;
}
/**
* Local job thread variable
*/
private static LocalPseudoTcpJob localJob = null;
static LocalPseudoTcpJob getLocalJob() {
return localJob;
}
/**
* Remote job thread variable
*/
private static RemotePseudoTcpJob remoteJob = null;
static RemotePseudoTcpJob getRemoteJob() {
return remoteJob;
}
/**
* Test data size
*/
private static final int TEST_BYTES_COUNT = 100;
/**
* Flag inidcates if STUN should be used
*/
private static final boolean USE_STUN = true;
/**
* Flag inidcates if TURN should be used
*/
private static final boolean USE_TURN = true;
/**
* Monitor object used to wait for remote agent to finish it's job
*/
private static final Object remoteAgentMonitor = new Object();
public static Object getRemoteAgentMonitor() {
return remoteAgentMonitor;
}
/**
* Monitor object used to wait for local agent to finish it's job
*/
private static final Object localAgentMonitor = new Object();
public static Object getLocalAgentMonitor() {
return localAgentMonitor;
}
/**
* Timeout for ICE discovery
*/
public static long agentJobTimeout = 15000;
protected static Agent createAgent(int pTcpPort)
throws Throwable
{
Agent agent = new Agent();
// STUN
if (USE_STUN)
{
StunCandidateHarvester stunHarv = new StunCandidateHarvester(
new TransportAddress("sip-communicator.net",
3478, Transport.UDP));
StunCandidateHarvester stun6Harv = new StunCandidateHarvester(
new TransportAddress("ipv6.sip-communicator.net",
3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv);
}
// TURN
if (USE_TURN)
{
String[] hostnames = new String[]
{
"172.16.58.3",
"fc00:e968:6179::de52:7100"
};
int port = 3478;
LongTermCredential longTermCredential = new LongTermCredential(
"guest", "anonymouspower!!");
for (String hostname : hostnames)
{
agent.addCandidateHarvester(new TurnCandidateHarvester(
new TransportAddress(hostname, port,
Transport.UDP), longTermCredential));
}
}
//STREAM
createStream(pTcpPort, "data", agent);
return agent;
}
private static IceMediaStream createStream(int pTcpPort,
String streamName,
Agent agent)
throws Throwable
{
IceMediaStream stream = agent.createMediaStream(streamName);
long startTime = System.currentTimeMillis();
//udp component
agent.createComponent(
stream, Transport.UDP, pTcpPort, pTcpPort, pTcpPort + 100);
long endTime = System.currentTimeMillis();
logger.log(Level.INFO,
"UDP Component created in " + (endTime - startTime) + " ms");
startTime = endTime;
return stream;
}
public static final class LocalIceProcessingListener
implements PropertyChangeListener
{
/**
* System.exit()s as soon as ICE processing enters a final state.
*
* @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing.
*/
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue();
logger.log(Level.INFO,
"Local agent entered the " + iceProcessingState + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED)
{
logger.log(Level.INFO,
"Local - Total ICE processing time: "
+ (processingEndTime - startTime) + "ms");
Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Local: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0);
CandidatePair selectedPair = udpComponent.getSelectedPair();
if (selectedPair != null)
{
LocalCandidate localCandidate = selectedPair.getLocalCandidate();
Candidate remoteCandidate = selectedPair.getRemoteCandidate();
logger.log(Level.INFO, "Local: " + localCandidate);
logger.log(Level.INFO, "Remote: " + remoteCandidate);
try
{
localJob = new LocalPseudoTcpJob(
localCandidate.getDatagramSocket());
}
catch (UnknownHostException ex)
{
logger.log(Level.SEVERE,
"Error while trying to create"
+ " local pseudotcp thread " + ex);
}
}
else
{
logger.log(Level.INFO, "Failed to select any candidate pair");
}
}
else
{
if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED)
{
/*
* Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for
* garbage collection.
*/
if (localJob != null
&& iceProcessingState == IceProcessingState.TERMINATED)
{
localJob.start();
}
synchronized (localAgentMonitor)
{
localAgentMonitor.notifyAll();
}
}
}
}
}
public static final class RemoteIceProcessingListener
implements PropertyChangeListener
{
/**
* System.exit()s as soon as ICE processing enters a final state.
*
* @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing.
*/
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue();
logger.log(Level.INFO,
"Remote agent entered the " + iceProcessingState + " state.");
if (iceProcessingState == IceProcessingState.COMPLETED)
{
logger.log(Level.INFO,
"Remote: Total ICE processing time: "
+ (processingEndTime - startTime) + " ms ");
Agent agent = (Agent) evt.getSource();
logger.log(Level.INFO, "Remote: Create pseudo tcp stream");
IceMediaStream dataStream = agent.getStream("data");
Component udpComponent = dataStream.getComponents().get(0);
CandidatePair usedPair = udpComponent.getSelectedPair();
if (usedPair != null)
{
LocalCandidate localCandidate = usedPair.getLocalCandidate();
Candidate remoteCandidate = usedPair.getRemoteCandidate();
logger.log(Level.INFO,
"Remote: Local address " + localCandidate);
logger.log(Level.INFO,
"Remote: Peer address " + remoteCandidate);
try
{
remoteJob = new RemotePseudoTcpJob(
localCandidate.getDatagramSocket(),
remoteCandidate.getTransportAddress());
}
catch (UnknownHostException ex)
{
logger.log(Level.SEVERE,
"Error while trying to create"
+ " remote pseudotcp thread " + ex);
}
}
else
{
logger.log(Level.SEVERE,
"Remote: Failed to select any candidate pair");
}
}
else
{
if (iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED)
{
/*
* Though the process will be instructed to die, demonstrate
* that Agent instances are to be explicitly prepared for
* garbage collection.
*/
if (remoteJob != null
&& iceProcessingState == IceProcessingState.TERMINATED)
{
remoteJob.start();
}
synchronized (remoteAgentMonitor)
{
remoteAgentMonitor.notifyAll();
}
}
}
}
}
public static class LocalPseudoTcpJob extends Thread implements Runnable
{
private DatagramSocket dgramSocket;
public LocalPseudoTcpJob(DatagramSocket socket)
throws UnknownHostException
{
this.dgramSocket = socket;
}
@Override
public void run()
{
logger.log(Level.FINEST, "Local pseudotcp worker started");
try
{
logger.log(Level.INFO,
"Local pseudotcp is using: "
+ dgramSocket.getLocalSocketAddress()+dgramSocket);
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket);
socket.setConversationID(1073741824);
//socket.setMTU(1500);
socket.setDebugName("L");
socket.accept(150000);
byte[] buffer = new byte[TEST_BYTES_COUNT];
int read = 0;
while (read != TEST_BYTES_COUNT)
{
read += socket.getInputStream().read(buffer);
logger.log(Level.FINEST, "Local job read: " + read);
}
//TODO: close when all received data is acked
//socket.close();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
logger.log(Level.FINEST, "Local pseudotcp worker finished");
}
}
public static class RemotePseudoTcpJob extends Thread implements Runnable
{
private DatagramSocket dgramSocket;
private InetSocketAddress peerAddr;
public RemotePseudoTcpJob(DatagramSocket socket,
InetSocketAddress peerAddr)
throws UnknownHostException
{
this.dgramSocket = socket;
this.peerAddr = peerAddr;
}
@Override
public void run()
{
logger.log(Level.FINEST, "Remote pseudotcp worker started");
try
{
logger.log(Level.INFO,
"Remote pseudotcp is using: " +
dgramSocket.getLocalSocketAddress()
+" and will comunicate with: " + peerAddr);
PseudoTcpSocket socket = new PseudoTcpSocketFactory().
createSocket(dgramSocket);
socket.setConversationID(1073741824);
//socket.setMTU(1500);
socket.setDebugName("R");
long start, end;
start = System.currentTimeMillis();
socket.connect(peerAddr, 150000);
byte[] buffer = new byte[TEST_BYTES_COUNT];
socket.getOutputStream().write(buffer);
socket.getOutputStream().flush();
//Socket will be closed by the iceAgent
//socket.close();
end = System.currentTimeMillis();
logger.log(Level.INFO,
"Transferred " + TEST_BYTES_COUNT
+ " bytes in " + ((end - start) / 1000) + " sec");
}
catch (IOException e)
{
throw new RuntimeException(e);
}
logger.log(Level.FINEST, "Remote pseudotcp worker finished");
}
}
}
| 14,214 | 0.540381 | 0.531876 | 403 | 34.302731 | 24.507509 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.895782 | false | false | 13 |
253e8c4901470803c5279d6daa1847da6c2bdace | 15,779,709,893,958 | 249484d69712c95664b5a929fb1f808276cb0099 | /app/src/main/java/com/rskj/productapp/sfinetw/utils/EnterpriserBasicListUtil.java | 24dc94f800c8943cf698fba112b7a0fe66dac2b0 | [] | no_license | fsh596847/SmeFinancingInformationNetwork | https://github.com/fsh596847/SmeFinancingInformationNetwork | b8a6fa239bd40654840635421d7f7aba05ad0acb | 10440ed000d0aa28effa4f68742d5d8868c02a0d | refs/heads/master | 2020-03-16T15:41:01.141000 | 2018-07-31T01:54:04 | 2018-07-31T01:54:04 | 132,754,471 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.rskj.productapp.sfinetw.utils;
import java.util.ArrayList;
import java.util.List;
public class EnterpriserBasicListUtil {
/**
* 还款方式
* <mat-option value="0">等额本息</mat-option>
* <mat-option value="1">等额本金</mat-option>
* <mat-option value="2">按期结息</mat-option>
* <mat-option value="3">利随本清</mat-option>
* <mat-option value="4">先息后本</mat-option>
* <mat-option value="5">等本等费</mat-option>
*/
public static List<String> repayment = new ArrayList() {
{
add("等额本息");
add("等额本金");
add("按期结息");
add("利随本清");
add("先息后本");
add("等本等费");
}
};
/**
* 担保方式
* <mat-option value="0">未知</mat-option> //兼容老数据
* <mat-option value="1">抵押</mat-option>
* <mat-option value="2">质押</mat-option>
* <mat-option value="3">信保基金</mat-option>
* <mat-option value="4">一般保证</mat-option>
* <mat-option value="5">信用</mat-option>
*/
public static List<String> guarantee = new ArrayList() {
{
add("未知");
add("抵押");
add("质押");
add("信保基金");
add("一般保证");
add("信用");
}
};
/**
* 还款期限
*/
public static List<String> repaymentPeriod = new ArrayList() {
{
add("3");
add("6");
add("9");
add("12");
add("18");
add("24");
add("36");
}
};
}
| UTF-8 | Java | 1,510 | java | EnterpriserBasicListUtil.java | Java | [] | null | [] | package com.rskj.productapp.sfinetw.utils;
import java.util.ArrayList;
import java.util.List;
public class EnterpriserBasicListUtil {
/**
* 还款方式
* <mat-option value="0">等额本息</mat-option>
* <mat-option value="1">等额本金</mat-option>
* <mat-option value="2">按期结息</mat-option>
* <mat-option value="3">利随本清</mat-option>
* <mat-option value="4">先息后本</mat-option>
* <mat-option value="5">等本等费</mat-option>
*/
public static List<String> repayment = new ArrayList() {
{
add("等额本息");
add("等额本金");
add("按期结息");
add("利随本清");
add("先息后本");
add("等本等费");
}
};
/**
* 担保方式
* <mat-option value="0">未知</mat-option> //兼容老数据
* <mat-option value="1">抵押</mat-option>
* <mat-option value="2">质押</mat-option>
* <mat-option value="3">信保基金</mat-option>
* <mat-option value="4">一般保证</mat-option>
* <mat-option value="5">信用</mat-option>
*/
public static List<String> guarantee = new ArrayList() {
{
add("未知");
add("抵押");
add("质押");
add("信保基金");
add("一般保证");
add("信用");
}
};
/**
* 还款期限
*/
public static List<String> repaymentPeriod = new ArrayList() {
{
add("3");
add("6");
add("9");
add("12");
add("18");
add("24");
add("36");
}
};
}
| 1,510 | 0.531915 | 0.514438 | 60 | 20.933332 | 17.47271 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.416667 | false | false | 13 |
9ad2ae6bd1284df7e3d117c488b8f679a9defe29 | 5,093,831,257,099 | 59ec553cd1cca93dd6225d1c14ccd7cb90c4b807 | /src/game/entities/sportsman/Skier.java | a291640a2e017f5c49dd77d24b70dd5bfea63798 | [] | no_license | Sean1511/Ski-competition | https://github.com/Sean1511/Ski-competition | 65b2ea4f9c75e562ed582ff8ecc629e294836d36 | f37888bbf70b43a65cb170651c795e2370e01543 | refs/heads/main | 2023-06-23T02:59:06.056000 | 2021-07-19T09:03:50 | 2021-07-19T09:03:50 | 387,401,632 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* @author Sean Assolin 311426118
* @author Ori Tabibi 205508971
*/
package game.entities.sportsman;
import game.enums.Discipline;
import game.enums.Gender;
import game.enums.League;
/**
* Class of the Skier
*/
public class Skier extends WinterSportsman {
/**
* Default Ctor for skier
*/
public Skier(){
super("Skier"+(getID()+1),12.0,Gender.MALE,5.0,40.0,Discipline.SLALOM,"Blue");
}
/**
* Non default ctor for Skier
* @param name the name of the competitor
* @param age the age of the competitor
* @param gender the gender of the competitor
* @param acceleration the acceleration of the competitor
* @param maxSpeed the max speed of the competitor
* @param discipline the discipline of the arena
*/
public Skier(String name, double age, Gender gender, double acceleration, double maxSpeed, Discipline discipline, String color) throws IllegalArgumentException {
super(name, age, gender, acceleration , maxSpeed, discipline, color);
}
/**
* Override method for toString
*/
public String toString() {
return ("Skier "+this.getName());
}
/**
* @return clone of skier
*/
public Skier Clone (){
String str = this.getName();
if (str.charAt(str.length()-1)=='1')
str = str.replace(str.substring(str.length()-1), "");
return new Skier(str+(WinterSportsman.ID+1),this.getAge(),this.getGender(),this.getAcceleration()- League.calcAccelerationBonus(this.getAge()),this.getMaxSpeed(),this.getDiscipline(), this.getColor());
}
}
| UTF-8 | Java | 1,661 | java | Skier.java | Java | [
{
"context": "/**\r\n * @author Sean Assolin 311426118\r\n * @author Ori Tabibi 205508971\r\n */\r\n",
"end": 28,
"score": 0.9998610615730286,
"start": 16,
"tag": "NAME",
"value": "Sean Assolin"
},
{
"context": "/**\r\n * @author Sean Assolin 311426118\r\n * @author Ori Tabibi 205508... | null | [] | /**
* @author <NAME> 311426118
* @author <NAME> 205508971
*/
package game.entities.sportsman;
import game.enums.Discipline;
import game.enums.Gender;
import game.enums.League;
/**
* Class of the Skier
*/
public class Skier extends WinterSportsman {
/**
* Default Ctor for skier
*/
public Skier(){
super("Skier"+(getID()+1),12.0,Gender.MALE,5.0,40.0,Discipline.SLALOM,"Blue");
}
/**
* Non default ctor for Skier
* @param name the name of the competitor
* @param age the age of the competitor
* @param gender the gender of the competitor
* @param acceleration the acceleration of the competitor
* @param maxSpeed the max speed of the competitor
* @param discipline the discipline of the arena
*/
public Skier(String name, double age, Gender gender, double acceleration, double maxSpeed, Discipline discipline, String color) throws IllegalArgumentException {
super(name, age, gender, acceleration , maxSpeed, discipline, color);
}
/**
* Override method for toString
*/
public String toString() {
return ("Skier "+this.getName());
}
/**
* @return clone of skier
*/
public Skier Clone (){
String str = this.getName();
if (str.charAt(str.length()-1)=='1')
str = str.replace(str.substring(str.length()-1), "");
return new Skier(str+(WinterSportsman.ID+1),this.getAge(),this.getGender(),this.getAcceleration()- League.calcAccelerationBonus(this.getAge()),this.getMaxSpeed(),this.getDiscipline(), this.getColor());
}
}
| 1,651 | 0.630343 | 0.61168 | 52 | 29.942308 | 38.322727 | 209 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.673077 | false | false | 13 |
e01e9d8838bdc81178e64a11cf474624c411c32e | 29,721,173,722,403 | 2ebd402497b292ce6514f877e3f3e650c9860917 | /app/src/main/java/com/rana/ranawords/StartActivity.java | 6743a101f15d5fba6ddac305123f34def0756c06 | [] | no_license | ilredirana/BeiDanCi | https://github.com/ilredirana/BeiDanCi | b1d1c775b6e8a62713c93539a4cd6c77b5cd58e3 | dbf0b112328bda2983de68b543aa00ffd592e709 | refs/heads/master | 2018-01-09T14:11:31.787000 | 2015-12-02T10:37:40 | 2015-12-02T10:37:40 | 44,423,653 | 0 | 0 | null | false | 2015-11-20T15:07:54 | 2015-10-17T04:12:59 | 2015-10-17T04:14:56 | 2015-11-20T15:07:53 | 1,679 | 0 | 0 | 0 | Java | null | null | package com.rana.ranawords;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.rana.ranawords.bases.DataBaseUtil;
import com.rana.ranawords.bases.MyDatabaseOperator;
public class StartActivity extends AppCompatActivity implements View.OnClickListener {
SharedPreferences preferences ;
TextView text_show_progress;
TextView text_show_not_understood_number;
TextView information;
FloatingActionButton fab;
int progress;
int num_not_understand;
int num_learned;
Intent toDetailActivity;
Snackbar snackbar;
boolean isShowing;
MyDatabaseOperator databaseOperator;
DataBaseUtil util;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//如果第一次使用本应用,则初始化数据库和属性
util = new DataBaseUtil(this);
preferences = getSharedPreferences("preferences",MODE_PRIVATE);
//跳转到单词详情的intent
toDetailActivity = new Intent(StartActivity.this,DetailActivity.class);
//初始化activity中的几个view
information = (TextView) findViewById(R.id.information_in_start_activity);
text_show_progress = (TextView) findViewById(R.id.progress_in_start_activity);
text_show_not_understood_number = (TextView) findViewById(R.id.not_understood_number);
fab = (FloatingActionButton) findViewById(R.id.fam);
//给按钮设置点击事件
fab.setOnClickListener(this);
}
@Override
protected void onResume() {
initialDatabase();
//数据库操作类
databaseOperator = new MyDatabaseOperator();
/*
更新显示和属性
*/
updateViews();
super.onResume();
// isShowing = false;
updateSnackBar();
}
//重置snackbar,不然snackbar会隐身。。。
private void updateSnackBar(){
snackbar = Snackbar.make(fab, "还有未掌握单词哟\n学习新词还是复习呢?", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.CYAN)
.setAction("复习", new View.OnClickListener() {
@Override
public void onClick(View view) {
toDetailActivity.putExtra("mode", "review");
toDetailActivity.putExtra("progress", 1);
startActivity(toDetailActivity);
}
});
}
//获取应用属性值并显示在TextView中,并把进度装进intent去
private void updateViews(){
//获得评分为(0,5)分间的所有单词指针对象
num_not_understand = databaseOperator.getNotMasteredWordsNumber();
//得到未掌握单词数量
num_learned = databaseOperator.getLearnedWordsNumber();
progress = preferences.getInt("progress", 1);
toDetailActivity.putExtra("progress", progress);
if (progress==1){
information.setText("第一次用哇o(^▽^)o\n点击√开始学习吧q(≧▽≦q)");
}else if (progress>38220){
information.setText("上次学到最后一个(⊙o⊙)");
toDetailActivity.putExtra("progress",1);
}
else{
information.setText(String.format("上次学到第%d个单词\n点击√继续学习吧q(≧▽≦q)", progress+1));
}
text_show_progress.setText(String.format("%d\n/已学过", num_learned));
text_show_not_understood_number.setText(String.format("%d\n/未掌握", num_not_understand));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//创建菜单
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_start, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
菜单选项被点击
*/
int id = item.getItemId();
switch (id){
case R.id.action_settings:
startActivity(new Intent(StartActivity.this,SettingActivity.class));
return true;
case R.id.action_instruction:
startActivity(new Intent(StartActivity.this,InstructionActivity.class));
return true;
case R.id.button_to_review:
if (num_not_understand!=0){
Intent intent = new Intent(StartActivity.this,ListActivity.class);
intent.putExtra("show what","review");
startActivity(intent);
}else {
Snackbar.make(fab,"没有未掌握单词哟,去学习新词吧",Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.CYAN)
.setAction("好的", new View.OnClickListener() {
@Override
public void onClick(View v) {
toDetailActivity.putExtra("mode", "study");
startActivity(toDetailActivity);
}
}).show();
}
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void initialDatabase() {
// 判断数据库是否存在
boolean dbExist = util.checkDataBase();
if (!dbExist) {
// 不存在就把raw里的数据库写入手机
util.copyDataBase();
}
}
@Override
public void onClick(View view) {
//跳转到单词详情的intent,设置学习模式为study
switch (view.getId()){
case R.id.fam:
/*
需求:如果有未掌握单词时,点击fab会弹出snackBar,snackBar的action按钮会提示是否复习,
有snackBar在时再点击fab会直接进入新单词学习
如果没有未掌握单词则直接进study模式的DetailActivity
思路:研究了半天,最后还是用callback做个flag就好了。。。
*/
if (num_not_understand==0||isShowing){
toDetailActivity.putExtra("mode", "study");
startActivity(toDetailActivity);
break;
}
snackbar.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
isShowing = false;
updateSnackBar();
}
@Override
public void onShown(Snackbar snackbar) {
super.onShown(snackbar);
isShowing = true;
}
});
if (!isShowing){
snackbar.show();
}
break;
}
}
@Override
protected void onDestroy() {
//如果就这么关掉会在使用最近任务打开本app时报一个不能开打已关闭的数据库异常,先去掉再想办法
// databaseOperator.closeDatabase();
super.onDestroy();
}
}
| UTF-8 | Java | 7,927 | java | StartActivity.java | Java | [] | null | [] | package com.rana.ranawords;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.rana.ranawords.bases.DataBaseUtil;
import com.rana.ranawords.bases.MyDatabaseOperator;
public class StartActivity extends AppCompatActivity implements View.OnClickListener {
SharedPreferences preferences ;
TextView text_show_progress;
TextView text_show_not_understood_number;
TextView information;
FloatingActionButton fab;
int progress;
int num_not_understand;
int num_learned;
Intent toDetailActivity;
Snackbar snackbar;
boolean isShowing;
MyDatabaseOperator databaseOperator;
DataBaseUtil util;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//如果第一次使用本应用,则初始化数据库和属性
util = new DataBaseUtil(this);
preferences = getSharedPreferences("preferences",MODE_PRIVATE);
//跳转到单词详情的intent
toDetailActivity = new Intent(StartActivity.this,DetailActivity.class);
//初始化activity中的几个view
information = (TextView) findViewById(R.id.information_in_start_activity);
text_show_progress = (TextView) findViewById(R.id.progress_in_start_activity);
text_show_not_understood_number = (TextView) findViewById(R.id.not_understood_number);
fab = (FloatingActionButton) findViewById(R.id.fam);
//给按钮设置点击事件
fab.setOnClickListener(this);
}
@Override
protected void onResume() {
initialDatabase();
//数据库操作类
databaseOperator = new MyDatabaseOperator();
/*
更新显示和属性
*/
updateViews();
super.onResume();
// isShowing = false;
updateSnackBar();
}
//重置snackbar,不然snackbar会隐身。。。
private void updateSnackBar(){
snackbar = Snackbar.make(fab, "还有未掌握单词哟\n学习新词还是复习呢?", Snackbar.LENGTH_LONG)
.setActionTextColor(Color.CYAN)
.setAction("复习", new View.OnClickListener() {
@Override
public void onClick(View view) {
toDetailActivity.putExtra("mode", "review");
toDetailActivity.putExtra("progress", 1);
startActivity(toDetailActivity);
}
});
}
//获取应用属性值并显示在TextView中,并把进度装进intent去
private void updateViews(){
//获得评分为(0,5)分间的所有单词指针对象
num_not_understand = databaseOperator.getNotMasteredWordsNumber();
//得到未掌握单词数量
num_learned = databaseOperator.getLearnedWordsNumber();
progress = preferences.getInt("progress", 1);
toDetailActivity.putExtra("progress", progress);
if (progress==1){
information.setText("第一次用哇o(^▽^)o\n点击√开始学习吧q(≧▽≦q)");
}else if (progress>38220){
information.setText("上次学到最后一个(⊙o⊙)");
toDetailActivity.putExtra("progress",1);
}
else{
information.setText(String.format("上次学到第%d个单词\n点击√继续学习吧q(≧▽≦q)", progress+1));
}
text_show_progress.setText(String.format("%d\n/已学过", num_learned));
text_show_not_understood_number.setText(String.format("%d\n/未掌握", num_not_understand));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//创建菜单
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_start, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
菜单选项被点击
*/
int id = item.getItemId();
switch (id){
case R.id.action_settings:
startActivity(new Intent(StartActivity.this,SettingActivity.class));
return true;
case R.id.action_instruction:
startActivity(new Intent(StartActivity.this,InstructionActivity.class));
return true;
case R.id.button_to_review:
if (num_not_understand!=0){
Intent intent = new Intent(StartActivity.this,ListActivity.class);
intent.putExtra("show what","review");
startActivity(intent);
}else {
Snackbar.make(fab,"没有未掌握单词哟,去学习新词吧",Snackbar.LENGTH_SHORT)
.setActionTextColor(Color.CYAN)
.setAction("好的", new View.OnClickListener() {
@Override
public void onClick(View v) {
toDetailActivity.putExtra("mode", "study");
startActivity(toDetailActivity);
}
}).show();
}
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void initialDatabase() {
// 判断数据库是否存在
boolean dbExist = util.checkDataBase();
if (!dbExist) {
// 不存在就把raw里的数据库写入手机
util.copyDataBase();
}
}
@Override
public void onClick(View view) {
//跳转到单词详情的intent,设置学习模式为study
switch (view.getId()){
case R.id.fam:
/*
需求:如果有未掌握单词时,点击fab会弹出snackBar,snackBar的action按钮会提示是否复习,
有snackBar在时再点击fab会直接进入新单词学习
如果没有未掌握单词则直接进study模式的DetailActivity
思路:研究了半天,最后还是用callback做个flag就好了。。。
*/
if (num_not_understand==0||isShowing){
toDetailActivity.putExtra("mode", "study");
startActivity(toDetailActivity);
break;
}
snackbar.setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
isShowing = false;
updateSnackBar();
}
@Override
public void onShown(Snackbar snackbar) {
super.onShown(snackbar);
isShowing = true;
}
});
if (!isShowing){
snackbar.show();
}
break;
}
}
@Override
protected void onDestroy() {
//如果就这么关掉会在使用最近任务打开本app时报一个不能开打已关闭的数据库异常,先去掉再想办法
// databaseOperator.closeDatabase();
super.onDestroy();
}
}
| 7,927 | 0.573101 | 0.570871 | 224 | 31.03125 | 24.593189 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540179 | false | false | 13 |
a7168d0065fe852a9aaeffe245b23f0b4273a03e | 29,721,173,721,312 | 2fbe2979ece6a3e0bd19c70c1c9557defb0b6332 | /src/Opgave2_11.java | cc7037399b99f464265105b23d677492ade9e15f | [] | no_license | Mewmewww/Kapitel2Programmering | https://github.com/Mewmewww/Kapitel2Programmering | a38d69dc47c260432d6a9b061e61d7f453006bb5 | 6f493cdf3c04e6c89fe6dd654a7808040bad5892 | refs/heads/master | 2022-12-18T20:43:55.710000 | 2020-09-15T12:07:10 | 2020-09-15T12:07:10 | 295,715,249 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class Opgave2_11 {
public static void main(String[] args) {
// Defining all known variables
System.out.println("Enter value in years");
Scanner input = new Scanner(System.in);
double year = input.nextDouble();
double birth = 7.0;
double death = 13.0;
double immigrant = 45.0;
double currentpopulation = 312032486;
// Defining how many seconds there is in a year - as all our previously defined variables are all calculated
// in seconds.
double yearlyseconds = (365 * 24 * 60 * 60);
// Simply divide the yearly seconds with the aforementioned variables.
double intbirth = (yearlyseconds / birth);
double intdeath = (yearlyseconds / death);
double intimmigrant = (yearlyseconds / immigrant);
// Making a loop, that only calculates from the beginning year to 5 years ahead.
for (int i = 1; i <= year; i++) {
currentpopulation += intbirth + intimmigrant - intdeath;
// Printing out the year, followed up with an value of 1 -> 5 to underline what year it is.
// Followed up by = and the current population for that year calculated in integers, so that
// the values aren't shown in E^
System.out.println("Year" + i + "=" + (int)currentpopulation);
}
}
}
| UTF-8 | Java | 1,397 | java | Opgave2_11.java | Java | [] | null | [] | import java.util.Scanner;
public class Opgave2_11 {
public static void main(String[] args) {
// Defining all known variables
System.out.println("Enter value in years");
Scanner input = new Scanner(System.in);
double year = input.nextDouble();
double birth = 7.0;
double death = 13.0;
double immigrant = 45.0;
double currentpopulation = 312032486;
// Defining how many seconds there is in a year - as all our previously defined variables are all calculated
// in seconds.
double yearlyseconds = (365 * 24 * 60 * 60);
// Simply divide the yearly seconds with the aforementioned variables.
double intbirth = (yearlyseconds / birth);
double intdeath = (yearlyseconds / death);
double intimmigrant = (yearlyseconds / immigrant);
// Making a loop, that only calculates from the beginning year to 5 years ahead.
for (int i = 1; i <= year; i++) {
currentpopulation += intbirth + intimmigrant - intdeath;
// Printing out the year, followed up with an value of 1 -> 5 to underline what year it is.
// Followed up by = and the current population for that year calculated in integers, so that
// the values aren't shown in E^
System.out.println("Year" + i + "=" + (int)currentpopulation);
}
}
}
| 1,397 | 0.621331 | 0.597709 | 30 | 45.566666 | 30.306967 | 116 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633333 | false | false | 13 |
f5db9131364fa631e4df10bb8c3833160bf29429 | 11,304,353,949,082 | 21791e98a9db6086f6d2bde9319955b83810ba0f | /HelloWorld.java | 4723d2f35d58b000eb873f73c05cb29a4d34f1dd | [] | no_license | RCipullo/Hello-World | https://github.com/RCipullo/Hello-World | fb6ee57899ad690f7fda5e3b9c1a97ed2a432dd8 | 67684a9f998ba521ca94ad1b41a951411bb72ed8 | refs/heads/master | 2021-05-06T02:11:51.942000 | 2017-12-17T02:45:54 | 2017-12-17T02:45:54 | 114,504,234 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //CS 1301
//Summer
//Ryan Cipullo
//Dr. North
//Assignment 1
import java.util.Scanner;
public class HelloWorld
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.print("Please enter your name:k");
String name= s.nextLine();
System.out.println("Hello "+ name + "!");
}
} | UTF-8 | Java | 330 | java | HelloWorld.java | Java | [
{
"context": "//CS 1301\n//Summer \n//Ryan Cipullo\n//Dr. North\n//Assignment 1\nimport java.util.Scann",
"end": 34,
"score": 0.9998889565467834,
"start": 22,
"tag": "NAME",
"value": "Ryan Cipullo"
}
] | null | [] | //CS 1301
//Summer
//<NAME>
//Dr. North
//Assignment 1
import java.util.Scanner;
public class HelloWorld
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.print("Please enter your name:k");
String name= s.nextLine();
System.out.println("Hello "+ name + "!");
}
} | 324 | 0.657576 | 0.642424 | 16 | 19.6875 | 15.845815 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.3125 | false | false | 13 |
8415629c3b8497875c228ba76c7510ab400d3311 | 16,217,796,531,596 | 46eaec4a936aac0288ba9a67bfd0a30e22d081f3 | /Avancado/src/br/com/bino/avancado/ifaces/simplefactory/Message.java | 9e46c8ca28004b10327f85bc4a9832ea044cc17a | [] | no_license | devBino/corporacaoCapsula | https://github.com/devBino/corporacaoCapsula | 5776cb2850bdd87ed85c71fcd7511648f81c4c53 | bf59c1f47f281802f46d9d7b7a406683349e77a2 | refs/heads/main | 2023-09-06T09:12:22.129000 | 2022-09-19T11:53:06 | 2022-09-19T11:53:06 | 418,759,262 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package br.com.bino.avancado.ifaces.simplefactory;
public interface Message {
void send(String pMsg);
}
| UTF-8 | Java | 109 | java | Message.java | Java | [] | null | [] | package br.com.bino.avancado.ifaces.simplefactory;
public interface Message {
void send(String pMsg);
}
| 109 | 0.761468 | 0.761468 | 7 | 14.571428 | 17.998867 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.571429 | false | false | 13 |
51a481e87ed8d9ef86223d89cc4c591df643ae95 | 33,028,298,547,115 | ca03cd77b25c20c62925a3d33262b2bdf84da389 | /palo-it-quizz-features/palo-it-quizz-webapp/src/main/java/com/paloit/quizz/dao/QuizzDao.java | f4c01a6737eeac5d944e78b4603f8bd399c14178 | [] | no_license | Palo-IT/palo-it-quizz | https://github.com/Palo-IT/palo-it-quizz | 90211bd73bd9b1521fcc35ddd496b25dcaea0312 | 8fbaea5e1d2c5ae02c9d0b99786e25042c596406 | refs/heads/master | 2016-09-11T11:55:03.024000 | 2013-03-27T22:16:24 | 2013-03-27T22:16:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Palo IT source code:
* ======================
* Links:
* ======
* Homepage : http://palo-it.com/
* Git : https://github.com/Palo-IT
*/
package com.paloit.quizz.dao;
import javax.inject.Named;
import org.jboss.seam.transaction.Transactional;
import org.palo.it.quizz.android.core.model.Quizz;
import com.paloit.quizz.dao.support.GenericDao;
/**
* QuizzService
*
* @author fred
* @since Mar 14, 2013
*/
@Named
@Transactional
public class QuizzDao extends GenericDao<Quizz, Integer> {
public QuizzDao() {
super(Quizz.class);
}
public Quizz getNew() {
return new Quizz();
}
}
| UTF-8 | Java | 649 | java | QuizzDao.java | Java | [
{
"context": "//palo-it.com/\n * Git : https://github.com/Palo-IT\n */\npackage com.paloit.quizz.dao;\n\nimport javax.i",
"end": 159,
"score": 0.9993194937705994,
"start": 152,
"tag": "USERNAME",
"value": "Palo-IT"
},
{
"context": "rt.GenericDao;\n\n/**\n * QuizzService\n * \n... | null | [] | /*
* Palo IT source code:
* ======================
* Links:
* ======
* Homepage : http://palo-it.com/
* Git : https://github.com/Palo-IT
*/
package com.paloit.quizz.dao;
import javax.inject.Named;
import org.jboss.seam.transaction.Transactional;
import org.palo.it.quizz.android.core.model.Quizz;
import com.paloit.quizz.dao.support.GenericDao;
/**
* QuizzService
*
* @author fred
* @since Mar 14, 2013
*/
@Named
@Transactional
public class QuizzDao extends GenericDao<Quizz, Integer> {
public QuizzDao() {
super(Quizz.class);
}
public Quizz getNew() {
return new Quizz();
}
}
| 649 | 0.610169 | 0.600924 | 35 | 17.542856 | 16.644764 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.257143 | false | false | 13 |
8dd92e6b9cc46d7da0a176a7a4e4b1b2d68a803f | 17,660,905,546,975 | 61051f7d4466b965730c2f3ab21ba6f882d508b4 | /app/src/main/java/me/balaaagi/popularmovies/domains/PopularMovieApiResponse.java | f04febef4e7722829b4c5e9549a3ceadb1fba029 | [] | no_license | balaaagi/PopularMovies | https://github.com/balaaagi/PopularMovies | d32cda1399bd1a3683eb2734e62f318cfb9d6309 | 1bf78829fce53631e19ef685277e383fb4de8395 | refs/heads/master | 2019-08-09T15:27:48.275000 | 2017-08-22T05:03:21 | 2017-08-22T05:03:21 | 54,050,041 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.balaaagi.popularmovies.domains;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by BALAJI SRINIVASAN on 8/3/2017.
*/
public class PopularMovieApiResponse {
@SerializedName("results")
List<MovieResults> results;
public List<MovieResults> getResults() {
return results;
}
public void setResults(List<MovieResults> results) {
this.results = results;
}
}
| UTF-8 | Java | 451 | java | PopularMovieApiResponse.java | Java | [
{
"context": "dName;\n\nimport java.util.List;\n\n\n/**\n * Created by BALAJI SRINIVASAN on 8/3/2017.\n */\n\npublic class PopularMovieApiRes",
"end": 156,
"score": 0.99985271692276,
"start": 139,
"tag": "NAME",
"value": "BALAJI SRINIVASAN"
}
] | null | [] | package me.balaaagi.popularmovies.domains;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by <NAME> on 8/3/2017.
*/
public class PopularMovieApiResponse {
@SerializedName("results")
List<MovieResults> results;
public List<MovieResults> getResults() {
return results;
}
public void setResults(List<MovieResults> results) {
this.results = results;
}
}
| 440 | 0.700665 | 0.687361 | 23 | 18.608696 | 19.399101 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.26087 | false | false | 13 |
09c5ab9f11b462a180d9c4ace491edc9182b0cee | 32,040,456,094,269 | 1babccd8fe82e4882a3878264fe7fc3777aaa1c0 | /hibernate_pojo_connector/com/demo/model/com/demo/model/SchemaTableStatisticsWithBuffer.java | c2866c14da2347be492337858175901b832a3cfa | [] | no_license | ggswineroom/hibernate_pojo_connector | https://github.com/ggswineroom/hibernate_pojo_connector | 544ce842b72f583ebb1c0057dd3bf984fd4fb19a | 33ce7aae351ecfbff8bf23f5fd2dc9814d786ba6 | refs/heads/master | 2023-03-23T16:33:42.553000 | 2021-03-20T00:44:58 | 2021-03-20T00:44:58 | 349,591,373 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.demo.model;
// Generated Mar 3, 2021, 12:02:21 PM by Hibernate Tools 5.4.27.Final
/**
* SchemaTableStatisticsWithBuffer generated by hbm2java
*/
public class SchemaTableStatisticsWithBuffer implements java.io.Serializable {
private SchemaTableStatisticsWithBufferId id;
public SchemaTableStatisticsWithBuffer() {
}
public SchemaTableStatisticsWithBuffer(SchemaTableStatisticsWithBufferId id) {
this.id = id;
}
public SchemaTableStatisticsWithBufferId getId() {
return this.id;
}
public void setId(SchemaTableStatisticsWithBufferId id) {
this.id = id;
}
}
| UTF-8 | Java | 617 | java | SchemaTableStatisticsWithBuffer.java | Java | [] | null | [] | package com.demo.model;
// Generated Mar 3, 2021, 12:02:21 PM by Hibernate Tools 5.4.27.Final
/**
* SchemaTableStatisticsWithBuffer generated by hbm2java
*/
public class SchemaTableStatisticsWithBuffer implements java.io.Serializable {
private SchemaTableStatisticsWithBufferId id;
public SchemaTableStatisticsWithBuffer() {
}
public SchemaTableStatisticsWithBuffer(SchemaTableStatisticsWithBufferId id) {
this.id = id;
}
public SchemaTableStatisticsWithBufferId getId() {
return this.id;
}
public void setId(SchemaTableStatisticsWithBufferId id) {
this.id = id;
}
}
| 617 | 0.748784 | 0.722853 | 26 | 21.73077 | 27.158449 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 9 |
94a828df1456ac456686473d1f86d9474372d4b7 | 20,323,785,299,176 | 17bb7a348ff15313edd72f230106013960c03432 | /src/edu/uci/plrg/cfi/x86/merge/graph/hash/ContextMatchState.java | aa6f53de0755820b8823e66d2cc54f3617ce88cb | [] | no_license | uci-plrg/cfi-x86-merge | https://github.com/uci-plrg/cfi-x86-merge | e3210bccf0ee6dad16ccaacee2606f9ca825fec4 | ec6c04711d9e67b35abdae650bfec16542a4ca4a | refs/heads/master | 2020-12-19T04:34:57.761000 | 2016-08-02T03:23:12 | 2016-08-02T03:23:12 | 64,704,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.uci.plrg.cfi.x86.merge.graph.hash;
public class ContextMatchState {
int index;
int matchedNodeCount;
int comparedNodeCount;
boolean fail;
boolean mismatch;
boolean reachedTargetDepth;
boolean hasAmbiguity;
boolean complete;
void copyTo(ContextMatchState target) {
target.index = index;
target.matchedNodeCount = matchedNodeCount;
target.comparedNodeCount = comparedNodeCount;
target.reachedTargetDepth = reachedTargetDepth;
target.hasAmbiguity = hasAmbiguity;
target.complete = complete;
target.fail = false;
}
public boolean isFailed() {
return fail;
}
public int getMatchedNodeCount() {
return matchedNodeCount;
}
public int getComparedNodeCount() {
return comparedNodeCount;
}
public boolean isMismatch() {
return mismatch;
}
public boolean isReachedTargetDepth() {
return reachedTargetDepth;
}
public boolean isHasAmbiguity() {
return hasAmbiguity;
}
public boolean isComplete() {
return complete;
}
}
| UTF-8 | Java | 982 | java | ContextMatchState.java | Java | [] | null | [] | package edu.uci.plrg.cfi.x86.merge.graph.hash;
public class ContextMatchState {
int index;
int matchedNodeCount;
int comparedNodeCount;
boolean fail;
boolean mismatch;
boolean reachedTargetDepth;
boolean hasAmbiguity;
boolean complete;
void copyTo(ContextMatchState target) {
target.index = index;
target.matchedNodeCount = matchedNodeCount;
target.comparedNodeCount = comparedNodeCount;
target.reachedTargetDepth = reachedTargetDepth;
target.hasAmbiguity = hasAmbiguity;
target.complete = complete;
target.fail = false;
}
public boolean isFailed() {
return fail;
}
public int getMatchedNodeCount() {
return matchedNodeCount;
}
public int getComparedNodeCount() {
return comparedNodeCount;
}
public boolean isMismatch() {
return mismatch;
}
public boolean isReachedTargetDepth() {
return reachedTargetDepth;
}
public boolean isHasAmbiguity() {
return hasAmbiguity;
}
public boolean isComplete() {
return complete;
}
}
| 982 | 0.755601 | 0.753564 | 51 | 18.254902 | 15.505651 | 49 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.509804 | false | false | 9 |
8b1ffaec6d430cb43aced9f31062fc99494f6d75 | 31,834,297,647,856 | da791a0196aeb247a113a8c0c006d480572877ba | /src/test/java/de/codecentric/centerdevice/sample/StandardMacApp.java | 44de8054fcf0c97cc1896ce2d06e33c8d4b1065d | [] | permissive | codecentric/NSMenuFX | https://github.com/codecentric/NSMenuFX | 24939a8e5e591d61c5445b2bbb0bd35e8d4914c1 | a978b1835d073a9921bee8ba8181cde50a5d0a4f | refs/heads/master | 2023-03-26T08:55:56.063000 | 2020-11-20T07:22:39 | 2020-11-20T07:22:39 | 33,120,191 | 147 | 31 | BSD-3-Clause | false | 2020-11-24T19:48:58 | 2015-03-30T11:50:53 | 2020-11-20T19:48:50 | 2020-11-24T19:48:50 | 1,898 | 126 | 18 | 10 | Java | false | false | package de.codecentric.centerdevice.sample;
import de.codecentric.centerdevice.MenuToolkit;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* Skeleton for Standard Macintosh Application See:
* "OS X Human Interface Guidelines"
*/
public class StandardMacApp extends Application {
static final String appName = "Standard";
static final String mainWindowTitle = "Main";
static final String childWindowTitle = "Child";
static long counter = 1;
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
Button button = new Button();
button.setText("Create new Stage");
button.setOnAction(action -> createNewStage());
root.getChildren().add(button);
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.requestFocus();
primaryStage.setTitle(mainWindowTitle);
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
MenuBar bar = new MenuBar();
// Application Menu
// TBD: services menu
Menu appMenu = new Menu(appName); // Name for appMenu can't be set at
// Runtime
MenuItem aboutItem = tk.createAboutMenuItem(appName);
MenuItem prefsItem = new MenuItem("Preferences...");
appMenu.getItems().addAll(aboutItem, new SeparatorMenuItem(), prefsItem, new SeparatorMenuItem(),
tk.createHideMenuItem(appName), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(),
new SeparatorMenuItem(), tk.createQuitMenuItem(appName));
// File Menu (items TBD)
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New...");
fileMenu.getItems().addAll(newItem, new SeparatorMenuItem(), tk.createCloseWindowMenuItem(),
new SeparatorMenuItem(), new MenuItem("TBD"));
// Edit (items TBD)
Menu editMenu = new Menu("Edit");
editMenu.getItems().addAll(new MenuItem("TBD"));
// Format (items TBD)
Menu formatMenu = new Menu("Format");
formatMenu.getItems().addAll(new MenuItem("TBD"));
// View Menu (items TBD)
Menu viewMenu = new Menu("View");
viewMenu.getItems().addAll(new MenuItem("TBD"));
// Window Menu
// TBD standard window menu items
Menu windowMenu = new Menu("Window");
windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(),
new SeparatorMenuItem(), tk.createBringAllToFrontItem());
// Help Menu (items TBD)
Menu helpMenu = new Menu("Help");
helpMenu.getItems().addAll(new MenuItem("TBD"));
bar.getMenus().addAll(appMenu, fileMenu, editMenu, formatMenu, viewMenu, windowMenu, helpMenu);
tk.autoAddWindowMenuItems(windowMenu);
tk.setGlobalMenuBar(bar);
}
private void createNewStage() {
Stage stage = new Stage();
stage.setScene(new Scene(new StackPane()));
stage.setTitle(childWindowTitle + " " + (counter++));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| UTF-8 | Java | 3,128 | java | StandardMacApp.java | Java | [] | null | [] | package de.codecentric.centerdevice.sample;
import de.codecentric.centerdevice.MenuToolkit;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* Skeleton for Standard Macintosh Application See:
* "OS X Human Interface Guidelines"
*/
public class StandardMacApp extends Application {
static final String appName = "Standard";
static final String mainWindowTitle = "Main";
static final String childWindowTitle = "Child";
static long counter = 1;
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
Button button = new Button();
button.setText("Create new Stage");
button.setOnAction(action -> createNewStage());
root.getChildren().add(button);
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.requestFocus();
primaryStage.setTitle(mainWindowTitle);
primaryStage.show();
MenuToolkit tk = MenuToolkit.toolkit();
MenuBar bar = new MenuBar();
// Application Menu
// TBD: services menu
Menu appMenu = new Menu(appName); // Name for appMenu can't be set at
// Runtime
MenuItem aboutItem = tk.createAboutMenuItem(appName);
MenuItem prefsItem = new MenuItem("Preferences...");
appMenu.getItems().addAll(aboutItem, new SeparatorMenuItem(), prefsItem, new SeparatorMenuItem(),
tk.createHideMenuItem(appName), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(),
new SeparatorMenuItem(), tk.createQuitMenuItem(appName));
// File Menu (items TBD)
Menu fileMenu = new Menu("File");
MenuItem newItem = new MenuItem("New...");
fileMenu.getItems().addAll(newItem, new SeparatorMenuItem(), tk.createCloseWindowMenuItem(),
new SeparatorMenuItem(), new MenuItem("TBD"));
// Edit (items TBD)
Menu editMenu = new Menu("Edit");
editMenu.getItems().addAll(new MenuItem("TBD"));
// Format (items TBD)
Menu formatMenu = new Menu("Format");
formatMenu.getItems().addAll(new MenuItem("TBD"));
// View Menu (items TBD)
Menu viewMenu = new Menu("View");
viewMenu.getItems().addAll(new MenuItem("TBD"));
// Window Menu
// TBD standard window menu items
Menu windowMenu = new Menu("Window");
windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(),
new SeparatorMenuItem(), tk.createBringAllToFrontItem());
// Help Menu (items TBD)
Menu helpMenu = new Menu("Help");
helpMenu.getItems().addAll(new MenuItem("TBD"));
bar.getMenus().addAll(appMenu, fileMenu, editMenu, formatMenu, viewMenu, windowMenu, helpMenu);
tk.autoAddWindowMenuItems(windowMenu);
tk.setGlobalMenuBar(bar);
}
private void createNewStage() {
Stage stage = new Stage();
stage.setScene(new Scene(new StackPane()));
stage.setTitle(childWindowTitle + " " + (counter++));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 3,128 | 0.731458 | 0.72922 | 96 | 31.583334 | 24.912624 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.114583 | false | false | 9 |
7926792f235e58be1713437b10e0c1095e56e135 | 11,467,562,687,199 | 950912675971db58ee41a27716fdfe986ffb6ff6 | /Innlevering2/SMSAPP/app/src/main/java/com/ntnu/gard/smsapp/MessageListAdapter.java | 6394696ff1f09cb4352234687e99bb0dc0412479 | [] | no_license | GardEngen/Mobil | https://github.com/GardEngen/Mobil | 8fcb81164b994a9c764cd834fb8d04550613701d | 08100299062a9bc91d699b989324ec3b396a28a8 | refs/heads/master | 2021-06-09T05:19:52.086000 | 2016-10-21T10:59:29 | 2016-10-21T10:59:29 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ntnu.gard.smsapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by mikael on 01.09.2016.
*/
public class MessageListAdapter extends ArrayAdapter<Message> {
public MessageListAdapter(Context context, List<Message> messages) {
super(context, 0, messages);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.messagelist_item_layout, parent, false);
}
//ImageView person = (ImageView)convertView.findViewById(R.id.imageView);
TextView messageView = (TextView) convertView.findViewById(R.id.textView);
messageView.setText(message.getMessage());
return convertView;
}
}
| UTF-8 | Java | 1,087 | java | MessageListAdapter.java | Java | [
{
"context": "xtView;\n\nimport java.util.List;\n\n/**\n * Created by mikael on 01.09.2016.\n */\n\npublic class MessageListAdapt",
"end": 316,
"score": 0.8947975039482117,
"start": 310,
"tag": "USERNAME",
"value": "mikael"
}
] | null | [] | package com.ntnu.gard.smsapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by mikael on 01.09.2016.
*/
public class MessageListAdapter extends ArrayAdapter<Message> {
public MessageListAdapter(Context context, List<Message> messages) {
super(context, 0, messages);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.messagelist_item_layout, parent, false);
}
//ImageView person = (ImageView)convertView.findViewById(R.id.imageView);
TextView messageView = (TextView) convertView.findViewById(R.id.textView);
messageView.setText(message.getMessage());
return convertView;
}
}
| 1,087 | 0.713891 | 0.705612 | 39 | 26.846153 | 28.615522 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.589744 | false | false | 9 |
9316c24d307bcde12cacd2bec8f1abc6dec3d835 | 31,035,433,749,834 | b7dd54e8ee3837bd77621d3586aa7487c379d485 | /src/main/java/cn/comgroup/tzmedia/server/admin/entity/UserCoupon.java | e2c66d0abc3740a492e059f59c71f2c395b8929c | [] | no_license | harry1115/tzzj | https://github.com/harry1115/tzzj | df257d5ef527c4f9c0372070ed0914523bf74a81 | c54446c3827f8ad170fb4df7de1f803892598727 | refs/heads/master | 2021-12-07T08:56:41.374000 | 2015-06-16T01:53:36 | 2015-06-16T01:53:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.comgroup.tzmedia.server.admin.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import org.eclipse.persistence.annotations.ConversionValue;
import org.eclipse.persistence.annotations.Convert;
import org.eclipse.persistence.annotations.ObjectTypeConverter;
import org.eclipse.persistence.annotations.ObjectTypeConverters;
@Entity
@Table(name = "USERCOUPONS")
@NamedQueries({
@NamedQuery(name = "UserCoupon.findAll",
query = "SELECT uc FROM UserCoupon uc"),
@NamedQuery(name = "UserCoupon.findByUserId",
query = "SELECT uc FROM UserCoupon uc WHERE uc.userId = :userId"),
@NamedQuery(name = "UserCoupon.findCountByCDNumberAndStatus",
query = "SELECT count(uc) FROM UserCoupon uc WHERE uc.couponDefinitionNumber = :couponDefinitionNumber and uc.couponStatus = :couponStatus"),
@NamedQuery(name = "UserCoupon.findByUserIdAndCDNumber",
query = "SELECT uc FROM UserCoupon uc WHERE uc.userId = :userId and uc.couponDefinitionNumber = :couponDefinitionNumber"),
@NamedQuery(name = "UserCoupon.findByDate",
query = "SELECT uc FROM UserCoupon uc, CouponDefinition cd WHERE "
+ "uc.couponDefinitionNumber=cd.couponDefinitionNumber and cd.expiryDate>= :expiryDate And cd.expiryDate <= :expiryDate"),})
@ObjectTypeConverters({
@ObjectTypeConverter(name = "couponStatus", objectType = CouponStatus.class, dataType = String.class, conversionValues = {
@ConversionValue(dataValue = "NEW", objectValue = "NEW"),
@ConversionValue(dataValue = "USED", objectValue = "USED"),
@ConversionValue(dataValue = "EXPIRED", objectValue = "EXPIRED")})
})
public class UserCoupon implements Serializable {
@Id
@Column(name = "COUPONNUMBER", nullable = false)
@TableGenerator(name = "COUPON_GENERATOR",
table = "ID_GENERATOR",
pkColumnName = "GENERATOR_NAME",
valueColumnName = "GENERATOR_VALUE",
pkColumnValue = "COUPONNUMBER_GEN",
allocationSize = 1,
initialValue = 1)
@GeneratedValue(generator = "COUPON_GENERATOR")
private long couponNumber;
@Basic
@Column(name = "USERID", updatable = false, insertable = false,nullable = false)
private String userId;
@Column(name = "COUPONDEFINITIONNUMBER", updatable = false, insertable = false,nullable = false)
private long couponDefinitionNumber;
@Basic
@Column(name = "COUPONSTATUS")
@Convert("couponStatus")
private CouponStatus couponStatus = CouponStatus.NEW;
// private String couponName;
//
// private double faceValue;
//
// @Temporal(DATE)
// private Calendar expiryDate;
@ManyToOne
@JoinColumn(name = "USERID")
@JsonIgnore
private User user;
@ManyToOne
@JoinColumn(name = "COUPONDEFINITIONNUMBER")
@JsonIgnore
private CouponDefinition couponDefinition;
public UserCoupon() {
}
public UserCoupon(String userId) {
this.userId = userId;
}
public long getCouponNumber() {
return couponNumber;
}
public void setCouponNumber(long couponNumber) {
this.couponNumber = couponNumber;
}
// @Temporal(DATE)
public Calendar getExpiryDate() {
if (couponDefinition != null) {
return couponDefinition.getExpiryDate();
}
return null;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public CouponStatus getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(CouponStatus couponStatus) {
this.couponStatus = couponStatus;
}
public String getCouponName() {
if (couponDefinition != null) {
return couponDefinition.getCouponName();
}
return "";
}
public double getFaceValue() {
if (couponDefinition != null) {
return couponDefinition.getFaceValue();
}
return 0.0D;
}
public double getMeetValue() {
if (couponDefinition != null) {
return couponDefinition.getMeetValue();
}
return 0.0D;
}
public long getCouponDefinitionNumber() {
return couponDefinitionNumber;
}
public void setCouponDefinitionNumber(long couponDefinitionNumber) {
this.couponDefinitionNumber = couponDefinitionNumber;
}
public CouponDefinition getCouponDefinition() {
return couponDefinition;
}
public void setCouponDefinition(CouponDefinition couponDefinition) {
this.couponDefinition = couponDefinition;
}
protected User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
if (user != null) {
this.userId = user.getUserId();
} else {
this.userId = null;
}
}
}
| UTF-8 | Java | 5,373 | java | UserCoupon.java | Java | [] | null | [] | package cn.comgroup.tzmedia.server.admin.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import org.eclipse.persistence.annotations.ConversionValue;
import org.eclipse.persistence.annotations.Convert;
import org.eclipse.persistence.annotations.ObjectTypeConverter;
import org.eclipse.persistence.annotations.ObjectTypeConverters;
@Entity
@Table(name = "USERCOUPONS")
@NamedQueries({
@NamedQuery(name = "UserCoupon.findAll",
query = "SELECT uc FROM UserCoupon uc"),
@NamedQuery(name = "UserCoupon.findByUserId",
query = "SELECT uc FROM UserCoupon uc WHERE uc.userId = :userId"),
@NamedQuery(name = "UserCoupon.findCountByCDNumberAndStatus",
query = "SELECT count(uc) FROM UserCoupon uc WHERE uc.couponDefinitionNumber = :couponDefinitionNumber and uc.couponStatus = :couponStatus"),
@NamedQuery(name = "UserCoupon.findByUserIdAndCDNumber",
query = "SELECT uc FROM UserCoupon uc WHERE uc.userId = :userId and uc.couponDefinitionNumber = :couponDefinitionNumber"),
@NamedQuery(name = "UserCoupon.findByDate",
query = "SELECT uc FROM UserCoupon uc, CouponDefinition cd WHERE "
+ "uc.couponDefinitionNumber=cd.couponDefinitionNumber and cd.expiryDate>= :expiryDate And cd.expiryDate <= :expiryDate"),})
@ObjectTypeConverters({
@ObjectTypeConverter(name = "couponStatus", objectType = CouponStatus.class, dataType = String.class, conversionValues = {
@ConversionValue(dataValue = "NEW", objectValue = "NEW"),
@ConversionValue(dataValue = "USED", objectValue = "USED"),
@ConversionValue(dataValue = "EXPIRED", objectValue = "EXPIRED")})
})
public class UserCoupon implements Serializable {
@Id
@Column(name = "COUPONNUMBER", nullable = false)
@TableGenerator(name = "COUPON_GENERATOR",
table = "ID_GENERATOR",
pkColumnName = "GENERATOR_NAME",
valueColumnName = "GENERATOR_VALUE",
pkColumnValue = "COUPONNUMBER_GEN",
allocationSize = 1,
initialValue = 1)
@GeneratedValue(generator = "COUPON_GENERATOR")
private long couponNumber;
@Basic
@Column(name = "USERID", updatable = false, insertable = false,nullable = false)
private String userId;
@Column(name = "COUPONDEFINITIONNUMBER", updatable = false, insertable = false,nullable = false)
private long couponDefinitionNumber;
@Basic
@Column(name = "COUPONSTATUS")
@Convert("couponStatus")
private CouponStatus couponStatus = CouponStatus.NEW;
// private String couponName;
//
// private double faceValue;
//
// @Temporal(DATE)
// private Calendar expiryDate;
@ManyToOne
@JoinColumn(name = "USERID")
@JsonIgnore
private User user;
@ManyToOne
@JoinColumn(name = "COUPONDEFINITIONNUMBER")
@JsonIgnore
private CouponDefinition couponDefinition;
public UserCoupon() {
}
public UserCoupon(String userId) {
this.userId = userId;
}
public long getCouponNumber() {
return couponNumber;
}
public void setCouponNumber(long couponNumber) {
this.couponNumber = couponNumber;
}
// @Temporal(DATE)
public Calendar getExpiryDate() {
if (couponDefinition != null) {
return couponDefinition.getExpiryDate();
}
return null;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public CouponStatus getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(CouponStatus couponStatus) {
this.couponStatus = couponStatus;
}
public String getCouponName() {
if (couponDefinition != null) {
return couponDefinition.getCouponName();
}
return "";
}
public double getFaceValue() {
if (couponDefinition != null) {
return couponDefinition.getFaceValue();
}
return 0.0D;
}
public double getMeetValue() {
if (couponDefinition != null) {
return couponDefinition.getMeetValue();
}
return 0.0D;
}
public long getCouponDefinitionNumber() {
return couponDefinitionNumber;
}
public void setCouponDefinitionNumber(long couponDefinitionNumber) {
this.couponDefinitionNumber = couponDefinitionNumber;
}
public CouponDefinition getCouponDefinition() {
return couponDefinition;
}
public void setCouponDefinition(CouponDefinition couponDefinition) {
this.couponDefinition = couponDefinition;
}
protected User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
if (user != null) {
this.userId = user.getUserId();
} else {
this.userId = null;
}
}
}
| 5,373 | 0.673553 | 0.672436 | 177 | 29.355932 | 27.557703 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.468927 | false | false | 9 |
6fb675edf33ab2ed01575459c22f3371030604fb | 601,295,489,583 | 0ff303eff890f3f0ab93ff4fe7b2a2815c5d281d | /core/src/uk/co/codeecho/gdx/forge/component/builder/ComponentBuilder.java | 5c867f084763966380d4409367181b1576d4b6a3 | [] | no_license | codeecho/game-forge | https://github.com/codeecho/game-forge | 63abbeb6c710d526cf9d145cffb9de904c3bfb3f | 33f33f6156ee681b5b92df57916c39e2cde2e3ea | refs/heads/master | 2020-06-01T13:52:27.890000 | 2017-03-30T06:23:34 | 2017-03-30T06:23:34 | 40,473,575 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.co.codeecho.gdx.forge.component.builder;
import uk.co.codeecho.gdx.forge.component.Component;
public interface ComponentBuilder<C extends Component> {
public C build();
}
| UTF-8 | Java | 194 | java | ComponentBuilder.java | Java | [] | null | [] | package uk.co.codeecho.gdx.forge.component.builder;
import uk.co.codeecho.gdx.forge.component.Component;
public interface ComponentBuilder<C extends Component> {
public C build();
}
| 194 | 0.757732 | 0.757732 | 9 | 20.555555 | 23.795942 | 56 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
fb6b8e2c51b2c4168c66a1b3238583dcf8295524 | 18,167,711,688,347 | fa7af53b4bc6b2841a40660adc870f496baadadf | /meeting-ui/src/main/java/io/agora/meeting/ui/http/body/ResponseBody.java | 6878f51794040a8100e73b61780d98dd3941447a | [
"MIT"
] | permissive | GaozyDev/Meeting | https://github.com/GaozyDev/Meeting | adb712e4dae76babd886e1c34b352c61203ffe97 | 02f5104e26ea4977579427ed49766b0d6d41fb09 | refs/heads/master | 2023-07-08T10:52:06.400000 | 2021-08-13T05:34:34 | 2021-08-13T05:34:34 | 388,386,422 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.agora.meeting.ui.http.body;
import io.agora.meeting.core.annotaion.Keep;
import io.agora.meeting.ui.http.network.BaseResponse;
@Keep
public class ResponseBody<T> extends BaseResponse {
public T P;
@Override
public String toString() {
return "{" +
", \"E\"=" + E +
", \"P\"=" + P +
'}';
}
}
| UTF-8 | Java | 376 | java | ResponseBody.java | Java | [] | null | [] | package io.agora.meeting.ui.http.body;
import io.agora.meeting.core.annotaion.Keep;
import io.agora.meeting.ui.http.network.BaseResponse;
@Keep
public class ResponseBody<T> extends BaseResponse {
public T P;
@Override
public String toString() {
return "{" +
", \"E\"=" + E +
", \"P\"=" + P +
'}';
}
}
| 376 | 0.547872 | 0.547872 | 17 | 21.117647 | 17.825567 | 53 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.411765 | false | false | 9 |
6c971c6895f9d3a6f7ba3870e66eeb9eb09f72e8 | 23,656,679,892,377 | d8fdac6b0533a5b6dc164562a5f5865a8842a95e | /CodeChef/CodeChef Feb 15/src/ChefAndEquality.java | b2f6c50e02ed32fe9766a6d230c09e33ecdcaabb | [] | no_license | kishuagarwal/CompetitiveProgramming | https://github.com/kishuagarwal/CompetitiveProgramming | 57d1272023ebfc4646b85f9b5be03cad60aec244 | cc18b0c23940ce66b47a31368b9c3f3bd35ce819 | refs/heads/master | 2023-08-03T19:07:18.496000 | 2021-09-13T05:18:21 | 2021-09-13T05:18:21 | 59,596,111 | 0 | 0 | null | false | 2018-12-02T11:16:49 | 2016-05-24T17:57:17 | 2018-10-01T20:20:32 | 2018-12-02T11:16:49 | 14,715 | 0 | 0 | 0 | Java | false | null | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by Kishu Agarwal on 08-02-2015.
*/
public class ChefAndEquality {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int hist[] = new int[100001];
for (int i = 0; i < t; i++) {
int n = in.nextInt();
Arrays.fill(hist, 0);
for (int j = 0; j < n; j++) {
hist[in.nextInt()]++;
}
int max = hist[1];
for (int j = 2; j < hist.length; j++) {
if( hist[j] > max) {
max = hist[j];
}
}
System.out.println(n-max);
}
in.close();
}
}
| UTF-8 | Java | 786 | java | ChefAndEquality.java | Java | [
{
"context": ";\r\nimport java.util.Scanner;\r\n\r\n/**\r\n * Created by Kishu Agarwal on 08-02-2015.\r\n */\r\npublic class ChefAndEquality",
"end": 87,
"score": 0.9998493194580078,
"start": 74,
"tag": "NAME",
"value": "Kishu Agarwal"
}
] | null | [] | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by <NAME> on 08-02-2015.
*/
public class ChefAndEquality {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int hist[] = new int[100001];
for (int i = 0; i < t; i++) {
int n = in.nextInt();
Arrays.fill(hist, 0);
for (int j = 0; j < n; j++) {
hist[in.nextInt()]++;
}
int max = hist[1];
for (int j = 2; j < hist.length; j++) {
if( hist[j] > max) {
max = hist[j];
}
}
System.out.println(n-max);
}
in.close();
}
}
| 779 | 0.414758 | 0.390585 | 29 | 25.103449 | 15.266246 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.655172 | false | false | 9 |
fd7bb50c2c544fbe75654848e4b0cc33434eba0c | 35,734,127,904,367 | 4fb8ca070c668fd88f55277e124b37fccb7191dc | /blog-serve/src/main/java/com/mc/blog/mapper/CategoryMapper.java | 2f5b6c52e4f3d9767805e7a04f82be5e0d283443 | [] | no_license | undercodeheap/blog-backend | https://github.com/undercodeheap/blog-backend | c0544cc6ba2b6585af54bedb31e3d540763f8992 | 3cc7b4048463c641b95f422e1c4712cdb21aeae3 | refs/heads/master | 2023-08-01T04:20:09.137000 | 2021-08-22T10:51:49 | 2021-08-22T10:51:49 | 393,937,611 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.mc.blog.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mc.blog.entity.Category;
public interface CategoryMapper extends BaseMapper<Category> {
}
| UTF-8 | Java | 187 | java | CategoryMapper.java | Java | [] | null | [] | package com.mc.blog.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mc.blog.entity.Category;
public interface CategoryMapper extends BaseMapper<Category> {
}
| 187 | 0.818182 | 0.818182 | 7 | 25.714285 | 24.481564 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 9 |
cf2ab0f6de77e6072445af37c16d9e5abb5682a6 | 33,921,651,730,156 | 714dc502af8bb18c6e891e567049301d45b84c62 | /app/src/main/java/top/easelink/mob/service/autoclick/moling/mode/BaseAutoMode.java | b1d9fbee65542de9a51609801cdd317477e67731 | [] | no_license | fabricezhang/Mob | https://github.com/fabricezhang/Mob | 881c66fea8289a36e93ada0707d4cb5b73fa22f1 | 017ec2ada1f224051c45a97634537862a6db79fd | refs/heads/master | 2018-10-22T06:20:20.156000 | 2018-10-07T14:18:12 | 2018-10-07T14:18:12 | 133,495,390 | 5 | 0 | null | false | 2019-01-12T04:40:45 | 2018-05-15T09:48:46 | 2018-12-05T14:01:43 | 2019-01-12T04:40:45 | 1,328 | 2 | 0 | 0 | Java | false | null | package top.easelink.mob.service.autoclick.moling.mode;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import org.apache.commons.lang3.NotImplementedException;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import top.easelink.mob.MobApp;
import top.easelink.mob.data.DataManager;
import top.easelink.mob.di.component.DaggerAutoModeComponent;
import top.easelink.mob.service.autoclick.moling.MolingConfig;
import top.easelink.mob.service.autoclick.moling.task.BaseMolingClickTask;
public class BaseAutoMode {
@Inject
DataManager dataManager;
@Inject
MolingConfig config;
protected AutoModeListener modeListener;
Map<String,BaseMolingClickTask> runeTaskList = new HashMap<>(20);
BaseAutoMode(@NonNull AutoModeListener listener){
DaggerAutoModeComponent.builder().applicationComponent(MobApp.getComponent()).build().inject(this);
setStartTime();
this.modeListener = listener;
initTask();
}
private void setStartTime(){
config.startTime = System.currentTimeMillis();
}
void initTask(){
throw new NotImplementedException("");
}
public void checkScreen(Bitmap bitmap){
throw new NotImplementedException("");
}
public interface AutoModeListener{
void onStart();
void onStop();
}
}
| UTF-8 | Java | 1,385 | java | BaseAutoMode.java | Java | [] | null | [] | package top.easelink.mob.service.autoclick.moling.mode;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import org.apache.commons.lang3.NotImplementedException;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import top.easelink.mob.MobApp;
import top.easelink.mob.data.DataManager;
import top.easelink.mob.di.component.DaggerAutoModeComponent;
import top.easelink.mob.service.autoclick.moling.MolingConfig;
import top.easelink.mob.service.autoclick.moling.task.BaseMolingClickTask;
public class BaseAutoMode {
@Inject
DataManager dataManager;
@Inject
MolingConfig config;
protected AutoModeListener modeListener;
Map<String,BaseMolingClickTask> runeTaskList = new HashMap<>(20);
BaseAutoMode(@NonNull AutoModeListener listener){
DaggerAutoModeComponent.builder().applicationComponent(MobApp.getComponent()).build().inject(this);
setStartTime();
this.modeListener = listener;
initTask();
}
private void setStartTime(){
config.startTime = System.currentTimeMillis();
}
void initTask(){
throw new NotImplementedException("");
}
public void checkScreen(Bitmap bitmap){
throw new NotImplementedException("");
}
public interface AutoModeListener{
void onStart();
void onStop();
}
}
| 1,385 | 0.729242 | 0.727076 | 56 | 23.732143 | 24.412008 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.464286 | false | false | 9 |
4b34bbd5d61c220aecc61b5b952ae9bd789c3c18 | 34,711,925,692,933 | 88f0f3e256b3980bbb6b7e4d5ab234b623baa712 | /app/src/main/java/com/almosky/almoskylaundryApp/notification/MyFirebaseMessagingService.java | 7f0cae4e39537bb5ecc738d863374b7ee03fad65 | [] | no_license | shwetadalvi/AlmoskyLaundryNew | https://github.com/shwetadalvi/AlmoskyLaundryNew | 862fc7d3fa575b628a05c71ac08ef01a9e18834d | 4b18251dd63f9ae75ef3bb2451a7563bfcc44211 | refs/heads/master | 2020-05-17T23:03:51.158000 | 2019-05-02T05:25:34 | 2019-05-02T05:25:34 | 184,020,644 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.almosky.almoskylaundryApp.notification;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import com.almosky.almoskylaundryApp.R;
import com.almosky.almoskylaundryApp.SplashScreenActivity;
import com.almosky.almoskylaundryApp.TabHostActivity;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import androidx.core.app.NotificationCompat;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
public static final String INTENT_FILTER = "INTENT_FILTER_NOTIFICATION";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// scheduleJob();
}
System.out.println("nxt"+remoteMessage.getNotification().getBody());
genNotif(remoteMessage);
// Map<String, String> notification = remoteMessage.getData();
// String type = notification.get("type");
//String result = notification.get("result");
// generateNotification(type,result);
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "id_product";
// The user-visible name of the channel.
CharSequence name = "Product";
// The user-visible description of the channel.
String description = "Notifications regarding our products";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(mChannel);
}*/
}
private void genNotif(RemoteMessage remoteMessage) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String messageBody = remoteMessage.getNotification().getBody();
// Sets an ID for the notification, so it can be updated.
// int notifyID = Integer.parseInt(data.get("notification_type"));
String channelId = this.getResources().getString(R.string.default_notification_channel_id);
CharSequence name = this.getResources().getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Toast.makeText(this, "received", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, TabHostActivity.class);
// intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
// intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
// PendingIntent.FLAG_ONE_SHOT);
NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody).setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setStyle(new Notification.BigTextStyle().bigText(messageBody))
.setChannelId(channelId)
.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager.notify(1, notification);
} else {
Intent intentNotification = new Intent(INTENT_FILTER);
sendBroadcast(intentNotification);
Intent intent = new Intent(this, TabHostActivity.class);
intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(getString(R.string.app_name))
// .setContentIntent(pendingIntent)
.setContentText(messageBody).setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH);
notificationManager.notify(1, builder.build());
}
}
private void scheduleJob() {
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
}
private void generateNotification(String title, String messageBody) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getApplicationContext().getString(R.string.default_notification_channel_id);
NotificationChannel channel = new NotificationChannel(channelId, "Almosky", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(messageBody);
channel.setName(getString(R.string.app_name));
mNotificationManager.createNotificationChannel(channel);
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
mNotifyBuilder.setChannelId(channelId);
mNotifyBuilder.setDefaults(Notification.DEFAULT_SOUND);
mNotifyBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(1, mNotifyBuilder.build());
} else {
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
mNotifyBuilder.setDefaults(Notification.DEFAULT_SOUND);
mNotifyBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
mNotificationManager.notify(1, mNotifyBuilder.build());
}
}
} | UTF-8 | Java | 9,117 | java | MyFirebaseMessagingService.java | Java | [] | null | [] | package com.almosky.almoskylaundryApp.notification;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import com.almosky.almoskylaundryApp.R;
import com.almosky.almoskylaundryApp.SplashScreenActivity;
import com.almosky.almoskylaundryApp.TabHostActivity;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import androidx.core.app.NotificationCompat;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static int NOTIFICATION_ID = 1;
public static final String INTENT_FILTER = "INTENT_FILTER_NOTIFICATION";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
// scheduleJob();
}
System.out.println("nxt"+remoteMessage.getNotification().getBody());
genNotif(remoteMessage);
// Map<String, String> notification = remoteMessage.getData();
// String type = notification.get("type");
//String result = notification.get("result");
// generateNotification(type,result);
/* if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "id_product";
// The user-visible name of the channel.
CharSequence name = "Product";
// The user-visible description of the channel.
String description = "Notifications regarding our products";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(mChannel);
}*/
}
private void genNotif(RemoteMessage remoteMessage) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String messageBody = remoteMessage.getNotification().getBody();
// Sets an ID for the notification, so it can be updated.
// int notifyID = Integer.parseInt(data.get("notification_type"));
String channelId = this.getResources().getString(R.string.default_notification_channel_id);
CharSequence name = this.getResources().getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Toast.makeText(this, "received", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, TabHostActivity.class);
// intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
// intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
// PendingIntent.FLAG_ONE_SHOT);
NotificationChannel mChannel = new NotificationChannel(channelId, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody).setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setStyle(new Notification.BigTextStyle().bigText(messageBody))
.setChannelId(channelId)
.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager.notify(1, notification);
} else {
Intent intentNotification = new Intent(INTENT_FILTER);
sendBroadcast(intentNotification);
Intent intent = new Intent(this, TabHostActivity.class);
intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setColor(getResources().getColor(R.color.colorPrimary))
.setContentTitle(getString(R.string.app_name))
// .setContentIntent(pendingIntent)
.setContentText(messageBody).setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH);
notificationManager.notify(1, builder.build());
}
}
private void scheduleJob() {
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
}
private void generateNotification(String title, String messageBody) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = getApplicationContext().getString(R.string.default_notification_channel_id);
NotificationChannel channel = new NotificationChannel(channelId, "Almosky", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(messageBody);
channel.setName(getString(R.string.app_name));
mNotificationManager.createNotificationChannel(channel);
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
mNotifyBuilder.setChannelId(channelId);
mNotifyBuilder.setDefaults(Notification.DEFAULT_SOUND);
mNotifyBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
mNotificationManager.notify(1, mNotifyBuilder.build());
} else {
Intent intent = new Intent(this, SplashScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
mNotifyBuilder.setDefaults(Notification.DEFAULT_SOUND);
mNotifyBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
if (NOTIFICATION_ID > 1073741824) {
NOTIFICATION_ID = 0;
}
mNotificationManager.notify(1, mNotifyBuilder.build());
}
}
} | 9,117 | 0.667764 | 0.66535 | 192 | 46.489582 | 31.82766 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 9 |
6ce7c7d15b86b1ee8e354f6d3c247261d51a6ac6 | 34,041,910,812,140 | 2f4ccc26f60cb9cce9243ccb9847c2ff76cb461a | /src/pboif2/pkg10119052/latihan51/gajikaryawan/PBOIF210119052Latihan51GajiKaryawan.java | 28bd4ce0b795efa065895b4e84273fb5b2de76de | [] | no_license | RizkiDwiN/PBOIF2-10119052-Latihan51-GajiKaryawan | https://github.com/RizkiDwiN/PBOIF2-10119052-Latihan51-GajiKaryawan | 8bab1eb1b026dbd0d2c389a2276b69a6ad9815f5 | 6ec946201e295dfb26dab7a271fb827c988ab377 | refs/heads/master | 2023-01-10T03:28:22.336000 | 2020-11-14T16:46:12 | 2020-11-14T16:46:12 | 312,858,662 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pboif2.pkg10119052.latihan51.gajikaryawan;
import java.util.Scanner;
/**
*
* NAMA : Rizki Dwi nugraha
* KELAS : IF-2
* NIM : 10119052
* Deskripsi Program : Program ini berisi program untuk menampilkan
* gaji karyawan dengan menggunakan polymorpism
*
*/
public class PBOIF210119052Latihan51GajiKaryawan {
public static void main(String[] args) {
Manager manager = new Manager();
Scanner userInput = new Scanner(System.in);
System.out.println("====Program Perhitungan Gaji Karyawan====");
System.out.print("Masukkan Nik : ");
manager.setNik(userInput.nextLine());
System.out.print("Masukkan Nama : ");
manager.setNama(userInput.nextLine());
System.out.print("Masukkan Golongan(1/2/3) :");
manager.setGolongan(userInput.nextInt());
System.out.print("Masukkan Jabatan (Manager/Kabag ) :");
manager.setJabatan(userInput.next());
System.out.print("Masukkan Jumlah Kehadiran : ");
manager.setKehadiran(userInput.nextInt());
System.out.println("");
System.out.print("====Hasil Perhitungan====");
System.out.println("NIK : "+manager.getNik());
System.out.println("NAMA : "+manager.getNama());
System.out.println("GOLONGAN : "+manager.getGolongan());
System.out.println("JABATAN : "+manager.getJabatan());
System.out.println("TUNJANGAN GOLONGAN : "+manager.tunjangGolongan(manager.getGolongan()));
System.out.println("TUNJANGAN JABATAN : "+manager.tunjangJabatan(manager.getJabatan()));
System.out.println("TUNJANGAN KEHADIRAN : "+manager.tunjangKehadiran(manager.getKehadiran()));
System.out.println("GAJI TOTAL : "+manager.gajitotal());
}
}
| UTF-8 | Java | 1,806 | java | PBOIF210119052Latihan51GajiKaryawan.java | Java | [
{
"context": ";\r\nimport java.util.Scanner;\r\n/**\r\n *\r\n * NAMA : Rizki Dwi nugraha\r\n * KELAS : IF-2\r\n * NIM : 10119052\r\n * Deskr",
"end": 117,
"score": 0.999873161315918,
"start": 100,
"tag": "NAME",
"value": "Rizki Dwi nugraha"
}
] | null | [] | package pboif2.pkg10119052.latihan51.gajikaryawan;
import java.util.Scanner;
/**
*
* NAMA : <NAME>
* KELAS : IF-2
* NIM : 10119052
* Deskripsi Program : Program ini berisi program untuk menampilkan
* gaji karyawan dengan menggunakan polymorpism
*
*/
public class PBOIF210119052Latihan51GajiKaryawan {
public static void main(String[] args) {
Manager manager = new Manager();
Scanner userInput = new Scanner(System.in);
System.out.println("====Program Perhitungan Gaji Karyawan====");
System.out.print("Masukkan Nik : ");
manager.setNik(userInput.nextLine());
System.out.print("Masukkan Nama : ");
manager.setNama(userInput.nextLine());
System.out.print("Masukkan Golongan(1/2/3) :");
manager.setGolongan(userInput.nextInt());
System.out.print("Masukkan Jabatan (Manager/Kabag ) :");
manager.setJabatan(userInput.next());
System.out.print("Masukkan Jumlah Kehadiran : ");
manager.setKehadiran(userInput.nextInt());
System.out.println("");
System.out.print("====Hasil Perhitungan====");
System.out.println("NIK : "+manager.getNik());
System.out.println("NAMA : "+manager.getNama());
System.out.println("GOLONGAN : "+manager.getGolongan());
System.out.println("JABATAN : "+manager.getJabatan());
System.out.println("TUNJANGAN GOLONGAN : "+manager.tunjangGolongan(manager.getGolongan()));
System.out.println("TUNJANGAN JABATAN : "+manager.tunjangJabatan(manager.getJabatan()));
System.out.println("TUNJANGAN KEHADIRAN : "+manager.tunjangKehadiran(manager.getKehadiran()));
System.out.println("GAJI TOTAL : "+manager.gajitotal());
}
}
| 1,795 | 0.639535 | 0.620709 | 40 | 43.150002 | 27.010693 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 9 |
a3664682b8ffa8cbe941e2ebd6d67e32f885a299 | 28,509,992,981,210 | ddb4b54b52a70e67fea0a0aa74c9a4c4a289fecc | /src/main/java/by/bsuir/bank_web/service/impl/ClientServiceImpl.java | 48febbe9c2d50b113a3fd2100b8bcbe279b08a8b | [] | no_license | EagleGlance/IdeaBankWeb | https://github.com/EagleGlance/IdeaBankWeb | e1cd4b870723df19dfcb6e2715debec0dd114e52 | de55f426ab215afd6612d63b0b37611c53e71a2f | refs/heads/master | 2018-01-08T00:48:22.668000 | 2015-12-13T02:02:16 | 2015-12-13T02:02:16 | 47,408,893 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package by.bsuir.bank_web.service.impl;
import by.bsuir.bank_web.dao.ClientDao;
import by.bsuir.bank_web.dao.DaoException;
import by.bsuir.bank_web.dao.DaoFactory;
import by.bsuir.bank_web.domain.entity.Client;
import by.bsuir.bank_web.service.ClientService;
import by.bsuir.bank_web.service.ServiceException;
import by.bsuir.bank_web.service.validator.RegistrationValidator;
import by.bsuir.bank_web.service.validator.ValidationException;
import by.bsuir.bank_web.service.validator.ValidatorInterface;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Слава on 19.11.2015.
*/
public class ClientServiceImpl implements ClientService {
private static final String USER_ROLE = "user";
private static final ClientService instance = new ClientServiceImpl();
private static final DaoFactory factory = DaoFactory.getDaoFactory();
private static final ValidatorInterface<Client> VALIDATOR = RegistrationValidator.getInstance();
private ClientServiceImpl(){}
public static ClientService getInstance(){
return instance;
}
@Override
public Client updateClientInfo(Client client) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
int id = clientDao.update(client);
return clientDao.findById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public boolean deleteClient(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
boolean check = clientDao.checkClientById(id);
if(!check) {
return false;
} else {
return clientDao.delete(id);
}
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public boolean checkClientById(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
return clientDao.checkClientById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public Client findById(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
return clientDao.findById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public Client create(Client client) throws ServiceException {
try {
if(VALIDATOR.isValid(client)) {
String password = client.getPassword();
String passwordMD5 = DigestUtils.md5Hex(password);
client.setPassword(passwordMD5);
ClientDao clientDao = factory.getClientDao();
boolean check = clientDao.checkClient(client);
if (!check) {
clientDao.create(client);
return client;
} else {
return null;
}
} else {
throw new ValidationException("Validation Exception");
}
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public List<Client> viewAll() throws ServiceException {
List<Client> clientList = null;
List<Client> finalList = new ArrayList<>();
try {
ClientDao clientDao = factory.getClientDao();
clientList = clientDao.findAll();
for(Client temp : clientList){
if(temp.getRole().equals(USER_ROLE)) {
finalList.add(temp);
}
}
return finalList;
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
}
| WINDOWS-1251 | Java | 4,039 | java | ClientServiceImpl.java | Java | [
{
"context": "rayList;\nimport java.util.List;\n\n/**\n * Created by Слава on 19.11.2015.\n */\npublic class ClientServiceImpl",
"end": 632,
"score": 0.9997996091842651,
"start": 627,
"tag": "NAME",
"value": "Слава"
},
{
"context": "Valid(client)) {\n String password =... | null | [] | package by.bsuir.bank_web.service.impl;
import by.bsuir.bank_web.dao.ClientDao;
import by.bsuir.bank_web.dao.DaoException;
import by.bsuir.bank_web.dao.DaoFactory;
import by.bsuir.bank_web.domain.entity.Client;
import by.bsuir.bank_web.service.ClientService;
import by.bsuir.bank_web.service.ServiceException;
import by.bsuir.bank_web.service.validator.RegistrationValidator;
import by.bsuir.bank_web.service.validator.ValidationException;
import by.bsuir.bank_web.service.validator.ValidatorInterface;
import org.apache.commons.codec.digest.DigestUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Слава on 19.11.2015.
*/
public class ClientServiceImpl implements ClientService {
private static final String USER_ROLE = "user";
private static final ClientService instance = new ClientServiceImpl();
private static final DaoFactory factory = DaoFactory.getDaoFactory();
private static final ValidatorInterface<Client> VALIDATOR = RegistrationValidator.getInstance();
private ClientServiceImpl(){}
public static ClientService getInstance(){
return instance;
}
@Override
public Client updateClientInfo(Client client) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
int id = clientDao.update(client);
return clientDao.findById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public boolean deleteClient(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
boolean check = clientDao.checkClientById(id);
if(!check) {
return false;
} else {
return clientDao.delete(id);
}
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public boolean checkClientById(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
return clientDao.checkClientById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public Client findById(int id) throws ServiceException {
try {
ClientDao clientDao = factory.getClientDao();
return clientDao.findById(id);
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public Client create(Client client) throws ServiceException {
try {
if(VALIDATOR.isValid(client)) {
String password = <PASSWORD>();
String passwordMD5 = <PASSWORD>.<PASSWORD>(password);
client.setPassword(passwordMD5);
ClientDao clientDao = factory.getClientDao();
boolean check = clientDao.checkClient(client);
if (!check) {
clientDao.create(client);
return client;
} else {
return null;
}
} else {
throw new ValidationException("Validation Exception");
}
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
@Override
public List<Client> viewAll() throws ServiceException {
List<Client> clientList = null;
List<Client> finalList = new ArrayList<>();
try {
ClientDao clientDao = factory.getClientDao();
clientList = clientDao.findAll();
for(Client temp : clientList){
if(temp.getRole().equals(USER_ROLE)) {
finalList.add(temp);
}
}
return finalList;
} catch (DaoException e) {
throw new ServiceException("Service Exception", e);
}
}
}
| 4,034 | 0.610808 | 0.608081 | 122 | 32.065575 | 23.996836 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.459016 | false | false | 9 |
f3961c2fd820a4f8279ea3d4b463e984a7ecf6c6 | 17,291,538,374,686 | 2b1316343de3dadc8721fa50138cbcf49072caaf | /app/src/main/java/com/example/siddhant/article_publisher/networkClasses/GetArticles.java | ae59a6a4f83cc49447d25c175f064ea78fc79350 | [] | no_license | sidsaurb/article-publisher-android | https://github.com/sidsaurb/article-publisher-android | f94f22c16a261814344a6936f206ddd3096b2064 | 1c26288ba1b27bd7bcaea2025f702eb76ce194f5 | refs/heads/master | 2021-01-10T03:51:39.727000 | 2016-02-02T11:18:40 | 2016-02-02T11:18:40 | 50,867,751 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.siddhant.article_publisher.networkClasses;
/**
* Created by siddhant on 1/2/16.
*/
public class GetArticles {
public int id;
public GetArticles(int id) {
this.id = id;
}
}
| UTF-8 | Java | 216 | java | GetArticles.java | Java | [
{
"context": "ticle_publisher.networkClasses;\n\n/**\n * Created by siddhant on 1/2/16.\n */\npublic class GetArticles {\n pub",
"end": 90,
"score": 0.9996223449707031,
"start": 82,
"tag": "USERNAME",
"value": "siddhant"
}
] | null | [] | package com.example.siddhant.article_publisher.networkClasses;
/**
* Created by siddhant on 1/2/16.
*/
public class GetArticles {
public int id;
public GetArticles(int id) {
this.id = id;
}
}
| 216 | 0.652778 | 0.634259 | 12 | 17 | 18.197985 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 9 |
b659ccaea204a802846db4cbcf434c2c35f08ecb | 4,836,133,216,785 | 500c1a6650c5d2a8fd95f9e5fd3e42a940bf19dd | /ASB2/common/TechCraft/blocks/BlockGarnetOre.java | a361a6ef4eaf51b3e0287639219055db3f56bb76 | [] | no_license | ASB2/TechCraft | https://github.com/ASB2/TechCraft | 989253ecf636b180384954d0d7232a305f1af2ef | 916a20af17131211eadfac5bdab70b1722a84f8f | refs/heads/master | 2016-09-06T08:37:11.278000 | 2013-08-16T19:12:42 | 2013-08-16T19:12:42 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package TechCraft.blocks;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import TechCraft.ItemRegistry;
public class BlockGarnetOre extends TechCraftBlocks {
public BlockGarnetOre(int par1, Material par3Material) {
super(par1, par3Material);
}
@Override
public void registerIcons(IconRegister par1IconRegister) {
this.blockIcon = par1IconRegister.registerIcon("TechCraft:BlockGarnetOre");
}
public int idDropped(int par1, Random par2Random, int par3) {
return ItemRegistry.ItemGarnet.itemID;
}
}
| UTF-8 | Java | 630 | java | BlockGarnetOre.java | Java | [] | null | [] | package TechCraft.blocks;
import java.util.Random;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import TechCraft.ItemRegistry;
public class BlockGarnetOre extends TechCraftBlocks {
public BlockGarnetOre(int par1, Material par3Material) {
super(par1, par3Material);
}
@Override
public void registerIcons(IconRegister par1IconRegister) {
this.blockIcon = par1IconRegister.registerIcon("TechCraft:BlockGarnetOre");
}
public int idDropped(int par1, Random par2Random, int par3) {
return ItemRegistry.ItemGarnet.itemID;
}
}
| 630 | 0.760317 | 0.746032 | 24 | 25.25 | 26.424814 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.791667 | false | false | 9 |
ceaeaee04bb6b953c5a5b81be28391e47fc022ee | 5,952,824,700,617 | dfdd29c8d34741a39266221e9acd3882de754070 | /app/src/main/java/com/pocketnhs/pocketnhsandroid/server/api_protocols/GetConditionDetailsProtocol.java | 9176860ee3110c8b72a736065eca9bf5910984d7 | [] | no_license | Jinhe928/PocketNH-Android | https://github.com/Jinhe928/PocketNH-Android | baf229d50b44f43d6042da0f07d34f93e959b57d | d090b6107ce8e08fa371fa2d1fd91718da4c8312 | refs/heads/master | 2020-04-06T04:04:05.289000 | 2017-02-24T16:53:11 | 2017-02-24T16:53:11 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.pocketnhs.pocketnhsandroid.server.api_protocols;
import android.util.Log;
import com.pocketnhs.pocketnhsandroid.server.PocketNHSServerProtocol;
import com.pocketnhs.pocketnhsandroid.server.ServerSettings;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSCondition;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSTextLinkPair;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSTextLinkPairList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.Map;
import java.util.concurrent.locks.Condition;
/**
* Created by MacBook Pro on 6/14/2016.
*/
public class GetConditionDetailsProtocol implements PocketNHSServerProtocol {
private static final String URL_ENDPOINT = ServerSettings.SERVER_BASE_URL + "/conditions/atoz/";
private static final String PROTOCOL_ID = "Get Condition Details";
public static final String CONDITION_LINK = "condition_link";
private static final String RESPONSE_ENTRY_ELEMENT = "entry";
private static final String RESPONSE_TITLE_ELEMENT = "title";
private static final String RESPONSE_SUMMARY_ELEMENT = "summary";
private static final String RESPONSE_CONTENT_ELEMENT = "content";
private static PocketNHSServerProtocol mInstance = null;
@Override
public String getEndpointURL(Map<String, Object> params) {
String endpoint = (String)params.get(CONDITION_LINK);
if (endpoint.indexOf("?") > 0 ) {
endpoint = endpoint.substring(0, endpoint.indexOf("?"));
}
//String endpoint = URL_ENDPOINT + params.get(CONDITION_LINK);
endpoint = endpoint + "/introduction.xml"
+ "?" + ServerSettings.API_KEY_STR;
return endpoint;
}
public static synchronized PocketNHSServerProtocol getInstance() {
if (mInstance == null) {
mInstance = new GetConditionDetailsProtocol();
}
return mInstance;
}
@Override
public boolean parseResponse(String response, Object outputs) {
NHSCondition condition = (NHSCondition) outputs;
boolean error = false;
try {
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(response.substring(getSkipValue(response))));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (condition != null) {
if (name.equalsIgnoreCase(RESPONSE_TITLE_ELEMENT)) {
condition.mTitle = parser.nextText();
} else if (name.equalsIgnoreCase(RESPONSE_SUMMARY_ELEMENT)) {
condition.mSummary = parser.nextText();
} else if (name.equalsIgnoreCase(RESPONSE_CONTENT_ELEMENT)) {
condition.mText = parser.nextText();
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(RESPONSE_CONTENT_ELEMENT)) {
Log.d("GET_COND_DET_PROTOCOL", "loaded condition info");
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
error = true;
}
return !error;
}
private int getSkipValue(String response) {
// int SKIP_UTF8_BOM = 3;
int skip = response.indexOf("<");
return skip;
}
@Override
public int getDataIndex(Object inputs){
return 0;
}
@Override
public String getProtocolRequestCode() {
return PROTOCOL_ID;
}
}
| UTF-8 | Java | 4,303 | java | GetConditionDetailsProtocol.java | Java | [
{
"context": "til.concurrent.locks.Condition;\n\n/**\n * Created by MacBook Pro on 6/14/2016.\n */\n\npublic class GetConditionDetai",
"end": 666,
"score": 0.8293282985687256,
"start": 655,
"tag": "NAME",
"value": "MacBook Pro"
}
] | null | [] | package com.pocketnhs.pocketnhsandroid.server.api_protocols;
import android.util.Log;
import com.pocketnhs.pocketnhsandroid.server.PocketNHSServerProtocol;
import com.pocketnhs.pocketnhsandroid.server.ServerSettings;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSCondition;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSTextLinkPair;
import com.pocketnhs.pocketnhsandroid.server.transfer_objects.NHSTextLinkPairList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.Map;
import java.util.concurrent.locks.Condition;
/**
* Created by <NAME> on 6/14/2016.
*/
public class GetConditionDetailsProtocol implements PocketNHSServerProtocol {
private static final String URL_ENDPOINT = ServerSettings.SERVER_BASE_URL + "/conditions/atoz/";
private static final String PROTOCOL_ID = "Get Condition Details";
public static final String CONDITION_LINK = "condition_link";
private static final String RESPONSE_ENTRY_ELEMENT = "entry";
private static final String RESPONSE_TITLE_ELEMENT = "title";
private static final String RESPONSE_SUMMARY_ELEMENT = "summary";
private static final String RESPONSE_CONTENT_ELEMENT = "content";
private static PocketNHSServerProtocol mInstance = null;
@Override
public String getEndpointURL(Map<String, Object> params) {
String endpoint = (String)params.get(CONDITION_LINK);
if (endpoint.indexOf("?") > 0 ) {
endpoint = endpoint.substring(0, endpoint.indexOf("?"));
}
//String endpoint = URL_ENDPOINT + params.get(CONDITION_LINK);
endpoint = endpoint + "/introduction.xml"
+ "?" + ServerSettings.API_KEY_STR;
return endpoint;
}
public static synchronized PocketNHSServerProtocol getInstance() {
if (mInstance == null) {
mInstance = new GetConditionDetailsProtocol();
}
return mInstance;
}
@Override
public boolean parseResponse(String response, Object outputs) {
NHSCondition condition = (NHSCondition) outputs;
boolean error = false;
try {
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(response.substring(getSkipValue(response))));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (condition != null) {
if (name.equalsIgnoreCase(RESPONSE_TITLE_ELEMENT)) {
condition.mTitle = parser.nextText();
} else if (name.equalsIgnoreCase(RESPONSE_SUMMARY_ELEMENT)) {
condition.mSummary = parser.nextText();
} else if (name.equalsIgnoreCase(RESPONSE_CONTENT_ELEMENT)) {
condition.mText = parser.nextText();
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase(RESPONSE_CONTENT_ELEMENT)) {
Log.d("GET_COND_DET_PROTOCOL", "loaded condition info");
}
break;
}
eventType = parser.next();
}
} catch (Exception e) {
error = true;
}
return !error;
}
private int getSkipValue(String response) {
// int SKIP_UTF8_BOM = 3;
int skip = response.indexOf("<");
return skip;
}
@Override
public int getDataIndex(Object inputs){
return 0;
}
@Override
public String getProtocolRequestCode() {
return PROTOCOL_ID;
}
}
| 4,298 | 0.600046 | 0.596793 | 119 | 35.15126 | 28.12327 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.470588 | false | false | 9 |
8c6b3bbac5eee7b8cbb162348f7b113bf9ff2c94 | 8,504,035,298,082 | 8ee330b6f2921408fc40b35fe074ee43963f5750 | /src/main/java/TestI.java | 0fa5c6094eb8ec188d77bba910f10ef61702ad61 | [] | no_license | dagoldenburg/Tests | https://github.com/dagoldenburg/Tests | 0c3984eff184d61374d5e0c9d9ecef81058bb8a1 | f6e349ecf8b6dc6dedcc55aabe8b6d49aa1a0657 | refs/heads/master | 2020-03-09T23:29:31.810000 | 2018-04-13T07:39:53 | 2018-04-13T07:39:53 | 129,059,142 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | abstract class TestI implements Cloneable{
String filename;
public TestI(String filename){
this.filename = filename;
setUpEnvironment();
}
abstract void testSendTransactions(int amountOfTests);
abstract void testRetrieveTransactions(int amountOfTests);
abstract void setUpEnvironment();
void setFileNameEnding(String specificFileName){
filename=specificFileName;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| UTF-8 | Java | 545 | java | TestI.java | Java | [] | null | [] | abstract class TestI implements Cloneable{
String filename;
public TestI(String filename){
this.filename = filename;
setUpEnvironment();
}
abstract void testSendTransactions(int amountOfTests);
abstract void testRetrieveTransactions(int amountOfTests);
abstract void setUpEnvironment();
void setFileNameEnding(String specificFileName){
filename=specificFileName;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| 545 | 0.702752 | 0.702752 | 24 | 21.708334 | 21.839336 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
41798e2b6609fb4ee3c43a4a6ac000d92b30f124 | 2,362,232,072,632 | 67bddb03846593e9be5a67eed19322eea8a96635 | /src/pe/edu/ulima/model/Libro.java | 4ccfe0c8a0fab5ebed62fdd5308a9b8c7417f0c5 | [] | no_license | Falcokun/Proyecto_Biblioteca | https://github.com/Falcokun/Proyecto_Biblioteca | e95adcf2a45fc97135d3d8839961e048948e672f | 20078ea9edf1283b881d182bc2f3419e51b50d5a | refs/heads/master | 2021-01-19T02:15:35.030000 | 2016-07-15T00:30:56 | 2016-07-15T00:30:56 | 35,916,561 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pe.edu.ulima.model;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
/**
* Created by Ricardo on 13/05/2015.
* Usuario
*/
@Entity("libro")
public class Libro {
@Id
ObjectId id;
String titulo;
String carrera;
boolean activo;
int cantidad;
String edicion;
String descripcion;
String autor;
public Libro() {
}
public Libro(String titulo, String carrera, boolean activo, int cantidad, String edicion, String descripcion, String autor) {
this.titulo = titulo;
this.carrera = carrera;
this.activo = activo;
this.cantidad = cantidad;
this.edicion = edicion;
this.descripcion = descripcion;
this.autor = autor;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getCarrera() {
return carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
public boolean isActivo() {
return activo;
}
public boolean getActivo() {
return activo;
}
public void setActivo(boolean activo) {
this.activo = activo;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public String getEdicion() {
return edicion;
}
public void setEdicion(String edicion) {
this.edicion = edicion;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public ObjectId getId() {
return id;
}
@Override
public String toString() {
return "Libro{" +
"id=" + id +
", titulo='" + titulo + '\'' +
", carrera='" + carrera + '\'' +
", activo=" + activo +
", cantidad=" + cantidad +
", edicion='" + edicion + '\'' +
", descripcion='" + descripcion + '\'' +
", autor='" + autor + '\'' +
'}';
}
}
| UTF-8 | Java | 2,417 | java | Libro.java | Java | [
{
"context": "mongodb.morphia.annotations.Id;\n\n/**\n * Created by Ricardo on 13/05/2015.\n * Usuario\n */\n@Entity(\"libro\")\npu",
"end": 177,
"score": 0.999684751033783,
"start": 170,
"tag": "NAME",
"value": "Ricardo"
}
] | null | [] | package pe.edu.ulima.model;
import org.bson.types.ObjectId;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
/**
* Created by Ricardo on 13/05/2015.
* Usuario
*/
@Entity("libro")
public class Libro {
@Id
ObjectId id;
String titulo;
String carrera;
boolean activo;
int cantidad;
String edicion;
String descripcion;
String autor;
public Libro() {
}
public Libro(String titulo, String carrera, boolean activo, int cantidad, String edicion, String descripcion, String autor) {
this.titulo = titulo;
this.carrera = carrera;
this.activo = activo;
this.cantidad = cantidad;
this.edicion = edicion;
this.descripcion = descripcion;
this.autor = autor;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getCarrera() {
return carrera;
}
public void setCarrera(String carrera) {
this.carrera = carrera;
}
public boolean isActivo() {
return activo;
}
public boolean getActivo() {
return activo;
}
public void setActivo(boolean activo) {
this.activo = activo;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public String getEdicion() {
return edicion;
}
public void setEdicion(String edicion) {
this.edicion = edicion;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public ObjectId getId() {
return id;
}
@Override
public String toString() {
return "Libro{" +
"id=" + id +
", titulo='" + titulo + '\'' +
", carrera='" + carrera + '\'' +
", activo=" + activo +
", cantidad=" + cantidad +
", edicion='" + edicion + '\'' +
", descripcion='" + descripcion + '\'' +
", autor='" + autor + '\'' +
'}';
}
}
| 2,417 | 0.55151 | 0.5482 | 114 | 20.201754 | 18.817768 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.429825 | false | false | 9 |
e12f9fe6155692881dc2c1b3a019859c07fda42d | 34,059,090,662,134 | e41a0ce487ff29c86adecf52a8f15f813507897b | /book/ch15-jpa-start/src/main/java/jpabook/exception/ExConfig.java | 9a82e2a0a07d2b10c63b7bc8735b05bb65fb808a | [] | no_license | zacscoding/learning-jpa | https://github.com/zacscoding/learning-jpa | e08febb16bfd5bc3fd6768e790737cb80ad19846 | 1ec941fc2de3c637ab4df232135a57d48c1d5905 | refs/heads/master | 2022-12-23T13:45:55.463000 | 2019-08-20T11:07:30 | 2019-08-20T13:54:18 | 171,112,390 | 0 | 0 | null | false | 2022-12-16T05:45:43 | 2019-02-17T11:09:13 | 2019-08-20T13:54:56 | 2022-12-16T05:45:42 | 490 | 0 | 0 | 24 | Java | false | false | package jpabook.exception;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
/**
* JPA 예외 발생 시 스프링이 제공하는 추상화 된 예외로 변경하기 위한 config
*
* @GitHub : https://github.com/zacscoding
*/
@Configuration
public class ExConfig {
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
| UTF-8 | Java | 592 | java | ExConfig.java | Java | [
{
"context": "변경하기 위한 config\n *\n * @GitHub : https://github.com/zacscoding\n */\n@Configuration\npublic class ExConfig {\n\n @",
"end": 329,
"score": 0.9994838237762451,
"start": 319,
"tag": "USERNAME",
"value": "zacscoding"
}
] | null | [] | package jpabook.exception;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
/**
* JPA 예외 발생 시 스프링이 제공하는 추상화 된 예외로 변경하기 위한 config
*
* @GitHub : https://github.com/zacscoding
*/
@Configuration
public class ExConfig {
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
| 592 | 0.790741 | 0.790741 | 19 | 27.421053 | 28.959711 | 87 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.263158 | false | false | 9 |
b89de89276bcc1f8c0cb0d907f88b291e3b426e6 | 19,610,820,686,041 | 5effec32d3de1769e4ca1b980bdf3b9f2fcfde5c | /src/test/java/ExamplePrimitives.java | 95227fcf81efe24becdae975bb8f875b1f20d0f4 | [] | no_license | ADEMCAKMAK/SpreadSheet | https://github.com/ADEMCAKMAK/SpreadSheet | f200027bee4941f5d814d0b890a540131359ca20 | 18b10160e505fc3a5eca4a30b8b8e9b7150861b3 | refs/heads/master | 2023-04-13T21:06:29.863000 | 2021-04-25T12:45:35 | 2021-04-25T12:45:35 | 327,372,951 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.io.Serializable;
public class ExamplePrimitives implements Serializable {
private static final long serialVersionUID = 8164093788528899177L;
// Integer
byte byteValue;
short shortValue;
int intValue;
long longValue;
// Real
float floatValue;
double doubleValue;
// Character
char charValue;
// Boolean
boolean booleanValue;
public ExamplePrimitives() {
}
public ExamplePrimitives(byte byteValue, short shortValue, int intValue, long longValue,
float floatValue, double doubleValue,
char charValue, boolean booleanValue) {
this.byteValue = byteValue;
this.shortValue = shortValue;
this.intValue = intValue;
this.longValue = longValue;
this.floatValue = floatValue;
this.doubleValue = doubleValue;
this.charValue = charValue;
this.booleanValue = booleanValue;
}
public byte getByteValue() {
return byteValue;
}
public void setByteValue(byte byteValue) {
this.byteValue = byteValue;
}
public short getShortValue() {
return shortValue;
}
public void setShortValue(short shortValue) {
this.shortValue = shortValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public long getLongValue() {
return longValue;
}
public void setLongValue(long longValue) {
this.longValue = longValue;
}
public float getFloatValue() {
return floatValue;
}
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
public char getCharValue() {
return charValue;
}
public void setCharValue(char charValue) {
this.charValue = charValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
| UTF-8 | Java | 2,266 | java | ExamplePrimitives.java | Java | [] | null | [] | import java.io.Serializable;
public class ExamplePrimitives implements Serializable {
private static final long serialVersionUID = 8164093788528899177L;
// Integer
byte byteValue;
short shortValue;
int intValue;
long longValue;
// Real
float floatValue;
double doubleValue;
// Character
char charValue;
// Boolean
boolean booleanValue;
public ExamplePrimitives() {
}
public ExamplePrimitives(byte byteValue, short shortValue, int intValue, long longValue,
float floatValue, double doubleValue,
char charValue, boolean booleanValue) {
this.byteValue = byteValue;
this.shortValue = shortValue;
this.intValue = intValue;
this.longValue = longValue;
this.floatValue = floatValue;
this.doubleValue = doubleValue;
this.charValue = charValue;
this.booleanValue = booleanValue;
}
public byte getByteValue() {
return byteValue;
}
public void setByteValue(byte byteValue) {
this.byteValue = byteValue;
}
public short getShortValue() {
return shortValue;
}
public void setShortValue(short shortValue) {
this.shortValue = shortValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public long getLongValue() {
return longValue;
}
public void setLongValue(long longValue) {
this.longValue = longValue;
}
public float getFloatValue() {
return floatValue;
}
public void setFloatValue(float floatValue) {
this.floatValue = floatValue;
}
public double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(double doubleValue) {
this.doubleValue = doubleValue;
}
public char getCharValue() {
return charValue;
}
public void setCharValue(char charValue) {
this.charValue = charValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
| 2,266 | 0.62842 | 0.620035 | 101 | 21.435644 | 19.878052 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405941 | false | false | 9 |
e651296f1e0c42fa418a34bad3b746c50a6367da | 27,419,071,252,800 | cf1e82a4db2eb785c5ebe6953659901d43cf9e64 | /lolweb/src/com/handler/BuyHeroHandler.java | f5414d392034a0699e9388deb00add70ef45b392 | [] | no_license | Peng-ss/WebDemo-LOL | https://github.com/Peng-ss/WebDemo-LOL | 871d61fe1a8a4b3f2030aac7756ae10b92f30a77 | 4dd4ef89448f392f49d385917787b10fb88027d5 | refs/heads/master | 2021-09-07T21:02:21.642000 | 2018-03-01T03:40:02 | 2018-03-01T03:40:02 | 113,551,138 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.handler;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bean.Hero;
import com.bean.ResultData;
import com.bean.User;
import com.utils.JDBC_Utils;
import com.utils.Servlet_Util;
public class BuyHeroHandler {
public static void buyHero(HttpServletRequest arg0, HttpServletResponse arg1) {
String sql = "SELECT t_hero.*,t_herotype.typeName FROM t_hero,t_herotype WHERE t_hero.id ="
+ arg0.getParameter("t_hero.id") + " AND t_herotype.id=" + arg0.getParameter("t_hero.id");
ResultData rd = new ResultData();
ArrayList<Hero> hero = JDBC_Utils.Query(new Hero(), sql);
String userIsExits = "SELECT * FROM t_user WHERE id='" + arg0.getParameter("user_id") + "'";
ArrayList<User> userList = JDBC_Utils.Query(new User(), userIsExits);
if (hero.get(0).getHeroPrice() <= userList.get(0).getBalance()) {
sql = "INSERT INTO t_userhero(user_id,hero_id) VALUES(" + arg0.getParameter("user_id") + ","
+ arg0.getParameter("t_hero.id") + ")";
int count = JDBC_Utils.JDBC_Update(sql);
if (count == 1) {
sql = "SELECT t_hero.*,t_herotype.typeName FROM t_hero,t_herotype WHERE t_hero.id="
+ arg0.getParameter("t_hero.id") + " AND t_herotype.id=" + arg0.getParameter("t_hero.id");
rd.setMessage("购买" + hero.get(0).getHeroName() + "英雄成功");
sql = "UPDATE t_user SET balance = balance -" + hero.get(0).getHeroPrice() + " WHERE id = '"
+ arg0.getParameter("user_id") + "'";
int num = JDBC_Utils.JDBC_Update(sql);
userIsExits = "SELECT * FROM t_user WHERE id='" + arg0.getParameter("user_id") + "'";
ArrayList<User> userList1 = JDBC_Utils.Query(new User(), userIsExits);
rd.setDatas(userList1);
rd.setCount(num);
rd.setResult(true);
} else {
rd.setMessage("你已经拥有该英雄");
rd.setCount(count);
rd.setResult(true);
}
} else {
rd.setMessage("余额不够,购买失败");
rd.setCount(0);
rd.setResult(false);
rd.setDatas(userList);
}
Servlet_Util.turn(arg0, arg1, rd, "result.jsp");
}
}
| UTF-8 | Java | 2,099 | java | BuyHeroHandler.java | Java | [] | null | [] | package com.handler;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bean.Hero;
import com.bean.ResultData;
import com.bean.User;
import com.utils.JDBC_Utils;
import com.utils.Servlet_Util;
public class BuyHeroHandler {
public static void buyHero(HttpServletRequest arg0, HttpServletResponse arg1) {
String sql = "SELECT t_hero.*,t_herotype.typeName FROM t_hero,t_herotype WHERE t_hero.id ="
+ arg0.getParameter("t_hero.id") + " AND t_herotype.id=" + arg0.getParameter("t_hero.id");
ResultData rd = new ResultData();
ArrayList<Hero> hero = JDBC_Utils.Query(new Hero(), sql);
String userIsExits = "SELECT * FROM t_user WHERE id='" + arg0.getParameter("user_id") + "'";
ArrayList<User> userList = JDBC_Utils.Query(new User(), userIsExits);
if (hero.get(0).getHeroPrice() <= userList.get(0).getBalance()) {
sql = "INSERT INTO t_userhero(user_id,hero_id) VALUES(" + arg0.getParameter("user_id") + ","
+ arg0.getParameter("t_hero.id") + ")";
int count = JDBC_Utils.JDBC_Update(sql);
if (count == 1) {
sql = "SELECT t_hero.*,t_herotype.typeName FROM t_hero,t_herotype WHERE t_hero.id="
+ arg0.getParameter("t_hero.id") + " AND t_herotype.id=" + arg0.getParameter("t_hero.id");
rd.setMessage("购买" + hero.get(0).getHeroName() + "英雄成功");
sql = "UPDATE t_user SET balance = balance -" + hero.get(0).getHeroPrice() + " WHERE id = '"
+ arg0.getParameter("user_id") + "'";
int num = JDBC_Utils.JDBC_Update(sql);
userIsExits = "SELECT * FROM t_user WHERE id='" + arg0.getParameter("user_id") + "'";
ArrayList<User> userList1 = JDBC_Utils.Query(new User(), userIsExits);
rd.setDatas(userList1);
rd.setCount(num);
rd.setResult(true);
} else {
rd.setMessage("你已经拥有该英雄");
rd.setCount(count);
rd.setResult(true);
}
} else {
rd.setMessage("余额不够,购买失败");
rd.setCount(0);
rd.setResult(false);
rd.setDatas(userList);
}
Servlet_Util.turn(arg0, arg1, rd, "result.jsp");
}
}
| 2,099 | 0.66829 | 0.658061 | 52 | 38.48077 | 30.410961 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.115385 | false | false | 9 |
5994196945c0a7acaa6e9a9a2e894296243597c2 | 30,382,598,666,171 | 6b00242c4f16be84ef1a1e090fea0e388da35b8e | /cadgenerico-api/src/main/java/com/generation/cadgenericoapi/repository/UserRespository.java | edc1b3d9d8ebc5e7afb5cda947fb595d80ae9024 | [] | no_license | conteudoGeneration/Deploy | https://github.com/conteudoGeneration/Deploy | 9add800799f781ec28fce7f810fb8dedfb282f82 | d70d34b9118a69e48d045719cc35bf51e54445e0 | refs/heads/master | 2022-06-18T13:55:09.576000 | 2020-05-13T14:33:55 | 2020-05-13T14:33:55 | 263,653,370 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.generation.cadgenericoapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.generation.cadgenericoapi.model.User;
public interface UserRespository extends JpaRepository<User, Long> {
}
| UTF-8 | Java | 236 | java | UserRespository.java | Java | [] | null | [] | package com.generation.cadgenericoapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.generation.cadgenericoapi.model.User;
public interface UserRespository extends JpaRepository<User, Long> {
}
| 236 | 0.838983 | 0.838983 | 9 | 25.222221 | 28.529819 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 9 |
831be32d5b58e3bf9e5cf3a5cf5704b26e4935a7 | 25,529,285,659,494 | 1eb4323b08443d68e39aea7ef64d3b44e2f2ca20 | /taoxuequ-web/src/main/java/com/xuequ/cmoc/auth/LoginAuthenticationProvider.java | c654e95224930ec0f28a050173bdf8dbe255fe10 | [] | no_license | duguruiyuan/cmoc | https://github.com/duguruiyuan/cmoc | 7ccd25abfd4ce081602df8f2305460005026e3de | ffc859b93732efcbc317c0e1c20f9fce904bfe56 | refs/heads/master | 2021-05-07T14:23:24.906000 | 2017-04-27T01:04:25 | 2017-04-27T01:04:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.xuequ.cmoc.auth;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import com.xuequ.cmoc.service.DefaultUserDetailsService;
import com.xuequ.cmoc.utils.MD5Util;
public class LoginAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
private Md5PasswordEncoder passwordEncoder;
private DefaultUserDetailsService userDetailService;
/**
* 检索用户
*/
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
UserDetails loadedUser;
try {
loadedUser = userLoginAuth(authentication);
} catch (AuthenticationException e) {
throw e;
}
return loadedUser;
}
/**
* 用户验证接口
* author zhouhuiqun470
* @param url
* @param userVO
* @return
*/
private AppUser userLoginAuth(UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
AppUser appUser = null;
String userAccount = authentication.getPrincipal().toString();
String password = authentication.getCredentials().toString();
try {
appUser = userDetailService.setUserDetails(userAccount, MD5Util.md5(password));
} catch (AuthException e1){
throw new AuthException(e1.getMessage());
} catch (Exception e) {
logger.error("--userLoginAuth error={}",e);
throw new AuthException(AuthConstant.SYS_EXCEPTION_MESSAGE);
}
return appUser;
}
public Md5PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public void setPasswordEncoder(Md5PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public DefaultUserDetailsService getUserDetailService() {
return userDetailService;
}
public void setUserDetailService(DefaultUserDetailsService userDetailService) {
this.userDetailService = userDetailService;
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
}
}
| UTF-8 | Java | 2,427 | java | LoginAuthenticationProvider.java | Java | [
{
"context": "return loadedUser;\n\t}\n\t\n\t/**\n\t * 用户验证接口\n\t * author zhouhuiqun470\n\t * @param url\n\t * @param userVO\n\t * @return\n\t */",
"end": 1141,
"score": 0.9997073411941528,
"start": 1128,
"tag": "USERNAME",
"value": "zhouhuiqun470"
}
] | null | [] | package com.xuequ.cmoc.auth;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import com.xuequ.cmoc.service.DefaultUserDetailsService;
import com.xuequ.cmoc.utils.MD5Util;
public class LoginAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
private Md5PasswordEncoder passwordEncoder;
private DefaultUserDetailsService userDetailService;
/**
* 检索用户
*/
@Override
protected UserDetails retrieveUser(String username,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
UserDetails loadedUser;
try {
loadedUser = userLoginAuth(authentication);
} catch (AuthenticationException e) {
throw e;
}
return loadedUser;
}
/**
* 用户验证接口
* author zhouhuiqun470
* @param url
* @param userVO
* @return
*/
private AppUser userLoginAuth(UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
AppUser appUser = null;
String userAccount = authentication.getPrincipal().toString();
String password = authentication.getCredentials().toString();
try {
appUser = userDetailService.setUserDetails(userAccount, MD5Util.md5(password));
} catch (AuthException e1){
throw new AuthException(e1.getMessage());
} catch (Exception e) {
logger.error("--userLoginAuth error={}",e);
throw new AuthException(AuthConstant.SYS_EXCEPTION_MESSAGE);
}
return appUser;
}
public Md5PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public void setPasswordEncoder(Md5PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
public DefaultUserDetailsService getUserDetailService() {
return userDetailService;
}
public void setUserDetailService(DefaultUserDetailsService userDetailService) {
this.userDetailService = userDetailService;
}
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
}
}
| 2,427 | 0.783548 | 0.778563 | 80 | 29.0875 | 29.226784 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.4375 | false | false | 9 |
a6c30b8929d34fdb517bc1cce4ce112d0b7ef734 | 10,857,677,360,092 | 60ccc6225d6b656d3865664f92e8d7b86289b328 | /src/acadLabManagementSystem/Publishing.java | 6e2b8e8adacc6da8d3b5ef82f3dc1517e273028e | [] | no_license | laellsr/acadLabManagementSystem | https://github.com/laellsr/acadLabManagementSystem | 11a96a0b1d16f235a6a8ec11d992176e1d1cdf14 | e11da9b523522d2a2404fabf7fcf939cf23e5f63 | refs/heads/master | 2020-04-10T01:38:13.719000 | 2018-12-12T14:24:06 | 2018-12-12T14:24:06 | 160,721,001 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package acadLabManagementSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Publishing
{
ArrayList<String> authors = new ArrayList<String>();
String name, conference, associated; int year;
Scanner input = new Scanner( System.in );
public void setPublishing()
{
System.out.printf("Digite o titulo da publicacao:\n=> ");
name = input.nextLine();
System.out.printf("Digite a conferencia onde foi publicada:\n=> ");
conference = input.nextLine();
System.out.printf("Projeto associado?\n[1] Sim [2] Nao\n=> ");
year = input.nextInt(); input.nextLine();
if (year==1)
{
System.out.printf("Digite o projeto associado:\n=> ");
associated = input.nextLine();
}
System.out.printf("Digite o ano da publicacao:\n=> ");
year = input.nextInt(); input.nextLine();
System.out.printf("Publicacao adicionada!\n\n");
}
}
| UTF-8 | Java | 867 | java | Publishing.java | Java | [] | null | [] | package acadLabManagementSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Publishing
{
ArrayList<String> authors = new ArrayList<String>();
String name, conference, associated; int year;
Scanner input = new Scanner( System.in );
public void setPublishing()
{
System.out.printf("Digite o titulo da publicacao:\n=> ");
name = input.nextLine();
System.out.printf("Digite a conferencia onde foi publicada:\n=> ");
conference = input.nextLine();
System.out.printf("Projeto associado?\n[1] Sim [2] Nao\n=> ");
year = input.nextInt(); input.nextLine();
if (year==1)
{
System.out.printf("Digite o projeto associado:\n=> ");
associated = input.nextLine();
}
System.out.printf("Digite o ano da publicacao:\n=> ");
year = input.nextInt(); input.nextLine();
System.out.printf("Publicacao adicionada!\n\n");
}
}
| 867 | 0.690888 | 0.687428 | 30 | 27.9 | 22.402901 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2 | false | false | 9 |
3547b2116b046ba525dcf331bfe53d02edd72037 | 31,842,887,540,162 | c6fafb17276bd94867d0dfbf7192109425626f0d | /build-plugins/src/main/java/util/RevApiConfig.java | 421b408b80e1e4289379eebcb4512e20ace1244d | [
"Apache-2.0"
] | permissive | renat-nosto/morphia | https://github.com/renat-nosto/morphia | 0774e89cc1712b87ab73ed43126518db56d3530f | 21bda5e417a889b5ce1370c361c2f41dc1c286f1 | refs/heads/master | 2023-03-27T08:20:56.886000 | 2021-02-20T22:54:02 | 2021-02-20T22:54:02 | 346,422,594 | 0 | 0 | Apache-2.0 | true | 2021-03-19T12:36:17 | 2021-03-10T16:35:35 | 2021-03-10T16:35:36 | 2021-03-19T12:36:16 | 350,880 | 0 | 0 | 0 | null | false | false | package util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
@Mojo(name = "revapi-config", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class RevApiConfig extends AbstractMojo {
@Parameter(name = "input", defaultValue = "${project.basedir}/config/revapi-input.json")
private File input;
@Parameter(name = "seed", defaultValue = "${project.basedir}/config/revapi-seed.json")
private File seed;
@Parameter(name = "output", defaultValue = "${project.basedir}/config/revapi.json")
private File output;
@Override
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
try {
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
Map<String, List<Map<String, String>>> inputMap = (Map<String, List<Map<String, String>>>) mapper.readValue(input,
LinkedHashMap.class);
List<Map<String, String>> seedMap = (List<Map<String, String>>) mapper.readValue(seed, ArrayList.class);
Map config = new LinkedHashMap();
config.put("extension", "revapi.ignore");
final List<Map> nodes = new ArrayList<>(seedMap);
inputMap.forEach((code, instances) -> {
nodes.addAll(instances.stream()
.map(instance -> {
Map node = new LinkedHashMap();
node.put("code", code);
node.putAll(instance);
return node;
})
.collect(Collectors.toList()));
});
config.put("configuration", nodes);
mapper.writer()
.withDefaultPrettyPrinter()
.writeValue(output, singletonList(config));
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
| UTF-8 | Java | 2,583 | java | RevApiConfig.java | Java | [] | null | [] | package util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
@Mojo(name = "revapi-config", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class RevApiConfig extends AbstractMojo {
@Parameter(name = "input", defaultValue = "${project.basedir}/config/revapi-input.json")
private File input;
@Parameter(name = "seed", defaultValue = "${project.basedir}/config/revapi-seed.json")
private File seed;
@Parameter(name = "output", defaultValue = "${project.basedir}/config/revapi.json")
private File output;
@Override
@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
try {
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
Map<String, List<Map<String, String>>> inputMap = (Map<String, List<Map<String, String>>>) mapper.readValue(input,
LinkedHashMap.class);
List<Map<String, String>> seedMap = (List<Map<String, String>>) mapper.readValue(seed, ArrayList.class);
Map config = new LinkedHashMap();
config.put("extension", "revapi.ignore");
final List<Map> nodes = new ArrayList<>(seedMap);
inputMap.forEach((code, instances) -> {
nodes.addAll(instances.stream()
.map(instance -> {
Map node = new LinkedHashMap();
node.put("code", code);
node.putAll(instance);
return node;
})
.collect(Collectors.toList()));
});
config.put("configuration", nodes);
mapper.writer()
.withDefaultPrettyPrinter()
.writeValue(output, singletonList(config));
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
| 2,583 | 0.608982 | 0.608982 | 63 | 39.984127 | 29.147949 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.825397 | false | false | 9 |
eae0ae5751f09f4cd27ef5f522e8c80c13a0ae6e | 2,602,750,200,063 | a4ffcbf97d4e3065aacc47a4dda8315ffed75229 | /src/com/streambuf/Main.java | d0f9d0a66f915017a4d05828a7754969bf29b133 | [] | no_license | Jigsawk/rework-risk | https://github.com/Jigsawk/rework-risk | f81cfd242dec35f9d6b000e5bd945d6f4a46a903 | 892c77ea55c5e643ffefb727d1f058ad9590f009 | refs/heads/master | 2021-01-14T22:36:23.956000 | 2020-02-28T03:44:09 | 2020-02-28T03:44:09 | 242,782,643 | 1 | 0 | null | false | 2020-02-27T15:01:58 | 2020-02-24T16:14:56 | 2020-02-24T16:16:40 | 2020-02-27T15:01:47 | 67 | 0 | 0 | 0 | Java | false | false | package com.streambuf;
import com.streambuf.panel.MainPanel;
import com.streambuf.service.ReworkService;
import com.streambuf.util.GraphicsConstants;
import javax.swing.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
initFrame();
rework();
}
private static void initFrame() {
MainPanel p = new MainPanel();
Thread panelThread = new Thread(p);
JFrame frame = new JFrame();
frame.add(p);
frame.setSize(1200, 1200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setTitle("复工传染情况模拟");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelThread.start();
}
private static void rework() {
ReworkService reworkService = new ReworkService();
try {
reworkService.rework();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 982 | java | Main.java | Java | [] | null | [] | package com.streambuf;
import com.streambuf.panel.MainPanel;
import com.streambuf.service.ReworkService;
import com.streambuf.util.GraphicsConstants;
import javax.swing.*;
public class Main {
public static void main(String[] args) throws InterruptedException {
initFrame();
rework();
}
private static void initFrame() {
MainPanel p = new MainPanel();
Thread panelThread = new Thread(p);
JFrame frame = new JFrame();
frame.add(p);
frame.setSize(1200, 1200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setTitle("复工传染情况模拟");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelThread.start();
}
private static void rework() {
ReworkService reworkService = new ReworkService();
try {
reworkService.rework();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 982 | 0.625259 | 0.616977 | 37 | 25.108109 | 18.782948 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.567568 | false | false | 9 |
f1b7020defaf8890d5b7f2e498146620a52c30d7 | 12,232,066,885,926 | 914cab172293ad66bd219ab83875f7f7bf1108ba | /trunk/teacher/src/main/java/com/abings/baby/teacher/ui/main/fm/school/SchoolMasterPresenter.java | 9911878ccbcc5485b0470d384ed3f76a46ffbd25 | [
"Apache-2.0"
] | permissive | Soon-gz/HelloV3 | https://github.com/Soon-gz/HelloV3 | 9a19bf661e0ae2732fd699959388bc604557a92f | 07b2c321ac01bfd28338045e6e9793b2627a1d35 | refs/heads/master | 2023-02-24T07:35:41.758000 | 2018-03-19T04:31:24 | 2018-03-19T04:31:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.abings.baby.teacher.ui.main.fm.school;
import com.abings.baby.teacher.ZSApp;
import com.alibaba.fastjson.JSONObject;
import com.hellobaby.library.data.DataManager;
import com.hellobaby.library.data.model.BaseModel;
import com.hellobaby.library.data.remote.rx.RxThread;
import com.hellobaby.library.data.remote.rx.SubscriberClass;
import com.hellobaby.library.ui.base.BasePresenter;
import javax.inject.Inject;
/**
* 作者:ShuWen
* 时间: 2017/12/28.
* 描述:
*/
public class SchoolMasterPresenter extends BasePresenter {
DataManager dataManager;
@Inject
public SchoolMasterPresenter(DataManager dataManager){
this.dataManager = dataManager;
}
public void selectClassAndGrade(){
dataManager.selectClassAndGrade(Integer.parseInt(ZSApp.getInstance().getSchoolId()))
.compose(RxThread.<BaseModel<JSONObject>>subscribe_Io_Observe_On())
.subscribe(new SubscriberClass<JSONObject>(bMvpView) {
@Override
protected void callSuccess(JSONObject s) {
bMvpView.showData(s);
}
});
}
}
| UTF-8 | Java | 1,176 | java | SchoolMasterPresenter.java | Java | [
{
"context": "resenter;\n\nimport javax.inject.Inject;\n\n/**\n * 作者:ShuWen\n * 时间: 2017/12/28.\n * 描述:\n */\n\npublic class Schoo",
"end": 441,
"score": 0.9701432585716248,
"start": 435,
"tag": "NAME",
"value": "ShuWen"
}
] | null | [] | package com.abings.baby.teacher.ui.main.fm.school;
import com.abings.baby.teacher.ZSApp;
import com.alibaba.fastjson.JSONObject;
import com.hellobaby.library.data.DataManager;
import com.hellobaby.library.data.model.BaseModel;
import com.hellobaby.library.data.remote.rx.RxThread;
import com.hellobaby.library.data.remote.rx.SubscriberClass;
import com.hellobaby.library.ui.base.BasePresenter;
import javax.inject.Inject;
/**
* 作者:ShuWen
* 时间: 2017/12/28.
* 描述:
*/
public class SchoolMasterPresenter extends BasePresenter {
DataManager dataManager;
@Inject
public SchoolMasterPresenter(DataManager dataManager){
this.dataManager = dataManager;
}
public void selectClassAndGrade(){
dataManager.selectClassAndGrade(Integer.parseInt(ZSApp.getInstance().getSchoolId()))
.compose(RxThread.<BaseModel<JSONObject>>subscribe_Io_Observe_On())
.subscribe(new SubscriberClass<JSONObject>(bMvpView) {
@Override
protected void callSuccess(JSONObject s) {
bMvpView.showData(s);
}
});
}
}
| 1,176 | 0.680484 | 0.673575 | 39 | 28.692308 | 26.103497 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.333333 | false | false | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.