blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
dae0a3c37ecdbaacdd298650d74e72fe0ad14fe1
|
Java
|
vovius/algo
|
/src/main/java/com/training/algo/RotateDoublyLLByN.java
|
UTF-8
| 661
| 2.8125
| 3
|
[] |
no_license
|
package com.training.algo;
import com.training.util.DoublyLL;
public class RotateDoublyLLByN {
public DoublyLL<Character> list;
public RotateDoublyLLByN(DoublyLL<Character> list) {
this.list = list;
}
public void rotateByN(int n) {
DoublyLL.Node nodeN = list.head;
for (int i=0 ; i < n; i++) {
nodeN = nodeN.next;
}
DoublyLL.Node oldHead = list.head;
DoublyLL.Node oldEnd = list.end;
list.head = nodeN;
list.end = nodeN.prior;
list.head.prior = null;
list.end.next = null;
oldHead.prior = oldEnd;
oldEnd.next = oldHead;
}
}
| true
|
cf98f7c2a810f9e8cadc3f0c4cdbb0c570476116
|
Java
|
PaulinaEEF/Proyecto
|
/src/Vehiculos/MainServidor.java
|
UTF-8
| 314
| 2.078125
| 2
|
[
"MIT"
] |
permissive
|
package Vehiculos;
import java.io.IOException;
//Clase principal que hará uso del servidor
public class MainServidor implements Runnable{
public static void main(String[] args) throws IOException
{
Probando c = new Probando();
}
@Override
public void run() {
}
}
| true
|
a5342f41f071ad0cb8ee01a161b9e3d8c217ef10
|
Java
|
htsit01/team_manager_android
|
/app/src/main/java/com/example/asus/teammanager/presenter/visit_plan/GetSalesmanVisitPlanListPresenter.java
|
UTF-8
| 1,591
| 2.203125
| 2
|
[] |
no_license
|
package com.example.asus.teammanager.presenter.visit_plan;
import com.example.asus.teammanager.model.connection.ApiConnection;
import com.example.asus.teammanager.model.response.SalesmanPlanListResponse;
import com.example.asus.teammanager.presenter.GlobalPresenter;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class GetSalesmanVisitPlanListPresenter {
private GlobalPresenter globalPresenter;
public GetSalesmanVisitPlanListPresenter (GlobalPresenter globalPresenter){
this.globalPresenter = globalPresenter;
}
public void getSalesmanVisitPlanList(String token, int id, int day){
ApiConnection.getInstance().getRoutes().getSalesmanVisitPlanList("Bearer ".concat(token), id, day).enqueue(new Callback<SalesmanPlanListResponse>() {
@Override
public void onResponse(Call<SalesmanPlanListResponse> call, Response<SalesmanPlanListResponse> response) {
if(response.code()==200){
globalPresenter.onSuccess(response.body());
}
else{
try {
globalPresenter.onError(response.code(), response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<SalesmanPlanListResponse> call, Throwable t) {
globalPresenter.onFail(t.getMessage());
}
});
}
}
| true
|
9dcbc6d5fa44d1bf3aef579933624771346085f7
|
Java
|
BrhaneWeldeslase/EnterpriseArchitecture544
|
/lab4Association2/src/main/java/manytooneuniuni/AppBook.java
|
UTF-8
| 686
| 2.421875
| 2
|
[] |
no_license
|
package manytooneuniuni;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class AppBook
{
private static EntityManagerFactory emf;
public static void main(String[] args){
emf= Persistence.createEntityManagerFactory("cs544");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Publisher p = new Publisher("Tina","Xing");
Book bk = new Book("WAA","A-1234",p);
bk.setPublisher(p);
em.persist(p);
em.persist(bk);
em.getTransaction().commit();
em.close();
}
}
| true
|
29da91228553f2368684c86d1e31dcecbca229d1
|
Java
|
timmalich/openiam
|
/src/main/java/com/malichzhang/openiam/repository/AccessorRepository.java
|
UTF-8
| 1,264
| 2.078125
| 2
|
[] |
no_license
|
package com.malichzhang.openiam.repository;
import com.malichzhang.openiam.domain.Accessor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
/**
* Spring Data repository for the Accessor entity.
*/
@Repository
public interface AccessorRepository extends JpaRepository<Accessor, Long> {
@Query(value = "select distinct accessor from Accessor accessor left join fetch accessor.entitlements left join fetch accessor.organizations",
countQuery = "select count(distinct accessor) from Accessor accessor")
Page<Accessor> findAllWithEagerRelationships(Pageable pageable);
@Query("select distinct accessor from Accessor accessor left join fetch accessor.entitlements left join fetch accessor.organizations")
List<Accessor> findAllWithEagerRelationships();
@Query("select accessor from Accessor accessor left join fetch accessor.entitlements left join fetch accessor.organizations where accessor.id =:id")
Optional<Accessor> findOneWithEagerRelationships(@Param("id") Long id);
}
| true
|
7369bb2fc6b14ae39c2921b4799387df51b1a57e
|
Java
|
masterkj/contact-app
|
/src/main/java/com/internetapplication/ws/ui/controller/UserController.java
|
UTF-8
| 1,968
| 2.25
| 2
|
[] |
no_license
|
package com.internetapplication.ws.ui.controller;
import com.internetapplication.ws.ErrorMessages;
import com.internetapplication.ws.service.UserService;
import com.internetapplication.ws.shared.dto.UserDto;
import com.internetapplication.ws.ui.model.request.UserDetailsRequestModel;
import com.internetapplication.ws.ui.model.response.UserRest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private
UserService userService;
@GetMapping(path = "/{id}",
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public UserRest getUser(@PathVariable String id) {
UserRest userRest = new UserRest();
UserDto userDto = userService.getUserByUserId(id);
BeanUtils.copyProperties(userDto, userRest);
return userRest;
}
@PostMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public UserRest createUser(@RequestBody UserDetailsRequestModel userDetails) throws Exception {
UserRest returnedValue = new UserRest();
if(userDetails.getFirstName().isEmpty()) throw new Exception(ErrorMessages.MESSING_REQUIRED_FIELD.getErrorMessage());
UserDto userDto = new UserDto();
BeanUtils.copyProperties(userDetails, userDto);
UserDto createdUser = userService.createUser(userDto);
BeanUtils.copyProperties(createdUser, returnedValue);
return returnedValue;
}
@PutMapping
public String updateUser() {
return "update user was called";
}
@DeleteMapping
public String deleteUser() {
return "delete user was called";
}
}
| true
|
87b87a954cace42eaec87a54865cbcda419d528a
|
Java
|
surajdeop/nokiatest
|
/eventconsumer/src/main/java/com/event/consumer/services/impl/EventService.java
|
UTF-8
| 1,138
| 2.234375
| 2
|
[] |
no_license
|
package com.event.consumer.services.impl;
import com.event.consumer.models.Events;
import com.event.consumer.models.Event;
import com.event.consumer.repository.EventRepository;
import com.event.consumer.services.IEventService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EventService implements IEventService {
private static final Logger logger = LoggerFactory.getLogger(EventService.class);
@Autowired
private EventRepository eventRepository;
// getting all Entity records
@Override
public Events getEvents() {
logger.info("Get all events");
Events events = new Events();
eventRepository.findAll().forEach(event -> events.getEvents().add(event));
return events;
}
// getting a specific record
@Override
public Event getEventById(String clientId) {
return eventRepository.findById(clientId).get();
}
@Override
public void saveOrUpdate(Event event) {
eventRepository.save(event);
}
}
| true
|
703e1ead1c7f11458e8b73e8c34180c2c82aefab
|
Java
|
maryfeng/FinalSearchEngine
|
/org/uiowa/cs2820/engine/GreaterThanSearch.java
|
UTF-8
| 603
| 2.640625
| 3
|
[] |
no_license
|
package org.uiowa.cs2820.engine;
public class GreaterThanSearch extends Search{
Field target;
Database D;
public GreaterThanSearch(Field f){
D = new LinearDiskDatabase();
target = f;
}
public ListIterator<String> doSearch() {
SearchGreater S = new SearchGreater(target);
String [] R = D.fetch(S);
if (R == null) R = new String[0];
ListIterator<String> L = new ListIterator<String>(R);
return L;
}
//this is only for test and debugging
public String toString() {
return "GreaterThanSearch (" + target.getFieldName() + "," + target.getFieldValue().toString() + ")";
}
}
| true
|
4ab0c4cd6d2ec2def687d03e6a87407bdc48888f
|
Java
|
guangjianwei/ssm_sum
|
/basic-code/day09-code/src/cn/itcast/day09/demo10/Coder.java
|
UTF-8
| 398
| 3.21875
| 3
|
[] |
no_license
|
package cn.itcast.day09.demo10;
/*
2.定义程序员类
属性:
姓名 工号 工资
行为:
工作work
*/
public class Coder extends worker{
public Coder(String name, int workNum, int salary, int bonus) {
super(name, workNum, salary, bonus);
}
public Coder() {
}
@Override
public void work(){
System.out.println("程序员工作");
}
}
| true
|
88c578c4d496e016e0e46c1cc442e00cf074d74c
|
Java
|
tpeang/datalearn
|
/src/Algorithm/TestNumber.java
|
UTF-8
| 1,378
| 3.921875
| 4
|
[] |
no_license
|
/**
* 题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
*/
package Algorithm;
import java.util.Scanner;
/**
* @author Ian
* @date 2016年5月11日上午11:03:11
*
*/
public class TestNumber {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("请输入一个正整数:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int[] a = new int[5];
int b = 0;
int n = 0;
for (int i = 4; i >= 0; i--) {
b = (int) Math.pow(10, i);
if (num / b != 0 && i >= n) {
n = i + 1; // 位数=最高位+1
}
a[i] = num / b;
num = num - a[i] * b;
}
System.out.println("位数:" + n);
for (int j = 0; j < n; j++) {
if (a[j] != -1) {
System.out.print(a[j] + "\t");
}
}
System.out.println("");
// test();
}
//另一种简单方法
/*
public static void test(){
System.out.println("请输入一个正整数:");
Scanner sc = new Scanner(System.in);
String num = sc.nextLine();
int numLength = num.length();
System.out.println("位数:"+numLength);
for(int i = numLength-1; i>=0;i--){
System.out.print(num.charAt(i)+"\t");
}
}
*/
}
| true
|
d6ddbf70b26b35556545dc0c4fdf04730e2ea04a
|
Java
|
1956025812/privilege
|
/src/main/java/com/authorization/privilege/mapper/dsprivilegeread/role/SysRoleReadMapper.java
|
UTF-8
| 1,489
| 2.078125
| 2
|
[] |
no_license
|
package com.authorization.privilege.mapper.dsprivilegeread.role;
import com.authorization.privilege.entity.dsprivelege.role.SysRole;
import com.authorization.privilege.vo.role.SysRoleVO;
import org.apache.ibatis.annotations.MapKey;
import java.util.HashMap;
import java.util.List;
/**
* @author qjwyss
* @date 2018/12/4
* @description 菜单读MAPPER接口
*/
public interface SysRoleReadMapper {
/**
* 根据主键查询角色对象
*
* @param rid
* @return SysRole
* @throws Exception
*/
SysRole selectByPrimaryKey(String rid) throws Exception;
/**
* 查询角色列表
*
* @param sysRoleVO
* @return SysRoleVO集合
* @throws Exception
*/
List<SysRoleVO> selectSysRoleList(SysRoleVO sysRoleVO) throws Exception;
/**
* 查询角色ID和角色VO对象MAP
*
* @param sysRoleVO
* @return 角色ID和角色VO对象MAP
* @throws Exception
*/
@MapKey("rid")
HashMap<String, SysRoleVO> selectRoleIdAndRoleVOMap(SysRoleVO sysRoleVO) throws Exception;
/**
* 查询角色VO对象
*
* @param sysRoleVO
* @return SysRoleVO
* @throws Exception
*/
SysRoleVO selectSysRoleVO(SysRoleVO sysRoleVO) throws Exception;
/**
* 查询角色列表数量
*
* @param sysRoleVO
* @return 角色列表数量
* @throws Exception
*/
Integer selectCountOfSysRoleList(SysRoleVO sysRoleVO) throws Exception;
}
| true
|
d46b0f74df629677c088903ea6e5f468f2d471db
|
Java
|
tixti/5cardstud
|
/5cardstud/src/main/java/fivecardstud/logic/ThreeOfAKind.java
|
UTF-8
| 1,060
| 3.390625
| 3
|
[] |
no_license
|
package fivecardstud.logic;
import java.util.ArrayList;
/**
*
* Kolmoset.
*/
public class ThreeOfAKind implements Rank {
private final int value;
/**
* Etsii annetun käden korteista, minkä kokoiset kolmoset käsi sisältää.
*
* @param cards kortit joista käsi muodostuu
*/
public ThreeOfAKind(ArrayList<Card> cards) {
this.value = cards.get(2).getValue();
}
/**
* Palauttaa arvon, josta kolmoset koostuvat. Tällä voidaan vertailla
* kolmosia toisiin kolmosiin.
*
* @return arvo josta kolmoset koostuvat
*/
public int getValue() {
return value;
}
@Override
public int rankAsNumber() {
return 4;
}
@Override
public int compareTo(Rank r) {
if (rankAsNumber() != r.rankAsNumber()) {
return rankAsNumber() - r.rankAsNumber();
}
ThreeOfAKind t = (ThreeOfAKind) r;
return value - t.getValue();
}
@Override
public String toString() {
return "Three of A Kind";
}
}
| true
|
025c94f80522e828c8702b138a123643da80a537
|
Java
|
Eric05/CC_Logbook
|
/Excercises/src/com/company/November/Comparator/EmployeeNameComparator.java
|
UTF-8
| 416
| 3.34375
| 3
|
[] |
no_license
|
package com.company.November.Comparator;
import java.util.Comparator;
// list.sort(Comparator.comparingInt(Employee::getYear));
// list.sort(Comparator.comparing(Employee::isMale).reversed());
public class EmployeeNameComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareToIgnoreCase(e2.getName());
}
}
| true
|
5f1f646d4cf20bb87ea59eb624aeac357c0b36fc
|
Java
|
TruthBean/fake-spring
|
/src/main/java/com/truthbean/debbie/fakespring/mvc/RequestMappingRouterParser.java
|
UTF-8
| 10,469
| 2.125
| 2
|
[
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/**
* Copyright (c) 2021 TruthBean(Rogar·Q)
* Debbie is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package com.truthbean.debbie.fakespring.mvc;
import com.truthbean.debbie.io.MediaType;
import com.truthbean.debbie.mvc.request.HttpMethod;
import com.truthbean.debbie.mvc.router.RouterAnnotationInfo;
import com.truthbean.debbie.mvc.router.RouterAnnotationParser;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
/**
* @author TruthBean/Rogar·Q
* @since 0.1.0
* Created on 2020-09-21 14:24
*/
public class RequestMappingRouterParser implements RouterAnnotationParser {
@Override
public RouterAnnotationInfo parse(Method method) {
boolean hasResponseBody = false;
var responseBody = method.getAnnotation(ResponseBody.class);
String[] prefix = null;
if (responseBody == null) {
Class<?> declaringClass = method.getDeclaringClass();
RequestMapping requestMapping = declaringClass.getAnnotation(RequestMapping.class);
if (requestMapping != null) {
String[] value = requestMapping.value();
if (value.length > 0) {
prefix = value;
} else {
prefix = requestMapping.path();
}
}
responseBody = declaringClass.getAnnotation(ResponseBody.class);
if (responseBody == null) {
RestController annotation = declaringClass.getAnnotation(RestController.class);
hasResponseBody = annotation != null;
}
} else {
hasResponseBody = true;
}
var requestMapping = method.getAnnotation(RequestMapping.class);
DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);
GetMapping getMapping = method.getAnnotation(GetMapping.class);
PostMapping postMapping = method.getAnnotation(PostMapping.class);
PutMapping putMapping = method.getAnnotation(PutMapping.class);
if (requestMapping != null) {
return parse(prefix, requestMapping, hasResponseBody);
} else if (deleteMapping != null) {
return parse(prefix, deleteMapping, hasResponseBody);
} else if (getMapping != null) {
return parse(prefix, getMapping, hasResponseBody);
} else if (postMapping != null) {
return parse(prefix, postMapping, hasResponseBody);
} else if (putMapping != null) {
return parse(prefix, putMapping, hasResponseBody);
}
return null;
}
public RouterAnnotationInfo parse(String[] prefix, RequestMapping requestMapping, boolean hasResponseBody) {
var info = new RouterAnnotationInfo();
var consumes = requestMapping.consumes();
var produces = requestMapping.produces();
var method = requestMapping.method();
info.setName(requestMapping.name());
String[] v = requestMapping.value();
if (v.length == 0) {
v = requestMapping.path();
}
if (prefix != null && prefix.length > 0 && v.length > 0) {
String[] path = new String[prefix.length * v.length];
int i = 0;
for (String s : prefix) {
for (String s1 : v) {
path[i++] = s + "/" + s1;
}
}
info.setValue(path);
} else if (v.length > 0) {
info.setValue(v);
} else {
info.setValue(prefix);
}
if (method.length > 0) {
info.setMethod(Arrays.stream(method).map(RequestMethod::toHttpMethod).toArray(value -> new HttpMethod[0]));
} else {
info.setMethod(Collections.singleton(HttpMethod.ALL));
}
if (consumes.length > 0) {
info.setRequestType(consumes[0]);
} else {
info.setRequestType(MediaType.ANY);
}
if (produces.length > 0) {
info.setResponseType(MediaType.of(produces[0]));
} else {
info.setResponseType(MediaType.ANY);
}
info.setHasTemplate(!hasResponseBody);
info.setTemplatePrefix("");
info.setTemplateSuffix("");
return info;
}
public RouterAnnotationInfo parse(String[] prefix, DeleteMapping requestMapping, boolean hasResponseBody) {
var info = new RouterAnnotationInfo();
var consumes = requestMapping.consumes();
var produces = requestMapping.produces();
info.setName(requestMapping.name());
String[] v = requestMapping.value();
if (v.length == 0) {
v = requestMapping.path();
}
if (prefix != null && prefix.length > 0 && v.length > 0) {
String[] path = new String[prefix.length * v.length];
int i = 0;
for (String s : prefix) {
for (String s1 : v) {
path[i++] = s + "/" + s1;
}
}
info.setValue(path);
} else if (v.length > 0) {
info.setValue(v);
} else {
info.setValue(prefix);
}
info.setMethod(Collections.singleton(HttpMethod.DELETE));
if (consumes.length > 0) {
info.setRequestType(consumes[0]);
} else {
info.setRequestType(MediaType.ANY);
}
if (produces.length > 0) {
info.setResponseType(MediaType.of(produces[0]));
} else {
info.setResponseType(MediaType.ANY);
}
info.setHasTemplate(!hasResponseBody);
info.setTemplatePrefix("");
info.setTemplateSuffix("");
return info;
}
public RouterAnnotationInfo parse(String[] prefix, GetMapping requestMapping, boolean hasResponseBody) {
var info = new RouterAnnotationInfo();
var consumes = requestMapping.consumes();
var produces = requestMapping.produces();
info.setName(requestMapping.name());
String[] v = requestMapping.value();
if (v.length == 0) {
v = requestMapping.path();
}
if (prefix != null && prefix.length > 0 && v.length > 0) {
String[] path = new String[prefix.length * v.length];
int i = 0;
for (String s : prefix) {
for (String s1 : v) {
path[i++] = s + "/" + s1;
}
}
info.setValue(path);
} else if (v.length > 0) {
info.setValue(v);
} else {
info.setValue(prefix);
}
info.setMethod(Collections.singleton(HttpMethod.DELETE));
if (consumes.length > 0) {
info.setRequestType(consumes[0]);
} else {
info.setRequestType(MediaType.ANY);
}
if (produces.length > 0) {
info.setResponseType(MediaType.of(produces[0]));
} else {
info.setResponseType(MediaType.ANY);
}
info.setHasTemplate(!hasResponseBody);
info.setTemplatePrefix("");
info.setTemplateSuffix("");
return info;
}
public RouterAnnotationInfo parse(String[] prefix, PostMapping requestMapping, boolean hasResponseBody) {
var info = new RouterAnnotationInfo();
var consumes = requestMapping.consumes();
var produces = requestMapping.produces();
info.setName(requestMapping.name());
String[] v = requestMapping.value();
if (v.length == 0) {
v = requestMapping.path();
}
if (prefix != null && prefix.length > 0 && v.length > 0) {
String[] path = new String[prefix.length * v.length];
int i = 0;
for (String s : prefix) {
for (String s1 : v) {
path[i++] = s + "/" + s1;
}
}
info.setValue(path);
} else if (v.length > 0) {
info.setValue(v);
} else {
info.setValue(prefix);
}
info.setMethod(Collections.singleton(HttpMethod.DELETE));
if (consumes.length > 0) {
info.setRequestType(consumes[0]);
} else {
info.setRequestType(MediaType.ANY);
}
if (produces.length > 0) {
info.setResponseType(MediaType.of(produces[0]));
} else {
info.setResponseType(MediaType.ANY);
}
info.setHasTemplate(!hasResponseBody);
info.setTemplatePrefix("");
info.setTemplateSuffix("");
return info;
}
public RouterAnnotationInfo parse(String[] prefix, PutMapping requestMapping, boolean hasResponseBody) {
var info = new RouterAnnotationInfo();
var consumes = requestMapping.consumes();
var produces = requestMapping.produces();
info.setName(requestMapping.name());
String[] v = requestMapping.value();
if (v.length == 0) {
v = requestMapping.path();
}
if (prefix != null && prefix.length > 0 && v.length > 0) {
String[] path = new String[prefix.length * v.length];
int i = 0;
for (String s : prefix) {
for (String s1 : v) {
path[i++] = s + "/" + s1;
}
}
info.setValue(path);
} else if (v.length > 0) {
info.setValue(v);
} else {
info.setValue(prefix);
}
info.setMethod(Collections.singleton(HttpMethod.DELETE));
if (consumes.length > 0) {
info.setRequestType(consumes[0]);
} else {
info.setRequestType(MediaType.ANY);
}
if (produces.length > 0) {
info.setResponseType(MediaType.of(produces[0]));
} else {
info.setResponseType(MediaType.ANY);
}
info.setHasTemplate(!hasResponseBody);
info.setTemplatePrefix("");
info.setTemplateSuffix("");
return info;
}
}
| true
|
0a0e8720600e661c861a8d18d8afabd11e90cdfd
|
Java
|
luciferDark/clientKylinTalk
|
/common/src/main/java/com/ll/common/app/Util/Logger.java
|
UTF-8
| 1,400
| 2.375
| 2
|
[] |
no_license
|
package com.ll.common.app.Util;
import android.util.Log;
public class Logger {
private Logger() {
}
private static boolean isDebug = true;//是否是测试包
private static final String TAG = "com.ll";//是否是测试包
public static void LogI(String msg) {
Logger.LogI(msg, TAG);
}
public static void LogI(String msg, String tag) {
if (!isDebug) {
return;
}
Log.i(tag, "==>\t" + msg);
}
public static void LogD(String msg) {
Logger.LogD(msg, TAG);
}
public static void LogD(String msg, String tag) {
if (!isDebug) {
return;
}
Log.d(tag, "==>\t" + msg);
}
public static void LogW(String msg) {
Logger.LogW(msg, TAG);
}
public static void LogW(String msg, String tag) {
if (!isDebug) {
return;
}
Log.w(tag, "==>\t" + msg);
}
public static void LogE(String msg) {
Logger.LogE(msg, TAG);
}
public static void LogE(String msg, String tag) {
if (!isDebug) {
return;
}
Log.e(tag, "==>\t" + msg);
}
public static void LogV(String msg) {
Logger.LogV(msg, TAG);
}
public static void LogV(String msg, String tag) {
if (!isDebug) {
return;
}
Log.v(tag, "==>\t" + msg);
}
}
| true
|
3a358241e91fa25417f445886c8b711de5187a1b
|
Java
|
DennisKingsman/NfBanckAppTomCat
|
/NFBankApplication/src/main/java/dao/UserAccountDao.java
|
UTF-8
| 9,855
| 2.65625
| 3
|
[] |
no_license
|
package dao;
import bean.UserAccount;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UserAccountDao {
private static final Logger logger = LoggerFactory.getLogger(UserAccountDao.class);
private static final String SQL_REQUEST_INSERT_INIT = "insert into user_account(user_login, user_password, user_role) values (?, ?, ?)";
private static final String SQL_REQUEST_SELECT_PROFILE = "select * from user_account where user_login = ?";
private static final String SQL_REQUEST_LOGIN = "select user_login, user_password from user_account where user_login = ? and user_password = ?";
private static final String SQL_REQ_SEARCH_REGISTERED_USER = "select user_login from user_account where user_login = ?";
private static final String SQL_REQUEST_DELETE = "delete from user_account where user_login = ?";
private static final String SQL_REQUEST_UPDATE_DOB = "update user_account set date_of_birth = ? where user_login = ?";
private static final String SQL_REQUEST_UPDATE_NAME = "update user_account set user_name = ? where user_login = ?";
private static final String SQL_REQUEST_UPDATE_SNAME = "update user_account set second_name = ? where user_login = ?";
private static final String SQL_REQUEST_UPDATE_PROFILE = "update user_account set date_of_birth = ?, user_name = ?, second_name = ? where user_login = ?";
private ConnectionBuilder connectionBuilder;
public UserAccountDao() {
}
public void setConnectionBuilder(ConnectionBuilder connectionBuilder) {
this.connectionBuilder = connectionBuilder;
}
private Connection getConnection() throws SQLException {
return this.connectionBuilder.getConnection();
}
public void updateUserProfileParam(String login, String param, String paramLabel){
logger.info("updateUserProfileParam has started");
paramLabel = paramLabel.substring(1);
logger.info("new param label: " + paramLabel);
String requiredStatement;
int mark = 0;
switch (paramLabel){
case "name":
logger.info("Name case in doPost method");
requiredStatement = SQL_REQUEST_UPDATE_NAME;
break;
case "secondName":
logger.info("second name case in doPost method");
requiredStatement = SQL_REQUEST_UPDATE_SNAME;
break;
default:
logger.info("ALERT!!! NO SQL REQUEST WAS SETTLED");
requiredStatement = null;
}
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(requiredStatement)){
int counter = 1;
preparedStatement.setString(counter++, param);
preparedStatement.setString(counter, login);
logger.info("result statement is: " + preparedStatement);
int row = preparedStatement.executeUpdate();
logger.info("Was updated " + row + " rows, updating complete! ");
} catch (SQLException e) {
logger.info("updateUserProfileParam fails");
e.printStackTrace();
}
}
public UserAccount loginPerson(String login, String password){
logger.info("Loggining has started in loginPerson method");
UserAccount userAccount = new UserAccount();
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQUEST_LOGIN)){
logger.info("transferred login and password are: " + login + " " + password);
int counter = 1;
preparedStatement.setString(counter++, login);
preparedStatement.setString(counter++, password);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
logger.info("ResultSet.next has called. Contains: "
+ resultSet.getString("user_login")
+ " "
+ resultSet.getString("user_password"));
userAccount.setLogin(login);
userAccount.setPassword(password);
userAccount.setRole("USER");
logger.info("userAccount object preparation were complete");
}
logger.info("after if");
} catch (SQLException e) {
logger.info("login fails");
e.printStackTrace();
}
logger.info("before return userAccount: " + userAccount.getLogin());
return userAccount;
}
public UserAccount getProfile(String login){
logger.info("getting profile has started");
UserAccount userAccount = new UserAccount();
logger.info("before setting connection");
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQUEST_SELECT_PROFILE)){
logger.info("Connected successfully");
int counter = 1;
preparedStatement.setString(counter, login);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
logger.info("Preparing user account object...");
userAccount.setLogin(login);
userAccount.setPassword(resultSet.getString("user_password"));
userAccount.setRole("USER");
userAccount.setDate(resultSet.getDate("date_of_birth"));
userAccount.setName(resultSet.getString("user_name"));
userAccount.setSecondName(resultSet.getString("second_name"));
}else logger.info("empty result set!!!");
} catch (SQLException e) {
logger.info("getProfile method fails");
e.printStackTrace();
}
return userAccount;
}
public void registerUserAccount(String login, String password){
logger.info("register in DB has started");
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQUEST_INSERT_INIT)){
int counter = 1;
preparedStatement.setString(counter++, login);
preparedStatement.setString(counter++, password);
preparedStatement.setString(counter++, "USER");
preparedStatement.executeUpdate();
logger.info("register complete");
} catch (SQLException e) {
logger.info("register fails");
e.printStackTrace();
}
}
public boolean hasSameLoginInDataBase(String userLogin) {
logger.info("CheckForRegistration method has called");
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQ_SEARCH_REGISTERED_USER)) {
String loginFromDB;
int counter = 1;
preparedStatement.setString(counter++, userLogin);
logger.info("Statement in hasSameLogin: " + preparedStatement);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
loginFromDB = resultSet.getString("user_login");
logger.info("Query was execute: " + loginFromDB + ". Compare logins: " + userLogin.equals(loginFromDB) + ". Checking resultSet: " + !resultSet.next());
if (!userLogin.equals(loginFromDB)) {
return false;
}else {
logger.info("User founded");
return true;
}
} else {
logger.info("No such result set");
return false;
}
} catch(Exception e){
logger.info("did not searched same login in DB");
e.printStackTrace();
}
return false;
}
public void setUserProfile(String login, Date date, String name, String secondName){
logger.info("setUserProfile has started");
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQUEST_UPDATE_PROFILE)){
int counter = 1;
preparedStatement.setDate(counter++, date);
preparedStatement.setString(counter++, name);
preparedStatement.setString(counter++, secondName);
preparedStatement.setString(counter++, login);
preparedStatement.executeUpdate();
logger.info("setUserProfile complete");
} catch (SQLException e) {
logger.info("setUserProfile fails");
e.printStackTrace();
}
}
// savedPathInfo always be /dateOfBirth because user has not other dates in userDAO
public void updateDateParam(String userLogin, Date date, String savedPathInfo) {
logger.info("updateUserProfileParam has started");
savedPathInfo = savedPathInfo.substring(1);
logger.info("new param label: " + savedPathInfo);
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SQL_REQUEST_UPDATE_DOB)){
logger.info("preparing statement...");
int c = 1;
preparedStatement.setDate(c++, date);
preparedStatement.setString(c, userLogin);
logger.info("result statement is: " + preparedStatement);
int row = preparedStatement.executeUpdate();
logger.info("Was updated " + row + " rows, updating complete! ");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
125682a66ca1486de11b47bd3952d7b5610d24dd
|
Java
|
sebastiencaille/sky-lib
|
/testcase-writer/webapp/backend/src/main/java/ch/scaille/tcwriter/server/services/ContextService.java
|
UTF-8
| 396
| 1.773438
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package ch.scaille.tcwriter.server.services;
import ch.scaille.tcwriter.server.dto.Context;
import ch.scaille.tcwriter.server.dto.Identity;
import ch.scaille.util.helpers.JavaExt.AutoCloseableNoException;
public interface ContextService {
AutoCloseableNoException set(Context context);
Context get();
Context merge(Context newContext);
AutoCloseableNoException load(Identity of);
}
| true
|
11fdab974f251fc945c910f872138ac12280ef4f
|
Java
|
georgeguu/AOS_2
|
/parseFile_test.java
|
UTF-8
| 838
| 2.734375
| 3
|
[] |
no_license
|
import bin.Node;
import bin.Parseconfig;
public class parseFile_test {
private static int nodeId;
private static int portNum;
public static void main(String[] args){
if (args.length != 3) {
throw new IllegalArgumentException("Please enter port#, node ID and config file path");
}
portNum = Integer.parseInt(args[0]);
nodeId = Integer.parseInt(args[1]);
System.out.println("Port#= "+portNum);
System.out.println("nodeID= "+nodeId);
// Parse the config.txt
Parseconfig config = new Parseconfig(nodeId, args[2]);
// Print the configuration file
//config.loadConfig();
config.printConfig(nodeId);
//System.out.println("Number of nodes: "+ config.getNumOfNode());
}
}
| true
|
fe03f4b482ff22459365d11cfaa1ec4cbf4d97ec
|
Java
|
Ching-git/exp
|
/src/chapter9/Test953.java
|
UTF-8
| 303
| 2.828125
| 3
|
[] |
no_license
|
package chapter9;
class X {
Y b = new Y();
X(){
System.out.println("X");
}
}
class Y {
Y() {
System.out.println("Y");
}
}
public class Test953 extends X{
Y y = new Y();
public Test953() {
System.out.println("Z");
}
public static void main(String[] args) {
new Test953();
}
}
| true
|
76524871009a8f55ce4f15d734dfa65528b5276a
|
Java
|
TICUma/TIC2011-12
|
/practica 1/26973461/Fuente.java
|
UTF-8
| 8,106
| 2.890625
| 3
|
[] |
no_license
|
package practica1;
import java.sql.Time;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
public class Fuente {
private Alfabeto alfabeto;
private Random random = new Random(System.currentTimeMillis());
private static int BASE = 2;
// Redefinido
private List<Double> probabilidades;
public Fuente(Alfabeto alfabeto, List<?> probabilidades) {
this.alfabeto = alfabeto;
this.probabilidades = (List<Double>) probabilidades;
}
public Fuente(Alfabeto alfabeto) {
this.alfabeto = alfabeto;
}
/**
* Metodo que genera la lista de simbolosObject
* del alfabeto segun sus probabilidades
*
* @param numeroSimbolos
* @return
*/
public List<?> getSimbolos(int numeroSimbolos){
double prob = this.random.nextDouble();
double acum;
int j;
List<Object> res = new ArrayList<Object>();
for(int i=0;i<numeroSimbolos;i++){
prob = this.random.nextDouble();
j=0;
acum=0;
while(j<probabilidades.size() && acum<prob){
acum+=probabilidades.get(j);
j++;
}
res.add(alfabeto.get(j-1));
}
return res;
}
/**
* Metodo encargado de obtener un codebook binario
* segun Shanon
*
* @return
*/
public CodeBook getCodificacion(){
CodeBook res =new CodeBook();
int longitud;
Codigo generador;
String codigoCandidato;
for(int indice=0; indice<probabilidades.size(); indice++){
double probabilidad = probabilidades.get(indice);
longitud = minimaLongitud(probabilidad);
boolean encontrado = false;
while (!encontrado) {
generador = new Codigo(longitud);
while (!encontrado && generador.hasNext()) {
codigoCandidato = generador.next();
if (!tienePrefijos(codigoCandidato, res.codes())) {
// Añade el codigo
res.add(alfabeto.get(indice), codigoCandidato);
// Sale del bucle
encontrado = true;
}
}
longitud++;
}
}
return res;
}
/**
* Metodo encargado de obtener un codebook al
* alfabeto binario segun Huffman
*
* @param alfabetoDestino
* @return
*/
public CodeBook getOptimalCodificacion(){
CodeBook res =new CodeBook();
TreeMap<String, Double> arbol = new TreeMap<String, Double>();
LinkedList<TreeMap<String, Double>> lista = new LinkedList<TreeMap<String, Double>>();
Iterator<TreeMap<String, Double>> itArbol;
// Creo un arbol inicial
for(int i=0;i<this.alfabeto.size();i++){
String tmp="";
tmp+=this.alfabeto.get(i);
arbol.put(""+(this.alfabeto.get(i)),this.probabilidades.get(i));
}
TreeMap<String, Double> arbolNuevo;
while(arbol.size()!=1){
lista.addFirst(arbol);
arbolNuevo = new TreeMap<String, Double>();
arbolNuevo.putAll(arbol);
Entry<String, Double> minimo1 = minimaProbabilidad(arbolNuevo);
arbolNuevo.remove(minimo1.getKey());
Entry<String, Double> minimo2 = minimaProbabilidad(arbolNuevo);
arbolNuevo.remove(minimo2.getKey());
arbolNuevo.put(minimo1.getKey()+minimo2.getKey(),minimo1.getValue()+minimo2.getValue());
arbol = arbolNuevo;
}
// Al llegar aquí ya tengo el arbol construido. Como el paso 1.
// Ahora tengo que hacer el paso 2
TreeMap<String, String> arbolCod = new TreeMap<String, String>();
itArbol = lista.iterator();
while(itArbol.hasNext()){
arbolNuevo = itArbol.next();
for(Entry<String, Double> entrada : arbol.entrySet()){
int i=0;
while(i<entrada.getKey().length() && !arbolNuevo.containsKey(entrada.getKey().substring(0, i))){
i++;
}
if(arbolCod.containsKey(entrada.getKey())){
// Es un nodo que estaba en el arbol
Entry<String, String> entradaAntigua = arbolCod.ceilingEntry(entrada.getKey());
// Agrega el nodo izquierdo. Si tiene longitud y no estaba antes
if ((entradaAntigua.getKey().substring(0, i).length()>=1) && (!arbolCod.containsKey(entradaAntigua.getKey().substring(0, i)))){
arbolCod.put(entradaAntigua.getKey().substring(0, i), entradaAntigua.getValue()+"0");
}
// Agrega el nodo derecho. Si tiene longitud y no estaba antes
if ((entradaAntigua.getKey().substring(i).length()>=1) && (!arbolCod.containsKey(entradaAntigua.getKey().substring(i)))){
arbolCod.put(entradaAntigua.getKey().substring(i), entradaAntigua.getValue()+"1");
}
// Borra el nodo antiguo si es diferente de longitud 1
if (entradaAntigua.getKey().length()!=1){
arbolCod.remove(entradaAntigua.getKey());
}
// Por aquí solo vendría la primera vez
}else{
// Agrega el nodo izquierdo
arbolCod.put(entrada.getKey().substring(0, i), "0");
// Agrega el nodo derecho
arbolCod.put(entrada.getKey().substring(i), "1");
}
}
arbol=arbolNuevo;
}
for(Entry<String,String> c : arbolCod.entrySet()){
if (c.getKey().length() == 1) res.add(c.getKey().charAt(0), c.getValue());
}
return res;
}
/**
* Metodo encargado de devolver una lista de
* numSimbolos del alfabeto origen
* y sus correspondientes codificaciones binarias según Shannon-Fano.
*
* @param numSimbolos
* @return
*/
public SimbolosCodificados getSimbolosCodificados(int numSimbolos){
List<Character> cadenaACodificar = (List<Character>) this.getSimbolos(numSimbolos);
CodeBook codeBook = this.getCodificacion();
List<String> cadenaCodificada = new ArrayList<String>();
for (Character c : cadenaACodificar){
cadenaCodificada.add(codeBook.get(c));
}
SimbolosCodificados res = new SimbolosCodificados(cadenaACodificar,cadenaCodificada);
return res;
}
/**
* Metodo encargado de devolver una lista de
* numSimbolos del alfabeto origen
* y sus correspondientes codificaciones binarias en el
* alfabeto destino segun hufman
*
* @param numSimbolos
* @return
*/
public SimbolosCodificados getSimbolosCodificadosOptimos(int numSimbolos){
List<Character> cadenaACodificar = (List<Character>) this.getSimbolos(numSimbolos);
CodeBook codeBook = this.getOptimalCodificacion();
List<String> cadenaCodificada = new ArrayList<String>();
for (Character c : cadenaACodificar){
cadenaCodificada.add(codeBook.get(c));
}
SimbolosCodificados res = new SimbolosCodificados(cadenaACodificar,cadenaCodificada);
return res;
}
//======================metodos auxiliares===================
//====================get and set========================
public Alfabeto getAlfabeto() {
return alfabeto;
}
public void setAlfabeto(Alfabeto alfabeto) {
this.alfabeto = alfabeto;
}
public void setAlfabetoCodificacion(Alfabeto alfabeto) {
}
public List<?> getProbabilidades() {
return probabilidades;
}
public void setProbabilidades(List<?> probabilidades) {
}
/**
* @brief Devuelve la minima longitud que debe tener un codigo según una probabilidad, Se utiliza en Shanon Fano
* @param probabilidad la probabilidad
* @return El menor entero que cumple la reestricción
*/
private int minimaLongitud(double probabilidad){
double res = (Math.log10(1/probabilidad))/(Math.log10(BASE));
return ((int)Math.ceil(res));
}
/**
* @brief Devuelve cierto si alguna cadena del segundo parametro es prefijo de la primera
* @param codigo La cadena a la que se le buscan prefijos
* @param codigos Todos los codigos en los que se buscarán prefijos
* @return Cierto si existe algún prefijo, falso en caso contrario
*/
private boolean tienePrefijos(String codigo, List<String> codigos){
boolean res = false;
for(String cod : codigos){
if (cod.length()<= codigo.length()){
res = codigo.substring(0, cod.length()).compareTo(cod) == 0;
if (res) break;
}
}
return res;
}
private Entry<String,Double> minimaProbabilidad(TreeMap<String, Double> a){
Entry<String, Double> menor = null;
for(Entry<String, Double> entrada : a.entrySet()){
if((menor == null)||(menor.getValue()>=entrada.getValue())){
menor = a.ceilingEntry(entrada.getKey());
}
}
return menor;
}
}
| true
|
d874982b6159be6701477514018ad419c3ac5265
|
Java
|
patriziamartemucci/iisalberghetti
|
/Esempio_JSon_BSon_XML_dat/src/ScriviDAT.java
|
UTF-8
| 666
| 2.421875
| 2
|
[] |
no_license
|
import java.io.*;
public class ScriviDAT {
public static void main(String args[]){
int i;
try
{
FileOutputStream x=new FileOutputStream("vocabolario.dat");
ObjectOutputStream oos =new ObjectOutputStream(x);
DataObject[] dt=new DataObject[200000];
for (i=0; i<200000; i++) {
dt[i] = new DataObject (("rich"+Integer.toString(i)).getBytes(), ("risp"+Integer.toString(i)).getBytes());
}
oos.writeObject(dt);
oos.close();
x.close();
System.out.println("finito");
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
| true
|
a936c7eb8c530d5ae95f51fa38f4d3d89083a2c8
|
Java
|
2857944093/springboot-series
|
/springboot-designmode/src/main/java/com/czk/hope/designmode/factory/pizza/VeggiePizza.java
|
UTF-8
| 245
| 2.53125
| 3
|
[] |
no_license
|
package com.czk.hope.designmode.factory.pizza;
/**
* @Author: Created by ChenZK
* @Create: 2020/4/2 14:50
*/
public class VeggiePizza implements Product {
@Override
public void print() {
System.out.println("veggie");
}
}
| true
|
4180e0ca3d4e2d6bfa66205d1793efcb8b4d698b
|
Java
|
amolkinage/NPSTrackerAndroid
|
/app/src/main/java/com/example/amolkinage/myapp1/MainActivity.java
|
UTF-8
| 6,780
| 2.34375
| 2
|
[] |
no_license
|
package com.example.amolkinage.myapp1;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
class ReadNAVTask extends AsyncTask<Void, Void, NPSData> {
protected NPSData doInBackground(Void...param) {
NPSData npsDbHelper = MainActivity.npsDb;
try {
npsDbHelper.createDataBase();
npsDbHelper.openDataBase();
npsDbHelper.readDatabase();
}
catch (Exception ex)
{
npsDbHelper = null;
}
return npsDbHelper;
}
protected void onPreExecute(){
}
protected void onPostExecute(NPSData dbhelper){
mAdapter.notifyDataSetChanged();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
npsDb = new NPSData(this);
recyclerView = (RecyclerView) findViewById(R.id.portfolio_recycler_view);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
mAdapter = new PorfolioListAdapter();
recyclerView.setAdapter(mAdapter);
Toast toast = Toast.makeText(getApplicationContext(),"Loading Database and reading latest NAV",Toast.LENGTH_SHORT);
toast.show();
new ReadNAVTask().execute();
}
public class PorfolioListAdapter extends RecyclerView.Adapter<PorfolioListAdapter.PortfolioListViewHolder>
{
@Override
public int getItemCount()
{
return MainActivity.npsDb.Portfolios.size();
}
@Override
public void onBindViewHolder(PortfolioListViewHolder viewHolder,int i){
viewHolder.currentPortfolio = i;
Portfolio portfolio = MainActivity.npsDb.Portfolios.elementAt(i);
DecimalFormat format = new DecimalFormat("##,##,###.##");
if(portfolio.getMarketValue() >= portfolio.getAmountInvested())
{
viewHolder.vPortfolioMarketValue.setTextColor(Color.GREEN);
}
else
{
viewHolder.vPortfolioMarketValue.setTextColor(Color.RED);
}
if(portfolio.getCAGR() > 0)
viewHolder.vPortfolioCAGR.setTextColor(Color.GREEN);
else
viewHolder.vPortfolioCAGR.setTextColor(Color.RED);
if(portfolio.getGain() > 0)
viewHolder.vPortfolioAbsRet.setTextColor(Color.GREEN);
else
viewHolder.vPortfolioAbsRet.setTextColor(Color.RED);
viewHolder.vPortfolioName.setText(portfolio.getName());
viewHolder.vPortfolioMarketValue.setText(format.format(portfolio.getMarketValue()));
viewHolder.vPortfolioInvestValue.setText(format.format(portfolio.getAmountInvested()));
viewHolder.vPortfolioCAGR.setText(format.format(portfolio.getCAGR())+"%");
viewHolder.vPortfolioAbsRet.setText(format.format(portfolio.getGain())+"%");
}
@Override
public PortfolioListViewHolder onCreateViewHolder(ViewGroup viewGroup,int i){
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.content_main, viewGroup, false);
return new PortfolioListViewHolder(itemView);
}
public class PortfolioListViewHolder extends RecyclerView.ViewHolder{
protected TextView vPortfolioName;
protected TextView vPortfolioMarketValue;
protected TextView vPortfolioInvestValue;
protected TextView vPortfolioCAGR;
protected TextView vPortfolioAbsRet;
public int currentPortfolio;
public View view;
public PortfolioListViewHolder(View v)
{
super(v);
vPortfolioName = (TextView) v.findViewById(R.id.portfolio_name);
vPortfolioMarketValue = (TextView) v.findViewById(R.id.portfolio_marketvalue);
vPortfolioInvestValue = (TextView) v.findViewById(R.id.portfolio_investValue);
vPortfolioCAGR = (TextView) v.findViewById(R.id.portfolio_CAGR);
vPortfolioAbsRet = (TextView) v.findViewById(R.id.portfolio_absRet);
view = v;
view.setOnClickListener(new View.OnClickListener(){
@Override public void onClick(View v){
Intent intent = new Intent(view.getContext(),SchemeList.class);
intent.putExtra("Portfolio",currentPortfolio);
startActivity(intent);
}
});
}
}
}
@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_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
@Override
public void onBackPressed() {
super.onBackPressed();
npsDb.saveDatabase();
npsDb.close();
}
public Portfolio getPortfolio(int position)
{
return npsDb.Portfolios.elementAt(position);
}
public static NPSData npsDb=null;
}
| true
|
045b1797cbde84efab29a7c559d2c16b7f67d731
|
Java
|
G-Impacta/ProjetoFinal-ED
|
/Projeto_Final_ED/src/TADS/TAD_Fila_Prioridade/TAD_Fila_Prioridade/Interfaces/PriorityQueue.java
|
ISO-8859-1
| 987
| 3.1875
| 3
|
[] |
no_license
|
package TADS.TAD_Fila_Prioridade.TAD_Fila_Prioridade.Interfaces;
import TADS.TAD_Fila_Prioridade.TAD_Fila_Prioridade.Excecoes.EmptyPriorityQueueException;
import TADS.TAD_Fila_Prioridade.TAD_Fila_Prioridade.Excecoes.InvalidKeyException;
//Interface para o TAD FILA DE PRIORIDADE.
public interface PriorityQueue<KEY, VALUE> {
//Retorna um inteiro com a quantidade de elementos contidos na FILA DE PRIORIDADE.
public int size();
//Retorna um valor booleano representando o status da FILA DE PRIORIDADE => True=Vazia, False=No Vazia.
public boolean isEmpty();
//Retorna uma entrada com a menor chave, sem remove-la.
public Entry<KEY, VALUE> min() throws EmptyPriorityQueueException;
//Adiciona uma entrada(key, value) e retorna a entrada criada.
public Entry<KEY, VALUE> insert(KEY key, VALUE value) throws InvalidKeyException;
//Remove e retorna uma entrada(key, value) com a menor chave.
public Entry<KEY, VALUE> removeMin() throws EmptyPriorityQueueException;
}
| true
|
d06538d3a87c51948117cbc608b26a43ada17116
|
Java
|
mestatrit/yinpingyong
|
/Rycs/Implement/Fmis/src/org/sunside/rycs/repository/model/cust/CusTax.java
|
UTF-8
| 8,568
| 2.1875
| 2
|
[] |
no_license
|
package org.sunside.rycs.repository.model.cust;
public class CusTax {
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private Integer id;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.cus_id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private Long cusId;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String name;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.register_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String registerNo;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.computer_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String computerNo;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.pay_type
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String payType;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.manager_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String managerName;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.dept_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String deptName;
/**
* This field was generated by Apache iBATIS ibator.
* This field corresponds to the database column cus_tax.telphone
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
private String telphone;
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.id
*
* @return the value of cus_tax.id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public Integer getId() {
return id;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.id
*
* @param id the value for cus_tax.id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.cus_id
*
* @return the value of cus_tax.cus_id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public Long getCusId() {
return cusId;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.cus_id
*
* @param cusId the value for cus_tax.cus_id
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setCusId(Long cusId) {
this.cusId = cusId;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.name
*
* @return the value of cus_tax.name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getName() {
return name;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.name
*
* @param name the value for cus_tax.name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setName(String name) {
this.name = name;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.register_no
*
* @return the value of cus_tax.register_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getRegisterNo() {
return registerNo;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.register_no
*
* @param registerNo the value for cus_tax.register_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setRegisterNo(String registerNo) {
this.registerNo = registerNo;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.computer_no
*
* @return the value of cus_tax.computer_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getComputerNo() {
return computerNo;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.computer_no
*
* @param computerNo the value for cus_tax.computer_no
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setComputerNo(String computerNo) {
this.computerNo = computerNo;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.pay_type
*
* @return the value of cus_tax.pay_type
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getPayType() {
return payType;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.pay_type
*
* @param payType the value for cus_tax.pay_type
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setPayType(String payType) {
this.payType = payType;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.manager_name
*
* @return the value of cus_tax.manager_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getManagerName() {
return managerName;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.manager_name
*
* @param managerName the value for cus_tax.manager_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setManagerName(String managerName) {
this.managerName = managerName;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.dept_name
*
* @return the value of cus_tax.dept_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getDeptName() {
return deptName;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.dept_name
*
* @param deptName the value for cus_tax.dept_name
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setDeptName(String deptName) {
this.deptName = deptName;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method returns the value of the database column cus_tax.telphone
*
* @return the value of cus_tax.telphone
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public String getTelphone() {
return telphone;
}
/**
* This method was generated by Apache iBATIS ibator.
* This method sets the value of the database column cus_tax.telphone
*
* @param telphone the value for cus_tax.telphone
*
* @ibatorgenerated Thu Sep 20 01:29:51 CST 2012
*/
public void setTelphone(String telphone) {
this.telphone = telphone;
}
}
| true
|
d82b55f6477bdddceafe51e298667a147961be6f
|
Java
|
miths1108/PiGen
|
/codd-data-gen/srcT2/in/ac/iisc/cds/dsl/cdgvendor/model/formal/FormalConditionSimpleJoin.java
|
UTF-8
| 1,321
| 2.21875
| 2
|
[] |
no_license
|
package in.ac.iisc.cds.dsl.cdgvendor.model.formal;
public class FormalConditionSimpleJoin extends FormalConditionSimple {
protected String columnname2;
public FormalConditionSimpleJoin(String columnname, String columnname2) {
super(columnname, Symbol.EQ.symbolString);
if (columnname2.contains(DOT)) {
columnname2 = columnname2.split(SPLITTER)[1];
}
this.columnname2 = columnname2;
}
public String getColumnname2() {
return columnname2;
}
public void setColumnname2(String columnname2) {
this.columnname2 = columnname2;
}
@Override
public String asString() {
return super.asString() + " " + columnname2;
}
@Override
public String asQueryString() {
throw new RuntimeException("Not Implemented");
}
public void updateColumnnames(String columnname, String columnname2) {
this.columnname = columnname;
this.columnname2 = columnname2;
}
@Override
public FormalConditionSimpleJoin getDeepCopy() {
FormalConditionSimpleJoin another = new FormalConditionSimpleJoin(columnname, columnname2);
another.outputCardinality = outputCardinality;
another.viewname = viewname;
//another.colPath = colPath;
return another;
}
}
| true
|
099fc725bb9da04bfa043fe4b23f19b824bb1fad
|
Java
|
YashRTiwari/LeetCode
|
/LeetCode/src/Verkada/S.java
|
UTF-8
| 4,965
| 3
| 3
|
[] |
no_license
|
package Verkada;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class S {
static int[] vehicleDetection(int[][] input) {
List<Integer> answer = Arrays.stream(input[0])
.boxed()
.collect(Collectors.toList());
int size = input.length - 1;
while(size !=-1){
List<Integer> temp = Arrays.stream(input[size])
.boxed()
.collect(Collectors.toList());
answer.retainAll(temp);
size = size - 1;
}
int[] an = new int[answer.size()];
for (int i = 0; i < an.length; i++) {
an[i] = answer.get(i);
}
return an;
}
static ArrayList<Integer> ne (int i, int j, int [][]image){
ArrayList<Integer> array = new ArrayList<Integer>();
// i-1, j-1
if(i-1 < 0 ){
} else {
if(j-1 < 0){
} else {
array.add(image[i-1][j-1]);
}
}
// i-1, j+1
if(i-1 < 0 ){
} else{
if(j+1 < image[0].length) {
array.add(image[i - 1][j + 1]);
}
}
// i-1, j
if(i-1 < 0 ){
} else{
array.add(image[i-1][j]);
}
// i,j-1
if(j - 1 <0){
} else {
array.add(image[i][j-1]);
}
// i, j+1
if(j+1 < image[0].length){
array.add(image[i][j+1]);
}
// i+1, j-1
if(i+1 < image.length){
if(j-1 < 0){
} else {
array.add(image[i+1][j-1]);
}
}
// i+1, j
if(i+1 < image.length){
array.add(image[i+1][j]);
}
if(i+1 < image.length){
if (j+1 < image.length){
array.add(image[i+1][j+1]);
}
}
return array;
}
private static double average(ArrayList<Integer> list){
double avg = 0;
for(int item : list){
avg += item;
}
return avg/list.size();
}
double[][] blurFaces(int[][] image) {
double [][] answer = new double[image.length][image[0].length];
for (int i = 0; i< image.length; i++){
for (int j=0; j<image[0].length; j++){
ArrayList<Integer> n = ne(i,j,image);
double avg = average(n);
answer[i][j] = avg;
}
}
return answer;
}
public static void main(String [] args){
// int [][] a = {{1,3,4,8,9,16,32,40},
// {0,1,6,7,8,12,40,62}};
// //double [][] answer = new double[a.length][a[0].length];
//
// double [][] answer = new double[a.length][a[0].length];
//
// for (int i = 0; i< a.length; i++){
// for (int j=0; j<a[0].length; j++){
// ArrayList<Integer> n = ne(i,j,a);
// double avg = average(n);
// answer[i][j] = avg;
// }
//
// }
//
// for (int k = 0; k< a.length; k++){
// for (int q=0; q<a[0].length; q++){
// System.out.print(answer[k][q]+" ");
// }
// System.out.println("");
//
// }
//System.out.println(vehicleDetection(a));
ArrayList<String> r = a2("19216855");
System.out.println(r);
}
static ArrayList<String> a2(String q){
System.out.println(q);
ArrayList<String> answer = new ArrayList<>();
int ioffset = 1;
while(ioffset < 4 && ioffset<q.length()){
int first = Integer.parseInt(q.substring(0,ioffset));
if(first > 255){
break;
}
int joffset = ioffset + 1;
while(joffset < ioffset + 4 && joffset < q.length()){
int second = Integer.parseInt(q.substring(ioffset,joffset));
if(second > 255){
break;
}
int koffset = joffset + 1;
while(koffset < joffset + 4 && koffset < q.length()){
int third = Integer.parseInt(q.substring(joffset,koffset));
if(third > 255){
break;
}
if(!q.substring(koffset, q.length()).equals("")) {
int fourth = Integer.parseInt(q.substring(koffset, q.length()));
String oIp = first + "" + second + "" + third + "" + fourth;
if (fourth < 256 && oIp.length() == q.length()) {
answer.add(first + "." + second + "." + third + "." + fourth);
}
}
koffset++;
}
joffset++;
}
ioffset++;
}
return answer;
}
}
| true
|
3bbcfc3bcb8ad5e0d053798cef04724cd376a502
|
Java
|
AmandaBonassoli/GradeAcademicProject
|
/src/br/com/gradeacademic/entidade/Estado.java
|
UTF-8
| 779
| 2.359375
| 2
|
[] |
no_license
|
package br.com.gradeacademic.entidade;
public class Estado {
private int id;
private String descricao;
private String sigla;
private String pais;
private int situacao;
public int getId() {
return id;
}
public void setId(int Id) {
this.id = Id;
}
public String getDescricao(){
return descricao;
}
public void setDescricao(String Descricao){
this.descricao = Descricao;
}
public String getSigla(){
return sigla;
}
public void setSigla(String Sigla){
this.sigla = Sigla;
}
public String getPais(){
return pais;
}
public void setPais(String Pais){
this.pais = Pais;
}
public int getSituacao() {
return situacao;
}
public void setSituacao(int Situacao) {
this.situacao = Situacao;
}
}
| true
|
d45dd989b76587fd5db855a7bfc8ed150b0698bc
|
Java
|
nillk/algorithm
|
/src/java/Q2511_Card.java
|
UTF-8
| 700
| 3.65625
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class Q2511_Card {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] cardA = scan.nextLine().split(" ");
String[] cardB = scan.nextLine().split(" ");
char lastWinner = 'D';
byte scoreA = 0;
byte scoreB = 0;
for (byte i = 0; i < 10; i++) {
if (cardA[i].equals(cardB[i])) {
scoreA++;
scoreB++;
} else if (cardA[i].compareTo(cardB[i]) > 0) {
scoreA += 3;
lastWinner = 'A';
} else {
scoreB += 3;
lastWinner = 'B';
}
}
char winner = scoreA == scoreB ? lastWinner : scoreA > scoreB ? 'A' : 'B';
System.out.printf("%d %d\n%c", scoreA, scoreB, winner);
scan.close();
}
}
| true
|
d416f0238c6181948ba2d6be8fb58494b70d8f58
|
Java
|
hjetti/MakingAProjectIntoLibrary
|
/SampleImport/app/src/main/java/com/vidya_vivaswanth/sampleimport/MainActivity.java
|
UTF-8
| 793
| 1.921875
| 2
|
[
"MIT"
] |
permissive
|
package com.vidya_vivaswanth.sampleimport;
import android.content.ComponentName;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import static java.lang.Class.forName;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void move(View view)
{
try {
Intent intent = new Intent(MainActivity.this, Class.forName("com.example.googlemapssearchnearby.MapsActivity"));
startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| true
|
25099524bf4732c249685762f04009a850398ccf
|
Java
|
bqw18744018044/DesignPattern
|
/src/com/bqw/Adapter/Twoway/TwoWayTarget.java
|
UTF-8
| 94
| 1.859375
| 2
|
[] |
no_license
|
package com.bqw.Adapter.Twoway;
public interface TwoWayTarget {
public void request();
}
| true
|
0cba857e4bd6e55a01de6838a05ed8e1fee5a686
|
Java
|
enGeneus/BoredWeekend
|
/boredWeekendService/src/main/java/it/univaq/disim/sose/boredweekend/boredweekendservice/webservice/BoredWeekendRestService.java
|
UTF-8
| 2,243
| 2.25
| 2
|
[] |
no_license
|
package it.univaq.disim.sose.boredweekend.boredweekendservice.webservice;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import it.univaq.disim.sose.boredweekend.boredweekendservice.controller.BoredWeekendProsumerCore;
import it.univaq.disim.sose.boredweekend.boredweekendservice.model.Activity;
import it.univaq.disim.sose.boredweekend.boredweekendservice.model.Event;
import it.univaq.disim.sose.boredweekend.boredweekendservice.model.Weekend;
import it.univaq.disim.sose.boredweekend.boredweekendservice.util.DateUtils;
@Service
public class BoredWeekendRestService {
private static final Logger LOGGER = LoggerFactory.getLogger(BoredWeekendRestService.class);
@Autowired
BoredWeekendProsumerCore prosumerCore;
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/getWeekends")
public Weekend getWeekends(@QueryParam("where") String city, @QueryParam("start") String start,
@QueryParam("end") String end, @QueryParam("preferences") String preferences, @QueryParam("traveldistance") int distance) {
LOGGER.info("Received getWeekends request");
Date startDate = DateUtils.getDateFromString(start, "yyy-MM-dd");
Date endDate = DateUtils.getDateFromString(end + "T23:59:59", "yyy-MM-dd'T'hh:mm:ss");
String[] values = preferences.split(",");
List<String> preferencesList = Arrays.asList(values);
Weekend weekend = prosumerCore.buildWeekend(city, startDate, endDate, preferencesList, distance);
return weekend;
}
@POST
@Path("/insertActivity")
@Consumes(MediaType.APPLICATION_JSON)
public void insert(Activity activity) {
LOGGER.info("Received insertActivity request");
prosumerCore.insertActivity(activity);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/insertEvent")
public void insert(Event event) {
LOGGER.info("Received insertEvent request");
prosumerCore.insertEvent(event);
}
}
| true
|
7f4020b7246a166d80426069c12cb8e56d9deef8
|
Java
|
m-assili/dev-isimg
|
/2021_2022/POO_Java/TP2/EX4/Facture.java
|
UTF-8
| 867
| 3.015625
| 3
|
[] |
no_license
|
package ex4;
import java.util.Calendar;
import java.util.Date;
public class Facture {
private static long numero=0;
private Date dateFacturation;
private LigneFacture lignes[];
private int nbLigne;
public Facture(){
numero++;
dateFacturation = Calendar.getInstance().getTime();
lignes = new LigneFacture[5000];
nbLigne = 0;
}
public void ajouterAchat(LigneFacture ligneFacture){
lignes[nbLigne++]=ligneFacture;
}
public void afficher()
{
for (LigneFacture l:lignes ) {
if(l!=null)
System.out.println(l.toString());
}
}
public double montant(){
double montant=0;
for (LigneFacture lig:lignes)
if(lig!=null)
montant+=lig.getArticle().getPrix();
return montant;
}
}
| true
|
557b28219e39041b0f878c09eb41bb422d5c97ba
|
Java
|
WorstCase00/GitHubPaper
|
/paper/src/main/java/edu/bocmst/scheduling/mrcpspmax/bmap/ga/repair/BarriosModeAssignmentRepair.java
|
UTF-8
| 1,575
| 2.25
| 2
|
[] |
no_license
|
package edu.bocmst.scheduling.mrcpspmax.bmap.ga.repair;
import java.util.List;
import java.util.Random;
import org.uncommons.watchmaker.framework.EvolutionaryOperator;
import org.uncommons.watchmaker.framework.operators.EvolutionPipeline;
import com.google.common.collect.Lists;
import edu.bocmst.scheduling.mrcpspmax.candidate.modeassignment.IModeAssignment;
import edu.bocmst.scheduling.mrcpspmax.instance.IMrcpspMaxInstance;
public class BarriosModeAssignmentRepair implements EvolutionaryOperator<IModeAssignment> {
private final EvolutionPipeline<IModeAssignment> repairs;
protected BarriosModeAssignmentRepair(EvolutionPipeline<IModeAssignment> repairs) {
super();
this.repairs = repairs;
}
@Override
public List<IModeAssignment> apply(
List<IModeAssignment> selectedCandidates,
Random rng) {
return repairs.apply(selectedCandidates, rng);
}
public static BarriosModeAssignmentRepair createInstance(IMrcpspMaxInstance instance) {
EvolutionaryOperator<IModeAssignment> resourceRepair = new BarriosModeAssignmentResourceRepair(instance);
EvolutionaryOperator<IModeAssignment> cycleRepair = new BarriosModeAssignmentCycleRepair(instance);
@SuppressWarnings("unchecked")
List<EvolutionaryOperator<IModeAssignment>> operators = Lists.newArrayList(
resourceRepair,
cycleRepair);
EvolutionPipeline<IModeAssignment> pipeline = new EvolutionPipeline<IModeAssignment>(operators);
BarriosModeAssignmentRepair operator = new BarriosModeAssignmentRepair(pipeline);
return operator;
}
}
| true
|
1d6d96352e573cf4676cd02c8b715845c8f49c12
|
Java
|
vmatyusGitHub/cloudant-java-sdk
|
/modules/cloudant/src/main/java/com/ibm/cloud/cloudant/v1/model/ActiveTask.java
|
UTF-8
| 2,972
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* (C) Copyright IBM Corp. 2020.
*
* 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 com.ibm.cloud.cloudant.v1.model;
import com.google.gson.annotations.SerializedName;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* Schema for information about a running task.
*/
public class ActiveTask extends GenericModel {
@SerializedName("changes_done")
protected Long changesDone;
protected String database;
protected String node;
protected String pid;
protected Long progress;
@SerializedName("started_on")
protected Long startedOn;
protected String status;
protected String task;
@SerializedName("total_changes")
protected Long totalChanges;
protected String type;
@SerializedName("updated_on")
protected Long updatedOn;
/**
* Gets the changesDone.
*
* Processed changes.
*
* @return the changesDone
*/
public Long getChangesDone() {
return changesDone;
}
/**
* Gets the database.
*
* Source database.
*
* @return the database
*/
public String getDatabase() {
return database;
}
/**
* Gets the node.
*
* Cluster node where the task is running.
*
* @return the node
*/
public String getNode() {
return node;
}
/**
* Gets the pid.
*
* Process ID.
*
* @return the pid
*/
public String getPid() {
return pid;
}
/**
* Gets the progress.
*
* Current percentage progress.
*
* @return the progress
*/
public Long getProgress() {
return progress;
}
/**
* Gets the startedOn.
*
* Schema for a Unix epoch timestamp.
*
* @return the startedOn
*/
public Long getStartedOn() {
return startedOn;
}
/**
* Gets the status.
*
* Task status message.
*
* @return the status
*/
public String getStatus() {
return status;
}
/**
* Gets the task.
*
* Task name.
*
* @return the task
*/
public String getTask() {
return task;
}
/**
* Gets the totalChanges.
*
* Total changes to process.
*
* @return the totalChanges
*/
public Long getTotalChanges() {
return totalChanges;
}
/**
* Gets the type.
*
* Operation type.
*
* @return the type
*/
public String getType() {
return type;
}
/**
* Gets the updatedOn.
*
* Schema for a Unix epoch timestamp.
*
* @return the updatedOn
*/
public Long getUpdatedOn() {
return updatedOn;
}
}
| true
|
517416c12ed327db341d569f80644c2ffbb51a48
|
Java
|
SubhashPavuskar/javapractice
|
/src/com/tecnotree/home/practice/string/SortingValue.java
|
UTF-8
| 1,009
| 3.5
| 4
|
[] |
no_license
|
package com.tecnotree.home.practice.string;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortingValue
{
public static void main(String[] args)
{
int[] intArray = {10,12,9,4,1,5,6,23,43};
System.out.println("Before Sort Integer:: "+Arrays.toString(intArray));
Arrays.sort(intArray);
System.out.println("After Sort Integer:: "+ Arrays.toString(intArray));
String[] charArray = {"A","C","E","D","B","F","G"};
System.out.println("Before Sorting Char:: "+Arrays.toString(charArray));
Arrays.sort(charArray);
System.out.println("After Sorting Char::"+Arrays.toString(charArray));
List<String> list = new ArrayList<String>();
list.add("1");
list.add("18");
list.add("4");
list.add("16");
list.add("15");
list.add("12");
list.add("10");
list.add("11");
System.out.println("List Item Before Sorting::"+list);
Collections.sort(list);
System.out.println("List Item After Sorting::"+list);
}
}
| true
|
6fb8e73ac7cfb069b8d110d64f2688648691d6a5
|
Java
|
ZakiaSalod/futurehack
|
/pip-backend-api/src/main/java/online/weoutchea/pip/repository/JobShadowRepository.java
|
UTF-8
| 557
| 1.960938
| 2
|
[] |
no_license
|
package online.weoutchea.pip.repository;
import online.weoutchea.pip.domain.JobShadow;
import org.springframework.stereotype.Repository;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the JobShadow entity.
*/
@SuppressWarnings("unused")
@Repository
public interface JobShadowRepository extends JpaRepository<JobShadow, Long> {
@Query("select job_shadow from JobShadow job_shadow where job_shadow.user.login = ?#{principal.username}")
List<JobShadow> findByUserIsCurrentUser();
}
| true
|
600230e275e85e0258d415afbb7c118673a03d11
|
Java
|
piyush170889/komalsteel_corporation
|
/komalsteelcorporation/src/main/java/co/in/replete/komalindustries/beans/entity/AppConfiguration.java
|
UTF-8
| 1,744
| 2.0625
| 2
|
[] |
no_license
|
package co.in.replete.komalindustries.beans.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
/**
* The persistent class for the configuration database table.
*
*/
@Entity
@Table(name="configuration")
public class AppConfiguration implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7998707340213408502L;
@Id
@Column(name="CONFIG_NAME")
private String configName;
@NotNull(message="error.servicetax.required")
@NotEmpty(message="error.servicetax.required")
@Column(name="CONFIG_VAL")
private String configVal;
@Column(name="CONFIG_DESC")
private String configDesc;
@Column(name="CRAETED_TS")
private Date createdTs;
@Column(name="MODIFIED_TS")
private Date modifiedTs;
public AppConfiguration(){}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public String getConfigVal() {
return configVal;
}
public void setConfigVal(String configVal) {
this.configVal = configVal;
}
public String getConfigDesc() {
return configDesc;
}
public void setConfigDesc(String configDesc) {
this.configDesc = configDesc;
}
public Date getCreatedTs() {
return createdTs;
}
public void setCreatedTs(Date createdTs) {
this.createdTs = createdTs;
}
public Date getModifiedTs() {
return modifiedTs;
}
public void setModifiedTs(Date modifiedTs) {
this.modifiedTs = modifiedTs;
}
}
| true
|
1ef461dd426ac389cb0e2678069501351e127069
|
Java
|
hyungtaik/AlgorithmStudy
|
/AlgorithmStudy/src/baekjoonA/boj_5014.java
|
UHC
| 2,147
| 3.484375
| 3
|
[] |
no_license
|
package baekjoonA;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
/**
*
* @author TAEK
* @category BFS
*
* @see 5014: ŸƮũ <br>
* : 53832 KB <br>
* ð: 172 ms
* @since 2020-08-26
*
*/
public class boj_5014 {
private static int F;
private static int S;
private static int G;
private static int U;
private static int D;
private static boolean[] checked;
private static LinkedList<Integer> list;
public static void main(String[] args) throws Exception{
// F ǹ - ŸƮũ G
// ȣ S -> G
// U , D ư - شϴ ̵ x
// ư ּ G ϴ - ٸ use the stairs
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String[] FSGUD = input.split(" ");
F = Integer.parseInt(FSGUD[0]);
S = Integer.parseInt(FSGUD[1]);
G = Integer.parseInt(FSGUD[2]);
U = Integer.parseInt(FSGUD[3]);
D = Integer.parseInt(FSGUD[4]);
checked = new boolean[F+1];
checked[0] = true;
checked[S] = true;
list = new LinkedList<Integer>();
list.add(S);
int count = 0;
boolean check = false;
if(S == G) {
System.out.println(count);
}else {
L:while(!list.isEmpty()) {
int len = list.size();
count++;
for(int i=0;i<len;i++) {
int temp = list.poll();
checked[temp] = true;
int upTemp = temp + U;
if(upTemp == G) {
check = true;
break L;
}else if(upTemp <F && !checked[upTemp]) {
list.add(upTemp);
checked[upTemp] = true;
}
int downTemp = temp - D;
if(downTemp == G) {
check = true;
break L;
}else if(downTemp > 0 && !checked[downTemp]) {
list.add(downTemp);
checked[downTemp] = true;
}
}
}
if(check) {
System.out.println(count);
}else {
System.out.println("use the stairs");
}
}
}
}
| true
|
2e0bb6e41df3b9308901d868313c8fb3320f5f27
|
Java
|
daihanhbvt/javasach
|
/src/bean/ChiTietHoaDonBean.java
|
UTF-8
| 959
| 2.34375
| 2
|
[] |
no_license
|
package bean;
public class ChiTietHoaDonBean {
private String maChiTietHoaDon;
private String maSach;
private long soLuongMua;
private String maHoaDon;
public ChiTietHoaDonBean(String maChiTietHoaDon, String maSach, long soLuongMua, String maHoaDon) {
super();
this.maChiTietHoaDon = maChiTietHoaDon;
this.maSach = maSach;
this.soLuongMua = soLuongMua;
this.maHoaDon = maHoaDon;
}
public String getMaChiTietHoaDon() {
return maChiTietHoaDon;
}
public void setMaChiTietHoaDon(String maChiTietHoaDon) {
this.maChiTietHoaDon = maChiTietHoaDon;
}
public String getMaSach() {
return maSach;
}
public void setMaSach(String maSach) {
this.maSach = maSach;
}
public long getSoLuongMua() {
return soLuongMua;
}
public void setSoLuongMua(long soLuongMua) {
this.soLuongMua = soLuongMua;
}
public String getMaHoaDon() {
return maHoaDon;
}
public void setMaHoaDon(String maHoaDon) {
this.maHoaDon = maHoaDon;
}
}
| true
|
9e40a74901a4641f15197eab424a7e39cfdc68b1
|
Java
|
leoaug/MozartModel
|
/ejbModule/com/mozart/model/ejb/entity/UsuarioPontoVendaEJBPK.java
|
UTF-8
| 1,415
| 2.40625
| 2
|
[] |
no_license
|
package com.mozart.model.ejb.entity;
import java.io.Serializable;
import javax.persistence.*;
/**
* The primary key class for the USUARIO_PONTO_VENDA database table.
*
*/
@Embeddable
public class UsuarioPontoVendaEJBPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="ID_USUARIO")
private long idUsuario;
@Column(name="ID_PONTO_VENDA")
private long idPontoVenda;
public UsuarioPontoVendaEJBPK() {
}
public long getIdUsuario() {
return this.idUsuario;
}
public void setIdUsuario(long idUsuario) {
this.idUsuario = idUsuario;
}
public long getIdPontoVenda() {
return this.idPontoVenda;
}
public void setIdPontoVenda(long idPontoVenda) {
this.idPontoVenda = idPontoVenda;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof UsuarioPontoVendaEJBPK)) {
return false;
}
UsuarioPontoVendaEJBPK castOther = (UsuarioPontoVendaEJBPK)other;
return
(this.idUsuario == castOther.getIdUsuario())
&& (this.idPontoVenda == castOther.getIdPontoVenda());
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + ((int) (this.idUsuario ^ (this.idUsuario >>> 32)));
hash = hash * prime + ((int) (this.idPontoVenda ^ (this.idPontoVenda >>> 32)));
return hash;
}
}
| true
|
7faf8bfe993b675d2b1100f028553e2bdeeade6c
|
Java
|
aalnct/walker-dev
|
/src/main/test/com/application/walker/controller/WalkerControllerTest.java
|
UTF-8
| 3,943
| 2.375
| 2
|
[] |
no_license
|
package com.application.walker.controller;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.servlet.ModelAndView;
import com.application.walker.service.Address;
import com.application.walker.service.Coach;
import com.application.walker.service.User;
import com.application.walker.service.WalkerCalculation;
import com.application.walker.service.WalkerService;
@RunWith(MockitoJUnitRunner.class)
public class WalkerControllerTest {
@Mock
HttpServletRequest httpServletRequest;
@InjectMocks
WalkerController walkerController;
@Mock
WalkerService walkerService;
@Mock
WalkerCalculation walkerCalculation;
User user = new User();
Address address = new Address();
Coach coach = new Coach();
com.application.walker.service.health health = new com.application.walker.service.health();
@Before
public void setUp() throws Exception {
}
@Test
public void registerUserTest() {
Mockito.when(httpServletRequest.getParameter("list_state_india")).thenReturn("list_state_india");
Mockito.when(httpServletRequest.getParameter("zip")).thenReturn("30338");
ModelAndView model = walkerController.registerUser(httpServletRequest);
assertEquals("registrationSuccessfull", model.getViewName());
}
@Test
public void deleteuserTest() throws Exception{
int id = 0;
String message = walkerController.deleteuser(id, user);
assertEquals("user information is deleted", message);
}
@Test
public void calculateBMITest(){
int age = 11;
Double height = 180.0;
float weight = 80;
Mockito.when(walkerCalculation.bmiCalculation(age, height, weight)).thenReturn(0.24);
String aString = walkerController.calculateBMI(age, height, weight);
assertEquals("0.24",aString);
}
@Test
public void saveBMIUserTest(){
int id = 0;
int age = 11;
Double height = 180D;
float weight = 80f;
float bmi = 0.24f;
Mockito.when(walkerService.saveBMIService(health)).thenReturn("user health information is saved");
String message = walkerController.saveBMIUser(httpServletRequest, id, age, height, weight, bmi);
assertEquals("User Information is saved :)",message);
}
@Test
public void saveCoachInformationTest(){
String name = "Andrew";
String coachEmailId = "andrew@gmail.com";
String description = "Coach";
Mockito.when(walkerService.saveCoachInformation(name, coachEmailId, description)).thenReturn("Successfully saved information");
String message = walkerController.saveCoachInformation(name, coachEmailId, description);
assertEquals("user information is saved", message);
}
@Test
public void getCoachListTest(){
String coachTest = null;
List<String> coachList= new ArrayList<String>();
coachList.add("Andrew");
Mockito.when(walkerService.getAllCoach()).thenReturn(coachList);
coachTest = walkerController.getCoachList();
assertEquals(coachList.toString(), coachTest);
}
@Test
public void assignCoachtoUserTest(){
String coachName = "Andrew";
String coachEmail = "andrew@gmail.com";
String userEmail = "aalnct@gmail.com";
String userName = "aalnct";
String response = walkerService.assignCoachtoUser(coachName, coachEmail, userName, userEmail);
assertEquals(response,walkerController.assignCoachtoUser(coachName,coachEmail,userEmail,userName));
}
@Test
public void retrieveUserInformationTest(){
Integer id = 5;
Mockito.when(walkerService.retrieveUserInformationForUpdate(id)).thenReturn(user);
user = walkerService.retrieveUserInformationForUpdate(id);
assertEquals(user.toString(), walkerController.retrieveUserInformation(id));
}
@Test
public void saveStudentTest(){
}
}
| true
|
673d226864af5b56471a7a3d466b9bddecd08cbb
|
Java
|
jhompe14/back-libroDeOro
|
/src/main/java/com/scouts/backlibrodeoro/validator/impl/RamaValidator.java
|
UTF-8
| 2,557
| 2.484375
| 2
|
[] |
no_license
|
package com.scouts.backlibrodeoro.validator.impl;
import com.scouts.backlibrodeoro.validator.IValidator;
import com.scouts.backlibrodeoro.exception.NegocioException;
import com.scouts.backlibrodeoro.model.Rama;
import com.scouts.backlibrodeoro.types.TypeException;
import com.scouts.backlibrodeoro.util.GeneralValidates;
import com.scouts.backlibrodeoro.util.MessagesValidation;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class RamaValidator implements IValidator {
@Override
public <T> void validator(T rama) throws NegocioException {
Rama ramaValidation = (Rama) rama;
StringBuilder strValidation = new StringBuilder();
validateRequired(strValidation, ramaValidation);
if(!strValidation.toString().isEmpty()){
throw new NegocioException(MessagesValidation.VALIDATION_TODOS_CAMPOS_OBLIGATORIOS+"</br>"+
strValidation.toString(),
TypeException.VALIDATION);
}
if(!validateEdadMaximaMinima(ramaValidation)){
throw new NegocioException(MessagesValidation.VALIDATION_EDAD_MINIMA_MAXIMA, TypeException.VALIDATION);
}
if(!validateEdadMaximaMajorToEdadMinima(ramaValidation)){
throw new NegocioException(MessagesValidation.VALIDATION_EDAD_MAXIMA_MAJOR_EDAD_MINIMA, TypeException.VALIDATION);
}
}
private void validateRequired(StringBuilder strValidation, Rama ramaValidate){
Optional.ofNullable(ramaValidate).map(r ->{
if(!GeneralValidates.validateStringNotIsEmpty(r.getNombre())){
strValidation.append(MessagesValidation.VALIDATION_NOMBRE_OBLIGATORIO).append(" </br>");
}
if(!Optional.ofNullable(r.getEdadMinima()).isPresent()){
strValidation.append(MessagesValidation.VALIDATION_RAMA_EDAD_MINIMA).append(" </br>");
}
if(!Optional.ofNullable(r.getEdadMaxima()).isPresent()){
strValidation.append(MessagesValidation.VALIDATION_RAMA_EDAD_MAXIMA).append(" </br>");
}
return r;
});
}
private boolean validateEdadMaximaMinima(Rama ramaValidate){
return ramaValidate.getEdadMinima() > 0 && ramaValidate.getEdadMinima() < 200 &&
ramaValidate.getEdadMaxima() > 0 && ramaValidate.getEdadMaxima() < 200;
}
private boolean validateEdadMaximaMajorToEdadMinima(Rama ramaValidate){
return ramaValidate.getEdadMaxima() >= ramaValidate.getEdadMinima();
}
}
| true
|
eef0aff4378a27f4b9bac7c4c614b4d8cd6319db
|
Java
|
alibaba/SmartEngine
|
/core/src/main/java/com/alibaba/smart/framework/engine/bpmn/assembly/multi/instance/MultiInstanceLoopCharacteristics.java
|
UTF-8
| 779
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.alibaba.smart.framework.engine.bpmn.assembly.multi.instance;
import javax.xml.namespace.QName;
import com.alibaba.smart.framework.engine.bpmn.constant.BpmnNameSpaceConstant;
import com.alibaba.smart.framework.engine.model.assembly.ConditionExpression;
import com.alibaba.smart.framework.engine.model.assembly.NoneIdBasedElement;
import lombok.Data;
/**
* Created by 高海军 帝奇 74394 on 2017 September 21:03.
*/
@Data
public class MultiInstanceLoopCharacteristics implements NoneIdBasedElement {
public final static QName qtype = new QName(BpmnNameSpaceConstant.NAME_SPACE, "multiInstanceLoopCharacteristics");
private boolean sequential;
private ConditionExpression completionCondition;
private ConditionExpression abortCondition;
}
| true
|
593b777a54d6d077aa25b4379e9ba8d26efb6c6e
|
Java
|
shashankrnr32/WaveCLI
|
/est/speech_tools/java/common/cstr/testPrograms/WaveTest.java
|
UTF-8
| 5,234
| 2.578125
| 3
|
[
"MIT",
"LicenseRef-scancode-proprietary-license",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive",
"MIT-Festival"
] |
permissive
|
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// \\
// Centre for Speech Technology Research \\
// University of Edinburgh, UK \\
// Copyright (c) 1996,1997 \\
// All Rights Reserved. \\
// Permission is hereby granted, free of charge, to use and distribute \\
// this software and its documentation without restriction, including \\
// without limitation the rights to use, copy, modify, merge, publish, \\
// distribute, sublicense, and/or sell copies of this work, and to \\
// permit persons to whom this work is furnished to do so, subject to \\
// the following conditions: \\
// 1. The code must retain the above copyright notice, this list of \\
// conditions and the following disclaimer. \\
// 2. Any modifications must be clearly marked as such. \\
// 3. Original authors' names are not deleted. \\
// 4. The authors' names are not used to endorse or promote products \\
// derived from this software without specific prior written \\
// permission. \\
// THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK \\
// DISCLAIM ALL WARRANTIES With REGARD TO THIS SOFTWARE, INCLUDING \\
// ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT \\
// SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE \\
// FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES \\
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN \\
// AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, \\
// ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF \\
// THIS SOFTWARE. \\
// \\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
// \\
// Author: Richard Caley (rjc@cstr.ed.ac.uk) \\
// Date: Friday 12th September 1997 \\
// -------------------------------------------------------------------- \\
// Simple test program to see if wave class works. \\
// \\
//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\
package cstr.testPrograms;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import java.awt.image.*;
import java.lang.*;
import java.io.*;
import cstr.awt.*;
import cstr.est.*;
import cstr.est.awt.*;
public class WaveTest
{
public static void useage(String com)
{
System.out.println("Useage: WaveTest FILENAME " + com);
System.exit(1);
}
public static int save(Wave wv, int pos, String[] args)
{
if (args.length - pos <3)
useage("save NEWFILENAME FORMAT");
try {
wv.save(args[pos+1], args[pos+2]);
} catch (IOException e) {
System.out.println("Save Error: " + e.getMessage());
System.exit(1);
}
return 3;
}
public static int display(Wave wv, int pos, String[] args)
{
if (args.length - pos <1)
useage("display");
ImageProducer prod = new WaveImageSource(wv, 0, 400, 500, 1500, 150);
ImageCanvas canvas = new ImageCanvas(prod);
ScrollWindow win = new ScrollWindow(wv.name(), canvas, 500, 250);
try {
win.setVisible(true);
} catch (AWTError e) {
System.out.println("Exit: " + e.getMessage());
}
return 1;
}
public static int resample(Wave wv, int pos, String[] args)
{
if (args.length - pos < 2)
useage("resample RATE");
int rate=0;
try {
rate = Integer.decode(args[pos+1]).intValue();
} catch (NumberFormatException e) {
System.out.println("Sample rate must be integer > 0 not " + args[pos+1]);
System.exit(1);
}
if (rate <= 0)
{
System.out.println("Sample rate must be > 0");
System.exit(1);
}
wv.resample(rate);
return 2;
}
public static void main(String [] args)
{
System.runFinalizersOnExit(true);
Wave wv = new Wave();
if (args.length < 1)
{
useage("COMMAND {ARGS...} ...");
return;
}
try {
wv.load(args[0]);
} catch (FileNotFoundException e) {
System.out.println("Load Error: " + e.getMessage());
return;
}
int pos=1;
while (pos < args.length)
{
if (args[pos].equals("save"))
pos += save(wv, pos, args);
else if (args[pos].equals("resample"))
pos += resample(wv, pos, args);
else if (args[pos].equals("display"))
pos += display(wv, pos, args);
else
useage("save/resample/display ...");
}
}
}
| true
|
33d6349ed29a99b3bfcb4dc83247054bfcbca3e7
|
Java
|
adam-arold/game-of-life-as-service
|
/src/test/java/biz/pavonis/golservice/internal/GameOfLifeServiceImplTest.java
|
UTF-8
| 649
| 2.203125
| 2
|
[
"MIT"
] |
permissive
|
package biz.pavonis.golservice.internal;
import org.junit.Before;
import org.junit.Test;
import biz.pavonis.golservice.api.GameOfLifeService;
import biz.pavonis.golservice.api.GameOfLifeServiceBuilder;
public class GameOfLifeServiceImplTest {
private GameOfLifeService target;
@Before
public void setUp() throws Exception {
target = new GameOfLifeServiceBuilder().setHeight(5000).setWidth(5000).setTickInterval(50).build();
}
@Test
public void test() throws InterruptedException {
target.start();
Thread.sleep(5000);
System.out.println(target.getLatestGeneration().getCount());
}
}
| true
|
8378492276b21de8fe51555d7b9aa34096a8f5ff
|
Java
|
erkejriwal/onlySrcCode
|
/onlySrcCodeProject/advancedJavaLynda/multithreading/MultiThreading.java
|
UTF-8
| 1,026
| 3.390625
| 3
|
[] |
no_license
|
package onlySrcCode.onlySrcCodeProject.advancedJavaLynda.multithreading;
public class MultiThreading {
public void multiThreadingExample(){
ThreadObject threadObject = new ThreadObject();
MyThread myThread1 = new MyThread(1,threadObject);
myThread1.start();
MyThread myThread2 = new MyThread(2,threadObject);
myThread2.start();
MyThread myThread3 = new MyThread(3,threadObject);
myThread3.start();
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
try {
Thread.sleep(2500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("just to call interrupt mythread");
myThread1.interrupt();
System.out.println("called interrupt mythread");
int count = 3;
try {
for (int i = 0; i < count; i++) {
System.out.println("from main thread "+i);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
9f24d6aae0b4d8e3d2e9c2f519920267e522dfd9
|
Java
|
dapin13148/test163mail6
|
/test163mail/src/test/java/package01/openchrome.java
|
GB18030
| 1,265
| 2.34375
| 2
|
[] |
no_license
|
package package01;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
/**
* Created by lenovo on 2016/10/11.
*/
public class openchrome {
WebDriver driver;
@Test
public void openchrome(){
System.setProperty("webdriver.chrome.driver","D:\\߲\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("https://www.sina.com.cn/");
String title=driver.getTitle();
System.out.println(title);
// Assert.assertEquals(title,"ҳ");
}
@Test
public void openEdge(){
System.setProperty("webdriver.edge.driver","D:\\testing\\webdriver_demo\\drivers\\MicrosoftWebDriver.exe");
driver=new EdgeDriver();
}
/* @AfterTest //ûнtestng.xmlʱִкҲִ
public void closedchrome()throws InterruptedException{
Thread.sleep(5000);
driver.quit();
}*/
}
| true
|
494a48cad4bdc170dbf0922439310d79d19a7395
|
Java
|
rustywhite404/Weekly_Algorithm
|
/eunju/week 3/A005.java
|
UTF-8
| 423
| 3.75
| 4
|
[] |
no_license
|
package week3;
import java.util.Scanner;
public class A005 {
public static void main(String[] args) {
// 두개의 참(1) 또는 거짓(0)이 입력될 때,
// 참/거짓이 서로 같을 때에만 참이 되는 프로그램을 작성하자.
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
if(a==b) {
System.out.println(1);
}else {
System.out.println(0);
}
}
}
| true
|
30104af9dbb0bb2908a35491ff21fbc9ee9820b4
|
Java
|
liu-hz18/Au_undergraduate
|
/Java程序设计/JavaProgramms/hugeinteger/Test.java
|
UTF-8
| 1,539
| 3.25
| 3
|
[
"MIT"
] |
permissive
|
package hugeinteger;
public class Test {
public static void main(String[] args) {
HugeInteger h = new HugeInteger("0");
h.output();
System.out.println("You should print 0.");
h.input("12345");
h.output();
System.out.println("You should print 12345.");
System.out.println("");
h.add(new HugeInteger("10988"));
h.output();
System.out.println("You should print 23333.");
System.out.println("");
h.input("12345");
System.out.println((h.isEqualTo(new HugeInteger("12345")) ? "Correct!" : "Wrong!") + " h = 12345");
System.out.println((h.isNotEqualTo(new HugeInteger("54321")) ? "Correct!" : "Wrong!") + " h != 54321");
System.out.println((h.isGreaterThan(new HugeInteger("12305")) ? "Correct!" : "Wrong!") + " h > 12305");
System.out.println((h.isGreaterThan(new HugeInteger("12348")) ? "Wrong!" : "Correct!") + " h < 12348");
System.out.println((h.isGreaterThan(new HugeInteger("12345")) ? "Wrong!" : "Correct!") + " h = 12345");
System.out.println((h.isGreaterThanOrEqualTo(new HugeInteger("12345")) ? "Correct!" : "Wrong!") + " h >= 12345");
System.out.println((h.isLessThan(new HugeInteger("19988")) ? "Correct!" : "Wrong!") + " h < 19988");
System.out.println((h.isLessThan(new HugeInteger("9887")) ? "Wrong!" : "Correct!") + " h > 9887");
System.out.println((h.isLessThan(new HugeInteger("12345")) ? "Wrong!" : "Correct!") + " h = 12345");
System.out.println((h.isLessThanOrEqualTo(new HugeInteger("100000")) ? "Correct!" : "Wrong!") + " h <= 100000");
}
}
| true
|
a792804631fe55a55a2e7e6cd8cfa99b61f0b527
|
Java
|
komica7zoj/kinetix
|
/blue_etl/src/blue/schema/BlueParsePreferenceForRaw.java
|
UTF-8
| 1,691
| 2.3125
| 2
|
[] |
no_license
|
/**
*
*/
package blue.schema;
import tagaga.etl.model.ColumnSchema;
import tagaga.etl.model.TableSchema;
import tagaga.etl.utils.AbstractParsePreference;
import tagaga.etl.utils.TableSchemaParser;
/**
* @author t
*
*/
public class BlueParsePreferenceForRaw extends AbstractParsePreference {
/**
*
*/
public BlueParsePreferenceForRaw() {
}
@Override
public void applyPreference(TableSchema tableSchema) {
tableSchema.setTableName(tableSchema.getTableName()+"_Raw");
for (int i=0; i<tableSchema.getColumns().size(); i++) {
ColumnSchema column = tableSchema.getColumns().get(i);
if (ColumnSchema.Type.DATE.equals(column.getColumnType())) {
column.setSyntax("YYYYMMDD");
column.setExample("20210520");
}
column.setColumnType(ColumnSchema.Type.STRING);
column.setPreferLength(1000);
column.setAllowEmpty(true);
}
}
@Override
public String getPostColumnScripts(TableSchema tableSchema) {
return "\n\tCreated_By VARCHAR(50) NOT NULL DEFAULT ('SYSTEM'),"
+"\n\tTime_Created DATETIME NOT NULL DEFAULT (GETDATE()),"
+"\n\tID BIGINT IDENTITY(1,1),";
}
@Override
public String getPostTableScripts(TableSchema tableSchema) {
String tableName = tableSchema.getTableName();
String viewNameForWrapper = "v_"+tableName+"_wrapper";
String scripts = "";
scripts += TableSchemaParser.generateDropViewScript(viewNameForWrapper);
scripts += "\nGO\n";
scripts += "create view "+viewNameForWrapper+" as select "+tableSchema.getFieldNames()+" from "+tableName;
scripts += "\nGO\n";
return scripts;
}
}
| true
|
f0475befc0832dc76317cb8946040269ce20dd16
|
Java
|
pushkal-prakash/LMS
|
/src/SubjectRegistration.java
|
UTF-8
| 1,874
| 2.671875
| 3
|
[] |
no_license
|
import javax.servlet.http.*;
import javax.servlet.*;
import java.sql.*;
import java.io.*;
public class SubjectRegistration extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
/********************************Declaring Variables***************************/
String subjectname = "";
int departmentid;
int insert = 0;
Connection connection = null;
RequestDispatcher dispatcher = null;
/*Getting the Parameters from SubjectRegistration.html Page*/
subjectname = request.getParameter("subject");
departmentid =Integer.parseInt(request.getParameter("departmentid"));
System.out.println("subjname "+subjectname);
/*Starting JDBC Logic*/
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = ConnectionUtility.getConnection();
PreparedStatement preparedstatement = connection.prepareStatement("insert into subject values(subjectid_seq.nextval,?,?)");
preparedstatement.setString(1,subjectname);
preparedstatement.setInt(2,departmentid);
insert = preparedstatement.executeUpdate();
System.out.println(insert);
/*Checking for insertion*/
if (insert>0)
{
dispatcher = request.getRequestDispatcher("subject.jsp");
dispatcher.forward(request,response);
}
else
{
PrintWriter out = response.getWriter();
out.println("Not Inserted");
}
}
catch (Exception e)
{
e.printStackTrace();
}
/*Closing the Connection*/
finally
{
try
{
if (connection!=null)
{
connection.close();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
doGet(request,response);
}
}
| true
|
951b82679bb146bc467fb308a9b1d28e69f5753c
|
Java
|
pluiedev/Blaze4D
|
/src/main/java/me/hydos/blaze4d/mixin/debug/TextureManagerMixin.java
|
UTF-8
| 513
| 1.625
| 2
|
[
"MIT"
] |
permissive
|
package me.hydos.blaze4d.mixin.debug;
import net.minecraft.client.texture.TextureManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(TextureManager.class)
public class TextureManagerMixin {
//
// @Inject(method = "tick", at = @At("HEAD"), cancellable = true)
// private void e(CallbackInfo ci) {
// ci.cancel();
// }
}
| true
|
1cf36dac63d63fb0e3f597ffb55dbdb8c7554180
|
Java
|
kingingo/kCore
|
/src/eu/epicpvp/kcore/Kit/PerkManager.java
|
UTF-8
| 6,178
| 1.898438
| 2
|
[] |
no_license
|
package eu.epicpvp.kcore.Kit;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import eu.epicpvp.kcore.Hologram.nametags.NameTagMessage;
import eu.epicpvp.kcore.Hologram.nametags.NameTagType;
import eu.epicpvp.kcore.Inventory.InventoryPageBase;
import eu.epicpvp.kcore.Inventory.Inventory.InventoryCopy;
import eu.epicpvp.kcore.Inventory.Item.Click;
import eu.epicpvp.kcore.Kit.Perks.Event.PerkPlayerAddEvent;
import eu.epicpvp.kcore.Kit.Perks.Event.PerkPlayerRemoveEvent;
import eu.epicpvp.kcore.Listener.EntityClick.EntityClickListener;
import eu.epicpvp.kcore.Permission.PermissionType;
import eu.epicpvp.kcore.Util.UtilEnt;
import eu.epicpvp.kcore.Util.UtilEvent.ActionType;
import eu.epicpvp.kcore.Util.UtilInv;
import eu.epicpvp.kcore.Util.UtilServer;
import eu.epicpvp.kcore.kConfig.kConfig;
import lombok.Getter;
import lombok.Setter;
public class PerkManager extends PerkData {
@Getter
public JavaPlugin instance;
@Getter
@Setter
private InventoryPageBase page;
@Getter
private Entity entity;
public PerkManager(JavaPlugin instance, Perk[] perks) {
UtilServer.setPerkManager(this);
this.instance = instance;
for (Perk perk : perks)
getPlayers().put(perk, new ArrayList<Player>());
registerPerks();
setPermission("Half-Falldamage", PermissionType.PERK_HALF_FALLDAMAGE);
setPermission("One-Hit", PermissionType.PERK_KILL_ZOMBIE);
setPermission("noHunger", PermissionType.PERK_NO_HUNGER);
setPermission("DoubleXP", PermissionType.PERK_DOUBLE_XP);
setPermission("Dropper", PermissionType.PERK_DROPPER);
setPermission("GetXP", PermissionType.PERK_GET_XP);
setPermission("PotionClear", PermissionType.PERK_GOLENAPPLE);
setPermission("noFiredamage", PermissionType.PERK_NO_FIRE);
setPermission("HealPotion", PermissionType.PERK_HEALER);
setPermission("ItemName", PermissionType.PERK_ITEM_NAME);
setPermission("DoubleJump", PermissionType.PERK_JUMP);
setPermission("Runner", PermissionType.PERK_RUNNER);
setPermission("GoldenApple", PermissionType.PERK_APPLE);
setPermission("Hat", PermissionType.PERK_HAT);
setPermission("noWaterdamage", PermissionType.PERK_WATER_DAMAGE);
setPermission("ArrowPotionEffect", PermissionType.PERK_ARROW_POTIONEFFECT);
setPermission("NoPotion", PermissionType.PERK_NO_POTION);
setPermission("PerkStrength", PermissionType.PERK_UNLIMITED_STRENGTH);
setPermission("KeepXP", PermissionType.PERK_KEEP_XP);
}
public void setPerkEntity(Location location) {
entity = location.getWorld().spawnEntity(location, EntityType.WITCH);
UtilEnt.setNoAI(entity, true);
UtilEnt.setSilent(entity, true);
NameTagMessage m = new NameTagMessage(NameTagType.SERVER, entity.getLocation().add(0, 2.1, 0), "§c§lPerks");
m.send();
new EntityClickListener(getInstance(), new Click() {
@Override
public void onClick(Player player, ActionType type, Object object) {
((InventoryCopy) getPage()).open(player, UtilInv.getBase());
}
}, entity);
}
public void removePlayer(Player player) {
Bukkit.getPluginManager().callEvent(new PerkPlayerRemoveEvent(player, null));
for (Perk perk : getPlayers().keySet())
getPlayers().get(perk).remove(player);
}
public void removePlayer(Perk perk, Player player) {
Bukkit.getPluginManager().callEvent(new PerkPlayerRemoveEvent(player, perk));
getPlayers().get(perk).remove(player);
}
// public void removePlayer(String perkString,Player player){
// Bukkit.getPluginManager().callEvent(new PerkPlayerRemoveEvent(player,perkString));
// for(Perk perk : getPlayers().keySet()){
// if(perk.getName().equalsIgnoreCase(perkString)){
// getPlayers().get(perk).remove(player);
// break;
// }
// }
// }
public boolean setPermission(String perkString, PermissionType permission) {
for (Perk perk : getPlayers().keySet()) {
if (perk.getName().equalsIgnoreCase(perkString)) {
perk.setPermission(permission);
return true;
}
}
return false;
}
public void addPlayer(Player player) {
for (Perk perk : getPlayers().keySet()) {
getPlayers().get(perk).add(player);
}
Bukkit.getPluginManager().callEvent(new PerkPlayerAddEvent(player, null));
}
public void addPlayer(Perk perk, Player player) {
getPlayers().get(perk).add(player);
Bukkit.getPluginManager().callEvent(new PerkPlayerAddEvent(player, perk));
}
public void addPlayer(String perkString, Player player) {
for (Perk perk : getPlayers().keySet()) {
if (perk.getName().equalsIgnoreCase(perkString)) {
addPlayer(perk, player);
break;
}
}
}
public void configPlayer(Player player) {
if (UtilServer.getUserData().contains(player)) {
configPlayer(player, UtilServer.getUserData().getConfig(player));
}
}
public void configPlayer(Player player, kConfig config) {
for (Perk perk : getPlayers().keySet()) {
if (config.isSet("perks." + perk.getName())) {
if (config.getString("perks." + perk.getName()).equalsIgnoreCase("true")) {
getPlayers().get(perk).add(player);
} else {
getPlayers().get(perk).remove(player);
}
} else {
config.set("perks." + perk.getName(), "false");
config.save();
}
}
Bukkit.getPluginManager().callEvent(new PerkPlayerAddEvent(player, null));
}
public boolean hasPlayer(String perkString, Player player) {
for (Perk perk : getPlayers().keySet()) {
if (perkString.equalsIgnoreCase(perk.getName()) && (player.hasPermission(perk.getPermission().getPermissionToString()) || player.hasPermission(PermissionType.PERK_ALL.getPermissionToString()))) {
return true;
}
}
return false;
}
public boolean hasPlayer(Player player) {
for (Perk perk : getPlayers().keySet()) {
if ((player.hasPermission(perk.getPermission().getPermissionToString()) || player.hasPermission(PermissionType.PERK_ALL.getPermissionToString())))
return true;
}
return false;
}
public void registerPerks() {
for (Perk perk : getPlayers().keySet()) {
perk.setPerkData(this);
Bukkit.getPluginManager().registerEvents(perk, instance);
}
}
}
| true
|
d204fbdd97a676ef7959cdd05339ca023b994ae1
|
Java
|
msals97/org.onedigit.study.java
|
/src/main/java/org/onedigit/study/java/collection/sync/ReadWriteLockExample.java
|
UTF-8
| 1,550
| 3.421875
| 3
|
[] |
no_license
|
package org.onedigit.study.java.collection.sync;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadWriteLockExample
{
static class RWDictionary {
private final Map<String, String> map = new TreeMap<>();
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private final Lock rLock = rwLock.readLock();
private final Lock wLock = rwLock.writeLock();
public String get(String key)
{
rLock.lock();
try {
return map.get(key);
} finally {
rLock.unlock();
}
}
public String[] allKeys()
{
rLock.lock();
try {
return map.keySet().toArray(new String[]{});
} finally {
rLock.unlock();
}
}
public void put(String key, String value)
{
wLock.lock();
try {
map.put(key, value);
} finally {
wLock.unlock();
}
}
}
public static void main(String[] args)
{
RWDictionary dict = new RWDictionary();
dict.put("firstName", "ahmed");
dict.put("lastName", "riza");
System.out.println(Arrays.toString(dict.allKeys()));
}
}
| true
|
b2b75705dbf431556e1c011bff8e4c3049837160
|
Java
|
carlosmahumane/fenix
|
/src/main/java/net/sourceforge/fenixedu/webServices/AlumniManagement.java
|
UTF-8
| 2,058
| 2.0625
| 2
|
[] |
no_license
|
package net.sourceforge.fenixedu.webServices;
import java.util.UUID;
import javax.servlet.ServletRequest;
import net.sourceforge.fenixedu.domain.AlumniIdentityCheckRequest;
import net.sourceforge.fenixedu.util.FenixConfigurationManager;
import net.sourceforge.fenixedu.webServices.exceptions.NotAuthorizedException;
import org.codehaus.xfire.MessageContext;
import pt.ist.fenixframework.FenixFramework;
public class AlumniManagement implements IAlumniManagement {
private static final String storedPassword;
private static final String storedUsername;
static {
storedUsername =
FenixConfigurationManager.getConfiguration().getWebServicesPersonManagementgetPersonInformationUsername();
storedPassword =
FenixConfigurationManager.getConfiguration().getWebServicesPersonManagementgetPersonInformationPassword();
}
@Override
public String validateAlumniIdentity(String username, String password, String requestOID, String requestUUID,
MessageContext context) throws NotAuthorizedException {
checkPermissions(username, password, context);
AlumniIdentityCheckRequest identityCheckRequest = FenixFramework.getDomainObject(requestOID);
if (identityCheckRequest != null && identityCheckRequest.getRequestToken().equals(UUID.fromString(requestUUID))) {
return identityCheckRequest.getAlumni().getLoginUsername();
}
return null;
}
private void checkPermissions(String username, String password, MessageContext context) throws NotAuthorizedException {
// check user/pass
if (!storedUsername.equals(username) || !storedPassword.equals(password)) {
throw new NotAuthorizedException();
}
// check hosts accessing this service
if (!FenixConfigurationManager.getHostAccessControl().isAllowed(this,
(ServletRequest) context.getProperty("XFireServletController.httpServletRequest"))) {
throw new NotAuthorizedException();
}
}
}
| true
|
2082c2eb440d2ce27646317b177afd8da28ec526
|
Java
|
renchangjiu/kon-android
|
/app/src/main/java/com/htt/kon/broadcast/PlayNotificationReceiver.java
|
UTF-8
| 1,626
| 2.25
| 2
|
[
"MIT"
] |
permissive
|
package com.htt.kon.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.htt.kon.util.LogUtils;
import com.htt.kon.util.stream.Optional;
import java.io.Serializable;
import lombok.Setter;
/**
* 播放的通知栏的广播消息
*
* @author su
* @date 2020/02/24 21:56
*/
public class PlayNotificationReceiver extends BroadcastReceiver implements BaseReceiver {
public static final String ACTION = "COM.HTT.KON.MUSIC.PLAY.NOTIFICATION.RECEIVER";
@Setter
private OnReceiveListener onReceiveListener;
@Override
public void onReceive(Context context, Intent intent) {
Serializable value = intent.getSerializableExtra("key");
Optional.of(this.onReceiveListener).ifPresent(v -> v.onReceive((Flag) value));
LogUtils.e("PlayNotificationReceiver Receive a broadcast.");
}
public static Intent getIntent(Flag flag) {
Intent intent = new Intent();
intent.setAction(ACTION);
intent.putExtra("key", flag);
return intent;
}
public interface OnReceiveListener {
void onReceive(Flag flag);
}
public enum Flag {
/**
* 表示点击关闭按钮
*/
CLOSE,
/**
* 点击爱心按钮
*/
LIKE,
/**
* 点击上一首按钮
*/
PREV,
/**
* 点击播放按钮
*/
PLAY,
/**
* 点击下一首按钮
*/
NEXT,
/**
* 点击歌词按钮
*/
LRC
}
}
| true
|
457dcbd08b620cdc63fd929c97f71c1a6e21473e
|
Java
|
panyu0514/manual_pure
|
/src/com/ay/jfds/dev/action/TemplateAction.java
|
UTF-8
| 1,617
| 2.46875
| 2
|
[] |
no_license
|
package com.ay.jfds.dev.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class TemplateAction extends ActionSupport{
private File templateFile;
private String templateFileFileName;
/**
* 上传文件
* @return
*/
public String uploadFile(){
HttpServletRequest req = ServletActionContext.getRequest();
String savePath = "upload";
try {
InputStream is=new FileInputStream(templateFile);
File f = new File(savePath);
if(!f.exists()){
f.mkdirs();
}
OutputStream os=new FileOutputStream(f+File.separator+templateFileFileName);
byte[] buffer = new byte[1024*8];
int count=0;
while((count=is.read(buffer))>0){
os.write(buffer,0,count);
}
os.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "upload";
}
public File getTemplateFile() {
return templateFile;
}
public void setTemplateFile(File templateFile) {
this.templateFile = templateFile;
}
public String getTemplateFileFileName() {
return templateFileFileName;
}
public void setTemplateFileFileName(String templateFileFileName) {
this.templateFileFileName = templateFileFileName;
}
}
| true
|
a29136262a2646a7141b5f8e1b4af81e8cdc19bc
|
Java
|
johncheunghust/Algorithm-Practice
|
/src/LRUCache.java
|
UTF-8
| 2,359
| 3.125
| 3
|
[] |
no_license
|
import java.util.HashMap;
public class LRUCache {
public static void main(String[] args) {
LRUCache1 cache = new LRUCache1(2);
cache.put(2,1);
cache.put(1,1);
cache.put(2,3);
cache.put(4,1);
System.out.println(cache.get(1));
System.out.println(cache.get(2));
;
}
}
class LRUCache1 {
int cap;
HashMap<Integer, ListNode1> m;
HashMap<ListNode1, Integer> rm;
ListNode1 head;
ListNode1 tail;
int size;
public LRUCache1(int capacity) {
cap = capacity;
m = new HashMap<>();
rm = new HashMap<>();
head = null;
tail = null;
size = 0;
}
public int get(int key) {
if(!m.containsKey(key)) return -1;
ListNode1 chosen = m.get(key);
if(chosen.prev==null) return chosen.val;
ListNode1 prev = chosen.prev;
ListNode1 next = chosen.next;
if(chosen.next ==null) tail = prev;
chosen.next = head;
head.prev = chosen;
chosen.prev = null;
head = chosen;
prev.next = next;
if(next!=null) next.prev = prev;
return chosen.val;
}
public void put(int key, int value) {
ListNode1 newNode = new ListNode1(value);
if(m.containsKey(key)) {
ListNode1 temp = m.get(key);
if(temp.prev==null) head = temp.next;
if(temp.next==null) tail = temp.prev;
rm.remove(temp);
ListNode1 prev = temp.prev;
ListNode1 next = temp.next;
if(prev!=null) prev.next = next;
if(next!=null) next.prev = prev;
}
else if (++size > cap) {
int t = rm.get(tail);
m.remove(t);
rm.remove(tail);
ListNode1 prev = tail.prev;
if(prev!=null) prev.next = null;
tail = prev;
--size;
}
m.put(key, newNode);
rm.put(newNode, key);
if (head == null) {
head = newNode;
tail = newNode;
} else {
head.prev = newNode;
newNode.next = head;
head = newNode;
}
}
}
class ListNode1 {
int val;
ListNode1 next;
ListNode1 prev;
public ListNode1(int val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
| true
|
2f9678ed03d131bb2638925eab4f12976f8a7af8
|
Java
|
andrewcoggins/TradingPlatform
|
/src/main/java/brown/auction/value/valuation/library/AdditiveValuation.java
|
UTF-8
| 1,606
| 2.546875
| 3
|
[] |
no_license
|
package brown.auction.value.valuation.library;
import java.util.Map;
import brown.auction.value.valuation.ISpecificValuation;
import brown.platform.item.ICart;
import brown.platform.item.IItem;
import brown.platform.item.library.Item;
public class AdditiveValuation extends AbsSparseValuation
implements ISpecificValuation {
private Map<IItem, Double> singleItemMapping;
public AdditiveValuation() {
this.singleItemMapping = null;
}
public AdditiveValuation(Map<IItem, Double> valuation) {
this.singleItemMapping = valuation;
}
public Double getValuation(ICart cart) {
Double value = 0.0;
for (IItem item : cart.getItems()) {
IItem sItem = new Item(item.getName());
value += this.singleItemMapping.get(sItem) * item.getItemCount();
}
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((singleItemMapping == null) ? 0 : singleItemMapping.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AdditiveValuation other = (AdditiveValuation) obj;
if (singleItemMapping == null) {
if (other.singleItemMapping != null)
return false;
} else if (!singleItemMapping.equals(other.singleItemMapping))
return false;
return true;
}
@Override
public String toString() {
return "AdditiveValuation [singleItemMapping=" + singleItemMapping + "]";
}
}
| true
|
54cc66be8ee1ea1009a602187e591193a71f674b
|
Java
|
panossot/VertxAT
|
/modules/src/test/java/io/vertx/it/past/384/SSLEngineTest.java
|
UTF-8
| 4,779
| 1.6875
| 2
|
[
"Apache-2.0",
"LGPL-2.1-only",
"EPL-2.0"
] |
permissive
|
/*
* Copyright (c) 2011-2017 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.it;
import io.netty.handler.ssl.JdkSslContext;
import io.netty.handler.ssl.OpenSslContext;
import io.netty.handler.ssl.SslContext;
import io.vertx.core.VertxException;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.http.impl.HttpServerImpl;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.net.JdkSSLEngineOptions;
import io.vertx.core.net.OpenSSLEngineOptions;
import io.vertx.core.net.SSLEngineOptions;
import io.vertx.core.net.impl.SSLHelper;
import io.vertx.core.http.HttpTestBase;
import io.vertx.test.tls.Cert;
import org.junit.Test;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
import org.jboss.eap.additional.testsuite.annotations.EapAdditionalTestsuite;
@EapAdditionalTestsuite({"modules/testcases/jdkAll/master/vertx/src/main/java#3.8.4*3.8.4"})
public class SSLEngineTest extends HttpTestBase {
private static boolean isJava9() {
try {
SSLEngineTest.class.getClassLoader().loadClass("java.lang.invoke.VarHandle");
return true;
} catch (Throwable ignore) {
return false;
}
}
private static final boolean JDK = Boolean.getBoolean("vertx-test-alpn-jdk");
private static boolean OPEN_SSL = Boolean.getBoolean("vertx-test-alpn-openssl");
private static final String EXPECTED_SSL_CONTEXT = isJava9() ? "jdk" : System.getProperty("vertx-test-sslcontext");
public SSLEngineTest() {
}
@Test
public void testDefaultEngineWithAlpn() throws Exception {
doTest(null, true, HttpVersion.HTTP_2, JDK | OPEN_SSL ? "ALPN is not available" : null, EXPECTED_SSL_CONTEXT, false);
}
@Test
public void testJdkEngineWithAlpn() throws Exception {
doTest(new JdkSSLEngineOptions(), true, HttpVersion.HTTP_2, JDK ? "ALPN not available for JDK SSL/TLS engine" : null, "jdk", false);
}
@Test
public void testOpenSSLEngineWithAlpn() throws Exception {
doTest(new OpenSSLEngineOptions(), true, HttpVersion.HTTP_2, OPEN_SSL ? "OpenSSL is not available" : null, "openssl", true);
}
@Test
public void testDefaultEngine() throws Exception {
doTest(null, false, HttpVersion.HTTP_1_1, null, "jdk", false);
}
@Test
public void testJdkEngine() throws Exception {
doTest(new JdkSSLEngineOptions(), false, HttpVersion.HTTP_1_1, null, "jdk", false);
}
@Test
public void testOpenSSLEngine() throws Exception {
doTest(new OpenSSLEngineOptions(), false, HttpVersion.HTTP_1_1, "OpenSSL is not available", "openssl", true);
}
private void doTest(SSLEngineOptions engine,
boolean useAlpn, HttpVersion version, String error, String expectedSslContext, boolean expectCause) {
server.close();
HttpServerOptions options = new HttpServerOptions()
.setSslEngineOptions(engine)
.setPort(DEFAULT_HTTP_PORT)
.setHost(DEFAULT_HTTP_HOST)
.setKeyCertOptions(Cert.SERVER_PEM.get())
.setSsl(true)
.setUseAlpn(useAlpn);
try {
server = vertx.createHttpServer(options);
} catch (VertxException e) {
e.printStackTrace();
if (error == null) {
fail(e);
} else {
assertEquals(error, e.getMessage());
if (expectCause) {
assertNotSame(e, e.getCause());
}
}
return;
}
server.requestHandler(req -> {
assertEquals(req.version(), version);
assertTrue(req.isSSL());
req.response().end();
});
server.listen(onSuccess(s -> {
HttpServerImpl impl = (HttpServerImpl) s;
SSLHelper sslHelper = impl.getSslHelper();
SslContext ctx = sslHelper.getContext((VertxInternal) vertx);
switch (expectedSslContext != null ? expectedSslContext : "jdk") {
case "jdk":
assertTrue(ctx instanceof JdkSslContext);
break;
case "openssl":
assertTrue(ctx instanceof OpenSslContext);
break;
}
client = vertx.createHttpClient(new HttpClientOptions()
.setSslEngineOptions(engine)
.setSsl(true)
.setUseAlpn(useAlpn)
.setTrustAll(true)
.setProtocolVersion(version));
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
});
}));
await();
}
}
| true
|
da33d3dca401d251f395bdb16641f971efa3987f
|
Java
|
ahujadipak3/Learning
|
/pattern.design/src/main/java/com/dipak/factory/abs/IndianCarFactory.java
|
UTF-8
| 282
| 2.734375
| 3
|
[] |
no_license
|
package com.dipak.factory.abs;
public class IndianCarFactory extends AbstractFactory {
@Override
public Car getCar(String carVendor) {
if("Ford".equalsIgnoreCase(carVendor)) {
return new Ford();
}
throw new RuntimeException("Invalid argument for Car Vendor");
}
}
| true
|
e0159ae56ce6118c70c683714a1f23575109506d
|
Java
|
rafael-queiroz/pendotiba_2
|
/pendotiba-core/src/main/java/br/com/logic/pendotiba/core/model/EscalaImportada.java
|
UTF-8
| 7,245
| 1.875
| 2
|
[] |
no_license
|
package br.com.logic.pendotiba.core.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "escala_importada")
public class EscalaImportada implements Serializable {
static final long serialVersionUID = 4274705363075320535L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
Long id;
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "dd/MM/yyyy")
@Column(name = "data_competencia")
Date dataCompetencia;
@Temporal(TemporalType.TIME)
@Column(name = "inicio_jornada")
Date incioJornada;
@Temporal(TemporalType.TIME)
@Column(name = "saida")
Date saida;
@Column(name = "cracha_motorista")
String crachaMotorista;
@Column(name = "nome_motorista")
String nomeMotorista;
@Column(name = "escala_motorista")
String escalaMotorista;
@Column(name = "cracha_parceiro")
String crachaParceiro;
@Column(name = "nome_parceiro")
String nomeParceiro;
@Column(name = "escala_parceiro")
String escalaParceiro;
@Column(name = "ordem_veiculo")
String ordemVeiculo;
@Column(name = "ordem_programacao")
String ordemProgramacao;
@Column(name = "ordem_viagem")
Long ordemViagem;
@ManyToOne
@JoinColumn(name = "id_linha")
Linha linha;
@ManyToOne
@JoinColumn(name = "id_motorista")
Funcionario motorista;
@ManyToOne
@JoinColumn(name = "id_parceiro")
Funcionario parceiro;
@ManyToOne
@JoinColumn(name = "id_carro")
Carro carro;
@ManyToOne
@JoinColumn(name = "id_turno")
Turno turno;
@ManyToOne
@JoinColumn(name = "id_arquivo_importado")
ArquivoImportado arquivoImportado;
public EscalaImportada() {
}
public EscalaImportada(Date dataCompetencia, Date inicioJornada, Date saida, String crachaMotorista, String nomeMotorista,
String crachaPerceiro, String nomeParceiro, String ordemVeiculo, Linha linha,
Funcionario motorista, Funcionario parceiro, Carro carro, ArquivoImportado arquivoImportado) {
this.dataCompetencia = dataCompetencia;
this.incioJornada = inicioJornada;
this.saida = saida;
this.crachaMotorista = crachaMotorista;
this.nomeMotorista = nomeMotorista;
//this.escalaMotorista = escalaMotorista;
this.crachaParceiro = crachaPerceiro;
this.nomeParceiro = nomeParceiro;
//this.escalaParceiro = escalaParceiro;
this.ordemVeiculo = ordemVeiculo;
this.linha = linha;
this.motorista = motorista;
this.parceiro = parceiro;
this.carro = carro;
this.arquivoImportado = arquivoImportado;
}
public EscalaImportada(Date dataCompetencia, Date saida, String crachaMotorista, String nomeMotorista,
String escalaMotorista, String crachaPerceiro, String nomeParceiro, String escalaParceiro,
String ordemVeiculo, Linha linha, ArquivoImportado arquivoImportado) {
this.dataCompetencia = dataCompetencia;
this.saida = saida;
this.crachaMotorista = crachaMotorista;
this.nomeMotorista = nomeMotorista;
this.escalaMotorista = escalaMotorista;
this.crachaParceiro = crachaPerceiro;
this.nomeParceiro = nomeParceiro;
this.escalaParceiro = escalaParceiro;
this.ordemVeiculo = ordemVeiculo;
this.linha = linha;
this.arquivoImportado = arquivoImportado;
}
//GETTERS E SETTERS
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDataCompetencia() {
return dataCompetencia;
}
public void setDataCompetencia(Date dataCompetencia) {
this.dataCompetencia = dataCompetencia;
}
public Date getIncioJornada() {
return incioJornada;
}
public void setIncioJornada(Date incioJornada) {
this.incioJornada = incioJornada;
}
public Date getSaida() {
return saida;
}
public void setSaida(Date saida) {
this.saida = saida;
}
public String getCrachaMotorista() {
return crachaMotorista;
}
public void setCrachaMotorista(String crachaMotorista) {
this.crachaMotorista = crachaMotorista;
}
public String getNomeMotorista() {
return nomeMotorista;
}
public void setNomeMotorista(String nomeMotorista) {
this.nomeMotorista = nomeMotorista;
}
public String getEscalaMotorista() {
return escalaMotorista;
}
public void setEscalaMotorista(String escalaMotorista) {
this.escalaMotorista = escalaMotorista;
}
public String getCrachaParceiro() {
return crachaParceiro;
}
public void setCrachaParceiro(String crachaParceiro) {
this.crachaParceiro = crachaParceiro;
}
public String getNomeParceiro() {
return nomeParceiro;
}
public void setNomeParceiro(String nomeParceiro) {
this.nomeParceiro = nomeParceiro;
}
public String getEscalaParceiro() {
return escalaParceiro;
}
public void setEscalaParceiro(String escalaParceiro) {
this.escalaParceiro = escalaParceiro;
}
public String getOrdemVeiculo() {
return ordemVeiculo;
}
public void setOrdemVeiculo(String ordemVeiculo) {
this.ordemVeiculo = ordemVeiculo;
}
public String getOrdemProgramacao() {
return ordemProgramacao;
}
public void setOrdemProgramacao(String ordemProgramacao) {
this.ordemProgramacao = ordemProgramacao;
}
public Long getOrdemViagem() {
return ordemViagem;
}
public void setOrdemViagem(Long ordemViagem) {
this.ordemViagem = ordemViagem;
}
public Linha getLinha() {
return linha;
}
public void setLinha(Linha linha) {
this.linha = linha;
}
public Funcionario getMotorista() {
return motorista;
}
public void setMotorista(Funcionario motorista) {
this.motorista = motorista;
}
public Funcionario getParceiro() {
return parceiro;
}
public void setParceiro(Funcionario parceiro) {
this.parceiro = parceiro;
}
public Carro getCarro() {
return carro;
}
public void setCarro(Carro carro) {
this.carro = carro;
}
public Turno getTurno() {
return turno;
}
public void setTurno(Turno turno) {
this.turno = turno;
}
public ArquivoImportado getArquivoImportado() {
return arquivoImportado;
}
public void setArquivoImportado(ArquivoImportado arquivoImportado) {
this.arquivoImportado = arquivoImportado;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EscalaImportada other = (EscalaImportada) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| true
|
2395ab1a1367d9b17c6ba13c018eed4a2fa37a4d
|
Java
|
rohitkmr06/Playground
|
/Converting String to Float/Main.java
|
UTF-8
| 884
| 3.328125
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Main
{
public static void main (String[] args)
{
Scanner s=new Scanner(System.in);
String str=s.nextLine();
int len=str.length();
double a=0;
double b=0;
int c=0;
for(int i=0;i<len;i++)
{
if(str.charAt(i)=='.')
c=1;
}
if(c==1)
{
for(int i=len-1;str.charAt(i)!='.' && i>=0;i--)
{
a=a/10+(str.charAt(i)-'0');
}
a=a/10;
for (int i=0;str.charAt(i)!='.';i++)
{
b=b*10+(str.charAt(i)-'0');
}
}
else
{
for(int i=0;i<len;i++)
{
b=b*10+(str.charAt(i)-'0');
}
}
double sum=(a+b);
System.out.printf("%.6f",sum);
}
}
| true
|
4962dd3580c64fa8ab259fd2317433100379ce40
|
Java
|
ziqin/fastjson
|
/src/test/java/com/alibaba/json/test/entity/Group.java
|
UTF-8
| 765
| 2.328125
| 2
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
package com.alibaba.json.test.entity;
import java.util.ArrayList;
import java.util.List;
public class Group {
private String name;
private String description;
private List<Company> companies = new ArrayList<Company>();
public List<Company> getCompanies() {
return companies;
}
public void setCompanies(List<Company> companies) {
this.companies = companies;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| true
|
f9bb45e2b2eeb035d1c732f565c8fba45dc68efc
|
Java
|
Michael-F-Chen/AndroidNetworkSwitch
|
/app/src/main/java/com/test/network/NetworkConstants.java
|
UTF-8
| 1,542
| 2.25
| 2
|
[] |
no_license
|
package com.test.network;
/**
* Created by softwise on 2017/7/11.
*/
public class NetworkConstants {
/**
* Unknown network class
*/
public static final int NETWORK_CLASS_UNKNOWN = 0;
/**
* wifi net work
*/
public static final int NETWORK_WIFI = 1;
/**
* "MOBILE" networks Unabled
*/
public static final int NETWORK_MOBILE_STATE_UNABLED = 20;
/**
* "MOBILE" networks Enabled
*/
public static final int NETWORK_MOBILE_STATE_ENABLED = 21;
/**
* "2G" networks
*/
public static final int NETWORK_CLASS_2_G = 22;
/**
* "3G" networks
*/
public static final int NETWORK_CLASS_3_G = 23;
/**
* "4G" networks
*/
public static final int NETWORK_CLASS_4_G = 24;
/**
* wifi net work DISABLED
*/
public static final int NETWORK_WIFI_STATE_DISABLED = 11;
/**
* wifi net work DISABLING
*/
public static final int NETWORK_WIFI_STATE_DISABLING = 10;
/**
* wifi net work ENABLING
*/
public static final int NETWORK_WIFI_STATE_ENABLING = 12;
/**
* wifi net work ENABLED
*/
public static final int NETWORK_WIFI_STATE_ENABLED = 13;
/**
* wifi net work UNKNOWN
*/
public static final int NETWORK_WIFI_STATE_UNKNOWN = 14;
/**
* wifi isConnected
*/
public static final int NETWORK_WIFI_STATE_ISCONNECTED = 15;
/**
* wifi UnConnected
*/
public static final int NETWORK_WIFI_STATE_UNCONNECTED = 16;
}
| true
|
188f509f272ef256ede7b7277c0787d2e086a3de
|
Java
|
Gekoncze/JMgApplication
|
/src/cz/mg/application/services/MgClassService.java
|
UTF-8
| 910
| 2.875
| 3
|
[
"Unlicense"
] |
permissive
|
package cz.mg.application.services;
import cz.mg.application.entities.components.definitions.MgClass;
import cz.mg.collections.list.List;
public class MgClassService {
public static void forEachClass(MgClass clazz, ClassVisitor classVisitor){
forEachClass(clazz, classVisitor, new List<>(), new List<>());
}
private static void forEachClass(MgClass clazz, ClassVisitor classVisitor, List<MgClass> path, List<MgClass> visited){
if(path.contains(clazz)) throw new RuntimeException("Circular inheritance detected.");
path.addLast(clazz);
if(visited.contains(clazz)) return;
visited.addLast(clazz);
classVisitor.visit(clazz);
for(MgClass base : clazz.getBaseClasses()){
forEachClass(base, classVisitor, new List<>(path), visited);
}
}
public interface ClassVisitor {
void visit(MgClass clazz);
}
}
| true
|
6c1582c6f84ff7df57df7c9247fe9088c3d06159
|
Java
|
SlimeSB/AfraidOfTheDark
|
/src/main/java/com/DavidM1A2/AfraidOfTheDark/common/reference/AOTDDamageSources.java
|
UTF-8
| 568
| 2.234375
| 2
|
[] |
no_license
|
package com.DavidM1A2.AfraidOfTheDark.common.reference;
import net.minecraft.entity.Entity;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntityDamageSource;
import net.minecraft.util.EntityDamageSourceIndirect;
public class AOTDDamageSources
{
public static DamageSource causeSilverDamage(Entity entity)
{
return new EntityDamageSource("silverDamage", entity);
}
public static DamageSource causePlasmaBallDamage(Entity source, Entity target)
{
return new EntityDamageSourceIndirect("plasmaBall", source, target).setProjectile();
}
}
| true
|
9a268411f988a69e093d636ec943b0e784097693
|
Java
|
GitHubvary/MyExpressDemo
|
/src/main/java/com/example/demo/domain/enums/PaymentTypeEnum.java
|
UTF-8
| 579
| 2.453125
| 2
|
[] |
no_license
|
package com.example.demo.domain.enums;
import com.baomidou.mybatisplus.core.enums.IEnum;
import lombok.Getter;
/**
* Description:支付方式枚举
* date: 2021/2/25 10:26
*/
@Getter
public enum PaymentTypeEnum implements IEnum<Integer> {
/**
* 支付宝支付
*/
AliPay(1, "支付宝"),
WeChatPay(2, "微信支付");
private int type;
private String name;
PaymentTypeEnum(int type, String name) {
this.type = type;
this.name = name;
}
@Override
public Integer getValue() {
return this.type;
}
}
| true
|
728246f9363dbe750146105f78f710ad2f14cdd0
|
Java
|
seongmin-kwon/Java_Basic_Pratice
|
/Calendar_06.java
|
UTF-8
| 2,423
| 3.765625
| 4
|
[] |
no_license
|
package days13;
import java.util.Calendar;
import java.util.Scanner;
public class Calendar_06 {
public static void main(String[] args) {
// 1.해당월의 시작날짜와 끝날자 을 저장할 켈린거 객체를생성합니다.
Calendar sDay = Calendar.getInstance();// 시작일
Calendar eDay = Calendar.getInstance();// 끝일
// 2. 출력할 달력을 위해 년도와 월을 입력 받습니다.
int year;
int month;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("년도와 월을 입력하세요.");
System.out.println("년도:");
year = sc.nextInt();
System.out.println("월:");
month = sc.nextInt();
// while(input!=3) {
// 3.입력받은 월의 시작날짜로 시작객체 변수를 세팅합니다.
sDay.set(year, month - 1, 1); // 월+1로나오니 -1로입력과 맞춰주자.
// 4.입력 받은 월의 끝날짜로 끝날짜 객체 변수를 세팅합니다.
eDay.set(year, month, 1);// 입력 달의 다음달 1일 셋팅
eDay.add(Calendar.DATE, -1);// 다음달 1일로 세팅해서 하루뺀 마지막달!
// 5.시작날짜의 요일을 계산합니다.
int START_WEEK = sDay.get(Calendar.DAY_OF_WEEK);
int END_WEEK = eDay.get(Calendar.DAY_OF_WEEK);
System.out.println(START_WEEK);
// 5-1달력 타이틀 출력
System.out.println("\n" + year + "년" + month + "월");
System.out.println("일\t월\t화\t수\t목\t금\t토");
System.out.println("---------------------------------------");
// 6.시작 날짜의 요일(숫자,일요일1) 까지 0부터 시작해서 빈칸을 채웁니다.
sDay.add(Calendar.DATE, (START_WEEK - 1) * (-1));
eDay.add(Calendar.DATE, 7 - END_WEEK);
for (int i = 1; i <= eDay.get(Calendar.DATE); sDay.add(Calendar.DATE, 1)) {
int day = sDay.get(Calendar.DATE);
System.out.printf("%2d\t", day);
if (i++%7 == 0) {
System.out.println();
}
}
// 이번 달력의 1일 이전 부분에 해당하는 빈칸의 수 를 알아야한다.
// 전달의 마지막 부분 날자수 알아야하고
// t답
// 현재출력할 달력이 2020년 5월 이라면 1일금요일
// sDay 의 날짜 4월 26일 ,eday 의 말짜를 6월 6일로 설정
// 참고로 5월 31일은 일요일
// 달력 출렧; sDay부터 eDay까지년 월 뺴고 일만 출력
// 일곱 번째 출력마다 줄바꿈
}
//}/
}
| true
|
26f44f962cc0c8400b33b929da050a397aca2faa
|
Java
|
wyn37/Factory_Method_Patter
|
/src/main/java/J4_6/DatabaseFactory.java
|
UTF-8
| 215
| 2.296875
| 2
|
[] |
no_license
|
package J4_6;
public class DatabaseFactory implements DataFactory{
public Data createData(){
System.out.println("Database转换工厂");
Data data = new Database();
return data;
}
}
| true
|
a5bf77e10802d5aae9e364e04016f66149bcf5e3
|
Java
|
Kaku-U/IOProject
|
/src/main/java/kakuu/com/MyBufferStream.java
|
UTF-8
| 1,623
| 3.671875
| 4
|
[] |
no_license
|
package kakuu.com;
import java.io.*;
/*
* 以介质是硬盘为例,字节流和字符流的弊端:
* 在每一次读写的时候,都会访问硬盘。 如果读写的频率比较高的时候,其性能表现不佳。
* 为了解决以上弊端,采用缓存流。
* 缓存流在读取的时候,会一次性读较多的数据到缓存中,以后每一次的读取,都是在缓存中访问。
* 直到缓存中的数据读取完毕,再到硬盘中读取。
* */
public class MyBufferStream {
public static void readBuffer(String path) {
File f = new File(path);
try(
FileReader fr = new FileReader(f);
//BufferReader 缓存流必须建立在一个存在的流的基础上
BufferedReader br = new BufferedReader(fr);
)
{
while (true){
//一次读一行
String line = br.readLine();
if(line == null) break;
//输出行
System.out.println(line);
}
} catch(IOException e){
e.printStackTrace();
}
}
public static void writeBuffer(String path, String[] content) {
File f = new File(path);
try(
FileWriter fw = new FileWriter(f);
//PrintWriter 缓存流必须建立在一个存在的流的基础上
PrintWriter pw = new PrintWriter(f);
)
{
for (String s :content ) {
pw.println(s);
}
} catch(IOException e){
e.printStackTrace();
}
}
}
| true
|
54630253bba65b64804faaf12c8cffdbdb980677
|
Java
|
holcza/training-solutions
|
/src/test/java/covidproject/service/VaccinationStatusTest.java
|
UTF-8
| 542
| 2.28125
| 2
|
[] |
no_license
|
package covidproject.service;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import static org.junit.jupiter.api.Assertions.*;
class VaccinationStatusTest {
@Test
public void testConstructor() {
VaccinationStatus vaccinationStatus = new VaccinationStatus(2, 1, LocalDate.of(2021, 3, 4));
assertEquals(vaccinationStatus.getCitizen_id(), 2);
assertEquals(vaccinationStatus.getNumberOfVaccination(), 1);
assertEquals(vaccinationStatus.getLastDate(), LocalDate.of(2021, 3, 4));
}
}
| true
|
6b1fce3589bdd2531f1aa42a282de70a8acf76ea
|
Java
|
huahangwanghao/my-design-pattern
|
/src/main/java/com/wanghao/txt/WriteExcel.java
|
UTF-8
| 8,366
| 2.625
| 3
|
[] |
no_license
|
package com.wanghao.txt;/**
* Created by Administrator on 2018/1/15.
*/
import com.wanghao.pojo.StudentInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* @author WangH
* @create 2018-01-15 12:22
**/
public class WriteExcel {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";
public static void writeExcel(List<StudentInfo> dataList, int cloumnCount, String finalXlsxPath){
OutputStream out = null;
try {
// 获取总列数
int columnNumCount = cloumnCount;
// 读取Excel文档
File finalXlsxFile = new File(finalXlsxPath);
Workbook workBook = getWorkbok(finalXlsxFile);
// sheet 对应一个工作页
Sheet sheet = workBook.getSheetAt(0);
/**
* 删除原有数据,除了属性列
*/
int rowNumber = sheet.getLastRowNum(); // 第一行从0开始算
System.out.println("原始数据总行数,除属性列:" + rowNumber);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}
// 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
/**
* 往Excel中写新数据
*/
for (int j = 0; j < dataList.size(); j++) {
if(j==0){
Row row = sheet.createRow(j);
row.createCell(0).setCellValue("客户姓名");
row.createCell(1).setCellValue("性别");
row.createCell(2).setCellValue("手机号码");
row.createCell(3).setCellValue("管理手机号码");
row.createCell(4).setCellValue("紧急联系人及号码");
row.createCell(5).setCellValue("创建时间");
row.createCell(6).setCellValue("证件类型");
row.createCell(7).setCellValue("证件号码");
row.createCell(8).setCellValue("备注");
row.createCell(9).setCellValue("邮箱");
row.createCell(10).setCellValue("级别");
row.createCell(11).setCellValue("班级");
row.createCell(12).setCellValue("报考院校");
row.createCell(13).setCellValue("报考专业");
row.createCell(14).setCellValue("应缴学费");
row.createCell(15).setCellValue("实缴学费");
row.createCell(16).setCellValue("支付方式");
row.createCell(17).setCellValue("几年学制");
row.createCell(18).setCellValue("是否包含学位");
}
// 创建一行:从第二行开始,跳过属性列
Row row = sheet.createRow(j + 1);
// 得到要插入的每一条记录
StudentInfo st = dataList.get(j);
String name = st.getName();
String address = st.getSex();
String phone = st.getPhone();
String guanlianshoujihao=st.getGuanlianPhone();
String jinJilianxiren=st.getJinJiLianxiRen();
String createDate=st.getCreateDate();
String zhengjianType=st.getZhengJianType();
String zhengJianNo=st.getZhengJianNo();
String beizhu=st.getBeizhu();
String email=st.getEmail();
String jibie=st.getJiBie();
String banji=st.getBanji();
String baokaoyuanxiao=st.getBaoKaoYuanxiao();
String baokaozhuanye=st.getBaoKaoZhuanYe();
String yingjixuefei=st.getYingJiaoXueFei();
String shijixuefei=st.getShiJiaoXueFei();
String zhifufangshi=st.getZhiFuFangShi();
String xuezhi=st.getXueZhi();
String shifoubh=st.getShiFouBaoHanXueWei();
for (int k = 0; k <= columnNumCount; k++) {
// 在一行内循环
Cell first = row.createCell(0);
first.setCellValue(name);
Cell second = row.createCell(1);
second.setCellValue(address);
Cell third = row.createCell(2);
third.setCellValue(phone);
Cell cell3 = row.createCell(3);
cell3.setCellValue(guanlianshoujihao);
Cell cell4 = row.createCell(4);
cell4.setCellValue(jinJilianxiren);
Cell cell5 = row.createCell(5);
cell5.setCellValue(createDate);
Cell cell6 = row.createCell(6);
cell6.setCellValue(zhengjianType);
Cell cell7 = row.createCell(7);
cell7.setCellValue(zhengJianNo);
Cell cell8 = row.createCell(8);
cell8.setCellValue(beizhu);
Cell cell9 = row.createCell(9);
cell9.setCellValue(email);
Cell cell10 = row.createCell(10);
cell10.setCellValue(jibie);
Cell cell11 = row.createCell(11);
cell11.setCellValue(banji);
Cell cell12 = row.createCell(12);
cell12.setCellValue(baokaoyuanxiao);
Cell cell13 = row.createCell(13);
cell13.setCellValue(baokaozhuanye);
Cell cell14 = row.createCell(14);
cell14.setCellValue(yingjixuefei);
Cell cell15 = row.createCell(15);
cell15.setCellValue(shijixuefei);
Cell cell16 = row.createCell(16);
cell16.setCellValue(zhifufangshi);
Cell cell17 = row.createCell(17);
cell17.setCellValue(xuezhi);
Cell cell18 = row.createCell(18);
cell18.setCellValue(shifoubh);
/* Cell cell19 = row.createCell(19);
cell19.setCellValue(phone);
Cell cell20 = row.createCell(20);
cell20.setCellValue(phone);
Cell cell21 = row.createCell(21);
cell21.setCellValue(phone);*/
}
}
// 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("数据导出成功");
}
/**
* 判断Excel的版本,获取Workbook
* @param
* @param
* @return
* @throws IOException
*/
public static Workbook getWorkbok(File file) throws IOException {
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}
}
| true
|
179967a8f928b8ad76a2af5fbc889c829e73042e
|
Java
|
luciandun/VideoRecordDemo
|
/app/src/main/java/com/example/videorecorddemo/ui/RecordFragment.java
|
UTF-8
| 3,770
| 2.171875
| 2
|
[] |
no_license
|
package com.example.videorecorddemo.ui;
import android.content.Context;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.TextView;
import com.example.videorecorddemo.R;
import com.example.videorecorddemo.helper.CameraHelper;
/**
* description:抽离录制页面
* author: dlx
* date: 2019/05/15
* version: 1.0
*/
public class RecordFragment extends Fragment implements View.OnClickListener {
private TextView btnSwitchCamera;
private TextView btnStart;
private Chronometer chronometer;
private CameraHelper mCameraHelper;
private RecordingListener mListener;
public void setRecordingListener(RecordingListener listener) {
mListener = listener;
}
public static RecordFragment newInstance(String videoPath) {
RecordFragment fragment = new RecordFragment();
Bundle args = new Bundle();
args.putString("videoPath", videoPath);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof RecordingListener) {
mListener = (RecordingListener) context;
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.record_fragment, container, false);
initView(contentView);
return contentView;
}
private void initView(View contentView) {
SurfaceView surfaceView = contentView.findViewById(R.id.surface_view);
btnSwitchCamera = contentView.findViewById(R.id.switch_camera);
chronometer = contentView.findViewById(R.id.chronometer);
btnStart = contentView.findViewById(R.id.btn_start);
mCameraHelper = CameraHelper.get(getActivity(), surfaceView);
btnSwitchCamera.setOnClickListener(this);
btnStart.setOnClickListener(this);
if (getArguments() != null) {
String videoPath = getArguments().getString("videoPath");
mCameraHelper.setVideoPath(videoPath);
}
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.switch_camera) {
mCameraHelper.changeCamera();
} else if (v.getId() == R.id.btn_start) {
if (!mCameraHelper.isRecording()) {
mCameraHelper.startOrStopRecord();
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
btnStart.setText("停止");
btnSwitchCamera.setVisibility(View.GONE);
} else {
mCameraHelper.startOrStopRecord();
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.stop();
btnStart.setText("开始");
btnSwitchCamera.setVisibility(View.VISIBLE);
if (mListener != null) {
mListener.onRecordFinish(mCameraHelper.getVideoPath());
}
}
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDestroyView() {
super.onDestroyView();
mCameraHelper.destroy();
}
public interface RecordingListener {
void onRecordFinish(String filePath);
}
}
| true
|
3737272b7bc0a30bfe0567cbcae7a5cc105aa4f2
|
Java
|
gago3008/hiep-projects
|
/api-dev/src/main/java/com/hiep/Entities/Tags.java
|
UTF-8
| 658
| 2.28125
| 2
|
[] |
no_license
|
package com.hiep.Entities;
// Generated Mar 16, 2020 10:55:25 AM by Hibernate Tools 5.4.7.Final
/**
* Tags generated by hbm2java
*/
public class Tags implements java.io.Serializable {
private String tagId;
private String tagName;
public Tags() {
}
public Tags(String tagId) {
this.tagId = tagId;
}
public Tags(String tagId, String tagName) {
this.tagId = tagId;
this.tagName = tagName;
}
public String getTagId() {
return this.tagId;
}
public void setTagId(String tagId) {
this.tagId = tagId;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
}
| true
|
3c61890ec2d5cfe1b8566524b9fa0d0d51fff913
|
Java
|
lvjie0519/MyAndroidStudy
|
/app/src/main/java/com/android/study/example/androidapi/utils/ProcessUtils.java
|
UTF-8
| 1,060
| 2.640625
| 3
|
[] |
no_license
|
package com.android.study.example.androidapi.utils;
import android.app.ActivityManager;
import android.content.Context;
import java.util.List;
public class ProcessUtils {
public static boolean checkAppRunningWithPkg(Context context, String packageName){
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.processName.equals(packageName)) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND
|| appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
// 表明程序在运行中
return true;
} else {
return false;
}
}
}
return false;
}
}
| true
|
26b0cbc6e7cfcf7e296b013fcfdafb5c821a58a4
|
Java
|
panda-lang/panda
|
/panda-framework/src/main/java/panda/interpreter/parser/expression/ExpressionParserSettings.java
|
UTF-8
| 2,574
| 2.4375
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2021 dzikoysk
*
* 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 panda.interpreter.parser.expression;
/**
* Settings used by the single parse process
*/
public final class ExpressionParserSettings {
/**
* Default instance of expression settings
*/
public static final ExpressionParserSettings DEFAULT = ExpressionParserSettings.create().build();
private final boolean standaloneOnly;
private final boolean mutualDisabled;
ExpressionParserSettings(ExpressionParserSettingsBuilder builder) {
this.standaloneOnly = builder.standaloneOnly;
this.mutualDisabled = builder.mutualDisabled;
}
/**
* Parse only standalone expressions
*
* @return true if parser can parse only standalone expressions
*/
public boolean isStandaloneOnly() {
return standaloneOnly;
}
public boolean isMutualDisabled() {
return mutualDisabled;
}
/**
* Create settings builder
*
* @return a new builder instance
*/
public static ExpressionParserSettingsBuilder create() {
return new ExpressionParserSettingsBuilder();
}
/**
* Settings builder
*/
public static final class ExpressionParserSettingsBuilder {
private boolean standaloneOnly;
private boolean mutualDisabled;
ExpressionParserSettingsBuilder() { }
/**
* Parse only standalone expressions
*
* @return builder instance
*/
public ExpressionParserSettingsBuilder onlyStandalone() {
this.standaloneOnly = true;
return this;
}
public ExpressionParserSettingsBuilder mutualDisabled() {
this.mutualDisabled = true;
return this;
}
/**
* Create settings based on the collected data
*
* @return a new settings instance
*/
public ExpressionParserSettings build() {
return new ExpressionParserSettings(this);
}
}
}
| true
|
430b07e5f01b8e02135d46adab4e147a00905594
|
Java
|
ppoo14152/game1-scooby
|
/Serpiente.java
|
UTF-8
| 955
| 3.046875
| 3
|
[] |
no_license
|
import greenfoot.*;
/**
* Write a description of class serpiente here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Serpiente extends Enemigo
{
/**
* Act - do whatever the serpiente wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
muevete();
}
public void muevete()
{
if(checa()==true)
move(-1);
else
setLocation(950,570);
}
/**
* Checa si Serpiente ha sobrepasado los limites del mundo.
*/
public boolean checa()
{
boolean c = false;
int aux;
Jugar m = new Jugar(0);
GreenfootImage i = new GreenfootImage("serpiente2.png");
aux = i.getWidth()/2;
if(getX()-aux>5)
c = true;
else
c = false;
return c;
}
}
| true
|
d98ea5066047aa1dd4245b47349905af19de8b4b
|
Java
|
newbigTech/trunk
|
/app/src/main/java/com/uniware/driver/gui/fragment/order/CommonOrderAddressView.java
|
UTF-8
| 5,346
| 1.90625
| 2
|
[] |
no_license
|
package com.uniware.driver.gui.fragment.order;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
import com.uniware.driver.R;
/**
* Created by SJ on 15/11/14.
*/
public class CommonOrderAddressView extends RelativeLayout {
private RelativeLayout mDestinationVoicePlayRelativeLayout;
private TextView mDestinationVoicePlayTimeLengthTextView;
private ViewFlipper mDestinationVoicePlayViewFlipper;
private ImageView mEndIcon;
private ImageView mImgAddrFrom;
private ImageView mImgAddrTo;
private RelativeLayout mLayoutFrom;
private RelativeLayout mLayoutTo;
private int mTaskId = -1;
private TextView mTxtExtInfo;
private TextView mTxtNameFrom;
private TextView mTxtNameTo;
public CommonOrderAddressView(Context context) {
super(context);
this.initView();
}
public CommonOrderAddressView(Context context, AttributeSet attrs) {
super(context, attrs);
this.initView();
this.mDestinationVoicePlayViewFlipper.stopFlipping();
this.mDestinationVoicePlayViewFlipper.setDisplayedChild(2);
//this.mDestinationVoicePlayRelativeLayout.setOnClickListener(this.playListener);
}
public CommonOrderAddressView(Context context, AttributeSet attrs, int def) {
super(context, attrs, def);
this.initView();
}
private void initView() {
inflate(this.getContext(), R.layout.main_order_fragment_address_layout, this);
this.mTxtNameFrom = (TextView) this.findViewById(R.id.txt_name_from);
this.mTxtNameTo = (TextView) this.findViewById(R.id.txt_name_to);
this.mEndIcon = (ImageView) this.findViewById(R.id.img_address_to);
this.mTxtExtInfo = (TextView) this.findViewById(R.id.txt_extinfo);
this.mLayoutFrom = (RelativeLayout) this.findViewById(R.id.llt_from);
this.mLayoutTo = (RelativeLayout) this.findViewById(R.id.llt_to);
this.mImgAddrFrom = (ImageView) this.findViewById(R.id.img_address_from);
this.mImgAddrTo = (ImageView) this.findViewById(R.id.img_address_to);
this.mDestinationVoicePlayRelativeLayout =
(RelativeLayout) this.findViewById(R.id.rl_destination_voice_play);
this.mDestinationVoicePlayViewFlipper =
(ViewFlipper) this.findViewById(R.id.viewflipper_destination_voice_play);
this.mDestinationVoicePlayTimeLengthTextView =
(TextView) this.findViewById(R.id.tv_voice_time_length);
}
public void setAddress(String fromAddr, String toAddr, String extInfo){
mTxtNameFrom.setText(fromAddr);
mTxtNameTo.setText(toAddr);
mTxtExtInfo.setText(extInfo);
if (!extInfo.equals("")&&!extInfo.trim().equals("无")){
mTxtExtInfo.setVisibility(View.VISIBLE);
}
else {
mTxtExtInfo.setVisibility(View.GONE);
}
}
public void setNightMode(boolean nightMode) {
Drawable var2;
Drawable var3;
if (nightMode) {
this.mTxtNameFrom.setTextColor(this.getResources().getColor(R.color.text_color_dark_gray));
this.mTxtNameTo.setTextColor(this.getResources().getColor(R.color.text_color_dark_gray));
this.mTxtExtInfo.setTextColor(this.getResources().getColor(R.color.text_color_dark_gray));
this.mImgAddrFrom.setImageResource(R.drawable.common_ic_address_from);
this.mImgAddrTo.setImageResource(R.drawable.common_ic_address_to);
this.mDestinationVoicePlayRelativeLayout.setBackgroundResource(R.drawable.common_bg_night);
var2 = this.getResources().getDrawable(R.drawable.common_bg_night);
var2.setBounds(0, 0, var2.getIntrinsicWidth(), var2.getIntrinsicHeight());
var3 = this.getResources().getDrawable(R.drawable.common_bg_night);
var3.setBounds(0, 0, var3.getIntrinsicWidth(), var3.getIntrinsicHeight());
this.mTxtExtInfo.setCompoundDrawables(var2, (Drawable) null, var3, (Drawable) null);
this.getChildAt(0).setBackgroundResource(R.drawable.common_bg_night);
} else {
this.mTxtNameFrom.setTextColor(this.getResources().getColor(R.color.text_color_white));
this.mTxtNameTo.setTextColor(this.getResources().getColor(R.color.text_color_white));
this.mTxtExtInfo.setTextColor(this.getResources().getColor(R.color.text_color_white));
this.mImgAddrFrom.setImageResource(R.drawable.common_ic_address_from);
this.mImgAddrTo.setImageResource(R.drawable.common_ic_address_to);
this.mDestinationVoicePlayRelativeLayout.setBackgroundResource(R.drawable.common_bg_noon);
var2 = this.getResources().getDrawable(R.drawable.common_bg_noon);
var2.setBounds(0, 0, var2.getIntrinsicWidth(), var2.getIntrinsicHeight());
var3 = this.getResources().getDrawable(R.drawable.common_bg_noon);
var3.setBounds(0, 0, var3.getIntrinsicWidth(), var3.getIntrinsicHeight());
this.mTxtExtInfo.setCompoundDrawables(var2, (Drawable) null, var3, (Drawable) null);
this.getChildAt(0).setBackgroundResource(R.drawable.common_bg_noon);
}
}
public void startVoiceFlip() {
this.mDestinationVoicePlayViewFlipper.startFlipping();
}
public void stopPlay() {
}
public void stopVoiceFlip() {
this.mDestinationVoicePlayViewFlipper.stopFlipping();
this.mDestinationVoicePlayViewFlipper.setDisplayedChild(2);
}
}
| true
|
b018d377ef45395d10a64b4680aba7e5ce54125c
|
Java
|
NiiCi/springboot-learn
|
/springboot-httpClient/src/main/java/com/spring/httpClient/bean/Gradient.java
|
UTF-8
| 259
| 1.796875
| 2
|
[] |
no_license
|
package com.spring.httpClient.bean;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
public class Gradient {
/**
* rgb_from : 00AAFF
* rgb_to : 0085FF
*/
public String rgbFrom;
public String rgbTo;
}
| true
|
5087c820611e70d5afa037c6cd0ce2326ba9e97b
|
Java
|
omkar1102/SKNCOECDIS-UserInterface
|
/src/main/java/DatabaseAccessObjects/ResultObjects/Statistics.java
|
UTF-8
| 1,188
| 2.40625
| 2
|
[
"MIT"
] |
permissive
|
/*
* 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 DatabaseAccessObjects.ResultObjects;
import java.io.Serializable;
/**
*
* @author windows
*/
public class Statistics implements Serializable{
public int total_library_content;
public int total_books;
public int total_reports;
public Statistics(){
total_library_content=-1;
total_books=-1;
total_reports=-1;
}
public int getTotal_library_content() {
return total_library_content;
}
public void setTotal_library_content(int total_library_content) {
this.total_library_content = total_library_content;
}
public int getTotal_books() {
return total_books;
}
public void setTotal_books(int total_books) {
this.total_books = total_books;
}
public int getTotal_reports() {
return total_reports;
}
public void setTotal_reports(int total_reports) {
this.total_reports = total_reports;
}
}
| true
|
a81c000236e376e851921c9e87d7cf3990942dbe
|
Java
|
lochness42/makimono
|
/net.makimono.dictionary.indexer/src/net/makimono/dictionary/util/SearcherUtil.java
|
UTF-8
| 1,097
| 3.171875
| 3
|
[] |
no_license
|
package net.makimono.dictionary.util;
import java.io.File;
import java.util.List;
import net.makimono.dictionary.model.DictionaryEntry;
import net.makimono.dictionary.searcher.DictionarySearcher;
/**
* <p>
* Searches in the given JMdict index
* </p>
* <p>
* When using Windows UTF-8 won't be properly printed on the console. <a href=
* "http://paranoid-engineering.blogspot.com/2008/05/getting-unicode-output-in-eclipse.html"
* >Check this workaround</a>.
* </p>
*/
public class SearcherUtil {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: Searcher [path to index] [saercher string]");
System.exit(1);
}
String query = args[1];
System.out.println("Searching for '" + query + "'");
long time = System.currentTimeMillis();
List<DictionaryEntry> entries = new DictionarySearcher(new File(args[0])).search(query);
for (DictionaryEntry entry : entries) {
System.out.println(entry);
}
System.out.println("Found " + entries.size() + " hits in " + (System.currentTimeMillis() - time) + "ms");
}
}
| true
|
fff29d5b172eaa60ea50571a6f8832c699297034
|
Java
|
blustin/elpStatics
|
/elpStatics-Server/elpStatics-server-admin/src/main/java/network/cycan/elpStatics/util/HttpBlockChainUtil.java
|
UTF-8
| 6,486
| 1.976563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package network.cycan.elpStatics.util;
import lombok.extern.slf4j.Slf4j;
import network.cycan.core.util.*;
import network.cycan.elpStatics.model.dto.ChainResultDto;
import network.cycan.elpStatics.model.dto.ChainLogDto;
import network.cycan.elpStatics.model.dto.TransactionRecorkResultDto;
import network.cycan.elpStatics.model.dto.UserChainBalanceResultDto;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
public class HttpBlockChainUtil {
public static final String APIKEY = "UVJIY1RQ348R5CJX9225SA8YIM95YMWA39";
public static final String ELP_CONTRACT_ADDREES = "0xe3894cb9e92ca78524fb6a30ff072fa5e533c162";
public static final String LP_TOKEN_ADDRESS = "0xdae876044756b51e83b8bcecf810be56cfad05b1";
public static final String LP_TOKEN_ADDRESS_V2 = "0x28fa12dc40df1c7bbc19ab2a8ea55799453082c1";
public static final String MOVING_CONTRACT_ADDRESS = "0xe62bb7f26588628229b7f184c4eb84c2baff299d";
public static final BigDecimal RADIX_POINT=new BigDecimal(Math.pow(10,18));
//获取链上区块数量
public static ChainResultDto getBlocknoByTime(Long timestamp) {
try {
String url = String.format("https://api.bscscan.com/api?module=block&action=getblocknobytime&closest=before×tamp=%s&apikey=%s", timestamp, APIKEY);
String strBlockModel = HttpClientHelper.get(url);
log.info("getBlocknoByTime==返回===" + strBlockModel);
if (StringUtils.isNotEmpty(strBlockModel)) {
ChainResultDto dto = FastJsonUtil.getJsonToBean(strBlockModel, ChainResultDto.class);
if(null!=dto&&checkStatus(dto.getStatus())&& ValidateUtils.isZIndex(dto.getResult()))
{
return dto;
}else
{
Date dt= DateUtils.parseDate(DateUtils.stampToDate(timestamp.toString()));
Date before2Hour= DateUtils.addHour(dt,-2);
return getBlocknoByTime( DateUtils.convertDateTamsp(before2Hour.getTime()));
}
}
}catch (Exception ex )
{
log.error(ex.getMessage());
ex.printStackTrace();
}
return null;
}
public static ChainLogDto getLogs(Long fromBlock, Long toBlock, String address, String topic0) {
try {
String url = String.format("https://api.bscscan.com/api?module=logs&action=getLogs&fromBlock=%s&toBlock=%s&address=%s&topic0=%s&apikey=%s", fromBlock, toBlock, address, topic0, APIKEY);
String strlogModel = HttpClientHelper.get(url);
log.info("getLogs==返回===" + strlogModel);
if (StringUtils.isNotEmpty(strlogModel)) {
ChainLogDto dto = FastJsonUtil.getJsonToBean(strlogModel, ChainLogDto.class);
return dto;
}
}catch (Exception ex){
log.error(ex.getMessage());
ex.printStackTrace();
}
return null;
}
public static TransactionRecorkResultDto getTransactionRecord(Long fromBlock, Long toBlock, String contractAddress) {
String url = String.format("https://api.bscscan.com/api?module=account&action=tokentx&startblock=%s&endblock=%s&sort=asc&contractaddress=%s&apikey=%s", fromBlock, toBlock, contractAddress, APIKEY);
try {
String strlogModel = HttpClientHelper.get(url);
log.info("getTransactionRecord==返回===" + strlogModel);
if (StringUtils.isNotEmpty(strlogModel)) {
TransactionRecorkResultDto dto = FastJsonUtil.getJsonToBean(strlogModel, TransactionRecorkResultDto.class);
return dto;
}
}catch (Exception ex)
{
log.error(ex.getMessage());
ex.printStackTrace();
}
return null;
}
//获取区块之间的日志
public static ChainResultDto getAccountBalance(String contractAddress,String address) {
try{
String url = String.format("https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=%s&address=%s&tag=latest&apikey=%s", contractAddress,address, APIKEY);
String strBlockModel = HttpClientHelper.get(url);
log.info("getAccountBalance==返回==="+strBlockModel);
if (StringUtils.isNotEmpty(strBlockModel)) {
ChainResultDto dto = FastJsonUtil.getJsonToBean(strBlockModel, ChainResultDto.class);
return dto;
}
}catch (Exception ex)
{
log.error(ex.getMessage());
ex.printStackTrace();
}
return null;
}
public static ChainResultDto getContractBalance(String contractAddress) {
try{
String url = String.format("https://api.bscscan.com/api?module=stats&action=tokenCsupply&contractaddress=%s&apikey=%s", contractAddress, APIKEY);
String strBlockModel = HttpClientHelper.get(url);
log.info("getAccountBalance==返回==="+strBlockModel);
if (StringUtils.isNotEmpty(strBlockModel)) {
ChainResultDto dto = FastJsonUtil.getJsonToBean(strBlockModel, ChainResultDto.class);
return dto;
}
}catch (Exception ex)
{
log.error(ex.getMessage());
ex.printStackTrace();
}
return null;
}
//获取用户余额
public static UserChainBalanceResultDto getBatchAccountBalance(List<String> addressList) {
String strAddress=String.join(",",addressList);
String url="https://api.bscscan.com/api";
HashMap<String,String> hashMap=new HashMap<>();
hashMap.put("module","account");
hashMap.put("action","balancemulti");
hashMap.put("tag","latest");
hashMap.put("apikey",APIKEY);
hashMap.put("address",strAddress);
String strBlockModel = HttpClientHelper.doPost(url,hashMap,"utf-8");
log.info("strBlockModel==返回==="+strBlockModel);
try {
if (StringUtils.isNotEmpty(strBlockModel)) {
UserChainBalanceResultDto dto = FastJsonUtil.getJsonToBean(strBlockModel, UserChainBalanceResultDto.class);
return dto;
}
}catch ( Exception exception)
{
log.error(exception.getMessage());
exception.printStackTrace();
}
return null;
}
public static boolean checkStatus(String status) {
if ("1".equals(status)) {
return true;
}
return false;
}
}
| true
|
e7eda80a8c8eaf58ed7f1cd2d9130f583bc93efe
|
Java
|
duartepinto/LPOO
|
/src/maze/gui/Gui.java
|
UTF-8
| 996
| 2.65625
| 3
|
[] |
no_license
|
package maze.gui;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Gui {
private JFrame frmDungeon;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui window = new Gui();
window.frmDungeon.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Gui() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmDungeon = new JFrame();
MainMenuPanel panel = new MainMenuPanel(frmDungeon);
frmDungeon.setTitle("Dungeon Frontiers");
frmDungeon.setBounds(10, 10, panel.background.getWidth(), panel.background.getHeight());
frmDungeon.setResizable(false);
frmDungeon.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.background.getHeight();
frmDungeon.getContentPane().add(panel);
}
}
| true
|
e9e3acd7ec96769076c1ee0a6cacfd3cd32614ff
|
Java
|
thomasb454/Commons
|
/src/main/java/com/caved_in/commons/threading/tasks/GivePlayerTunnelsExpCallable.java
|
UTF-8
| 946
| 2.609375
| 3
|
[] |
no_license
|
package com.caved_in.commons.threading.tasks;
import com.caved_in.commons.Commons;
import com.caved_in.commons.player.Players;
import java.util.UUID;
import java.util.concurrent.Callable;
public class GivePlayerTunnelsExpCallable implements Callable<Boolean> {
private String playerName;
private UUID playerId = null;
private int amount = 0;
public GivePlayerTunnelsExpCallable(String name, int amount) {
this.playerName = name;
this.amount = amount;
}
public GivePlayerTunnelsExpCallable(UUID id, int amount) {
this.playerId = id;
this.amount = amount;
}
@Override
public Boolean call() throws Exception {
boolean updated = false;
if (playerId == null) {
playerId = Players.getUUIDFromName(playerName);
}
updated = Commons.getInstance().getServerDatabase().givePlayerMoney(playerId, amount);
return updated;
}
}
| true
|
dba2359f8e56b5f99f0285561b111f71cd3aa7af
|
Java
|
yangyugang/LaputaStudio4Android
|
/codebase/src/main/java/com/laputa/util/InputMethodUtils.java
|
UTF-8
| 1,824
| 2.34375
| 2
|
[] |
no_license
|
package com.laputa.util;
import android.app.Activity;
import android.content.Context;
import android.os.IBinder;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class InputMethodUtils {
// 打开关闭切换
public static void showSoftInputMethod(Activity context) {
try {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
}
}
public static void setSoftInputMode(Activity context, int flag) {
context.getWindow().setSoftInputMode(flag);
}
public static void showSoftInputMethod(Activity context, View view) {
InputMethodManager iMM = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
iMM.showSoftInput(view, 0);
}
public static void hideSoftInputMethod(Context context, IBinder binder) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if(imm.isActive()){
imm.hideSoftInputFromWindow(binder, 0);
}
}
public static boolean isSoftKeyboardActive(Activity context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
return inputMethodManager.isActive(view);
}
public static boolean isSoftKeyboardActive(Activity context) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
return inputMethodManager.isActive();
}
}
| true
|
bc85f0753b34ab3208f6206ec164e292bc0b2e66
|
Java
|
akoubensky/algo
|
/04.BinTree/src/Iterators.java
|
UTF-8
| 2,354
| 4.3125
| 4
|
[] |
no_license
|
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Некоторые утилиты по работе с итераторами.
* - nullIterator() выдает итератор пустого множества
* - singleElement(item) выдает итератор одноэлементного множества
* - join(it1, it2) выдает последовательное соединение двух итераторов
*/
public abstract class Iterators {
/**
* Функция, выдающая пустой итератор
* @param <T> Тип элементов итератора
* @return Итератор
*/
public static <T> Iterator<T> nullIterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() { return false; }
@Override
public T next() {
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new IllegalStateException();
}
};
}
/**
* Функция, выдающая одноэлементный итератор.
* @param <T>
* @param item
* @return
*/
public static <T> Iterator<T> singleElement(final T item) {
return new Iterator<T>() {
boolean hasItem = true;
@Override
public boolean hasNext() {
return hasItem;
}
@Override
public T next() {
if (hasItem) {
hasItem = false;
return item;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Функция последовательного соединения двух итераторов.
* @param <T> - Тип элементов итераторов
* @param it1 - Первый итератор
* @param it2 - Второй итератор
* @return - Соединенный итератор.
*/
public static <T> Iterator<T>join(final Iterator<T> it1, final Iterator<T> it2) {
return new Iterator<T>() {
Iterator<T> current = it1;
@Override
public boolean hasNext() {
return it1.hasNext() || it2.hasNext();
}
@Override
public T next() {
if (it1.hasNext()) {
return it1.next();
} else {
current = it2;
return it2.next();
}
}
@Override
public void remove() {
current.remove();
}
};
}
}
| true
|
0c328d5c7c5b4ae04ad1116512603b23e9230287
|
Java
|
shixiangweii/codes
|
/codes-demo/src/main/java/interview/clone/entity/User.java
|
UTF-8
| 430
| 2.40625
| 2
|
[] |
no_license
|
package interview.clone.entity;
import lombok.ToString;
import java.util.List;
/**
* Description:
* User: shixiangweii
* Date: 2019-01-27
* Time: 22:47
*
* @author shixiangweii
*/
@ToString
public class User implements Cloneable {
public String name;
public int age;
public List<String> list;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| true
|
4de5b9caf692a5ded8fc48c3a16807bf933ae7f5
|
Java
|
rossfletcher19/crowdSourcingSite
|
/src/test/java/dao/Sql2oLocationDaoTest.java
|
UTF-8
| 3,833
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
package dao;
import models.Hike;
import models.Location;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sql2o.Sql2o;
import org.sql2o.Connection;
import static org.junit.Assert.*;
public class Sql2oLocationDaoTest {
private Sql2oLocationDao locationDao;
private Sql2oHikeDao hikeDao;
private Connection conn;
@Before
public void setUp() throws Exception {
String connectionString = "jdbc:h2:mem:testing;INIT=RUNSCRIPT from 'classpath:db/create.sql'";
Sql2o sql2o = new Sql2o(connectionString, "", "");
locationDao = new Sql2oLocationDao(sql2o);
hikeDao = new Sql2oHikeDao(sql2o);
conn = sql2o.open();
}
@After
public void tearDown() throws Exception {
conn.close();
}
@Test
public void addingLocationSetsId() throws Exception {
Location location = setupNewLocation();
int originalLocationId = location.getId();
locationDao.add(location);
assertNotEquals(originalLocationId, location.getId());
}
@Test
public void addedLocationsCanBeReturnedByGetAll() throws Exception {
Location location = setupNewLocation();
locationDao.add(location);
assertEquals(1, locationDao.getAll().size());
}
@Test
public void noLocationsReturnsEmptyList() throws Exception {
assertEquals(0, locationDao.getAll().size());
}
@Test
public void existingLocationsCanBeFoundById() throws Exception {
Location location = setupNewLocation();
locationDao.add(location);
Location foundLocation = locationDao.findById(location.getId());
assertEquals(location, foundLocation);
}
@Test
public void getAllHikesByLocationReturnsHikesCorrectly() throws Exception {
Location location = setupNewLocation();
locationDao.add(location);
int locationId = location.getId();
Hike newHike = new Hike("Opal Creek", "Beautiful Blue Pools", 5, locationId);
Hike otherHike = new Hike("Mt. Hood Hike", "Great forest hike", 5, locationId);
Hike thirdHike = new Hike("Silver Falls", "Beautiful Water Falls", 5, locationId);
hikeDao.add(newHike);
hikeDao.add(otherHike);
assertTrue(locationDao.getAllHikesByLocation(locationId).size() == 2);
assertTrue(locationDao.getAllHikesByLocation(locationId).contains(newHike));
assertTrue(locationDao.getAllHikesByLocation(locationId).contains(otherHike));
assertFalse(locationDao.getAllHikesByLocation(locationId).contains(thirdHike));
}
@Test
public void updateChangesLocationContent() throws Exception {
String initialCityName = "Portland";
Location location = new Location(initialCityName);
locationDao.add(location);
locationDao.update(location.getId(), "SW Portland");
Location updatedLocation = locationDao.findById(location.getId());
assertNotEquals(initialCityName, updatedLocation.getName());
}
@Test
public void deleteByIdDeletesCorrectLocation() throws Exception {
Location location = setupNewLocation();
locationDao.add(location);
locationDao.deleteById(location.getId());
assertEquals(0, locationDao.getAll().size());
}
@Test
public void clearAllLocationsClearsLocations() throws Exception {
Location location = setupNewLocation();
Location otherLocation = setupNewLocation();
locationDao.add(location);
locationDao.add(otherLocation);
int daoSize = locationDao.getAll().size();
locationDao.clearAllLocations();
assertTrue(daoSize > 0 && daoSize > locationDao.getAll().size());
}
public Location setupNewLocation() {
return new Location("Estacada");
}
}
| true
|
3d57516dc686fade1a1c03eb069b05d1679288d3
|
Java
|
bsaliba1/cs-coursework
|
/CS_140/lab02/Library.java
|
UTF-8
| 1,157
| 4.0625
| 4
|
[] |
no_license
|
package lab02;
public class Library{
public static void main(String[] args){
//create array
Book[] library = new Book[3];
//create 3 book objects and add to array
library[0] = new Book("Bible",650);
library[1] = new Book("Kite Runner", 450);
library[2] = new Book("Lightning Thief", 350);
//print titles
for (Book currentElement: library){
System.out.println(currentElement.getTitle());
}
for (Book currentElement: library){
System.out.println(currentElement.getNumPages());
}
//Print out expected vs actual
System.out.println("Expected # pages is 1450");
System.out.println(numPagesInLibrary(library));
//Test mostPages() method
System.out.println("Expected # is 650");
System.out.println(mostPages(library));
}
public static int numPagesInLibrary(Book[] books){
int pages= 0;
for (Book currentElement : books){
pages = pages + currentElement.getNumPages();
}
return pages;
}
public static int mostPages(Book[] books){
int pages = 0;
for (Book currentElement : books){
if (pages<currentElement.getNumPages()){
pages = currentElement.getNumPages();
}
}
return pages;
}
}
| true
|
0a37dd4bc0c4b9f94ba3d7ca3753b0607246c2b4
|
Java
|
paul-hyun/emp
|
/src/main/java/com/hellonms/platforms/emp_orange/share/model/network/ne_session/Model4NeSessionIf.java
|
UTF-8
| 1,650
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2015 Hello NMS. All rights reserved.
*/
package com.hellonms.platforms.emp_orange.share.model.network.ne_session;
import com.hellonms.platforms.emp_core.share.model.ModelIf;
/**
* <p>
* NE 통신채널 모델 정의
* </p>
*
* @since 1.6
* @create 2015. 3. 10.
* @modified 2015. 3. 10.
* @author cchyun
*
*/
public interface Model4NeSessionIf extends ModelIf {
/**
* <p>
* NE ID 조회
* </p>
*
* @return
*/
public int getNe_id();
/**
* <p>
* NE ID 저장
* </p>
*
* @param ne_id
*/
public void setNe_id(int ne_id);
/**
* <p>
* 지원하는 프로토콜
* </p>
*
* @return
*/
public NE_SESSION_PROTOCOL getProtocol();
/**
* <p>
* IP 주소 또는 DNS 이름
* </p>
*
* @return
*/
public String getHost();
/**
* <p>
* IP 주소 또는 DNS 이름 저장
* </p>
*
* @param IP
* 주소 또는 DNS 이름
*/
public void setHost(String host);
/**
* <p>
* 실제 IP 주소
* </p>
*
* @return
*/
public String getAddress();
/**
* <p>
* 실제 IP 주소
* </p>
*
* @param address
*/
public void setAddress(String address);
/**
* 모니터링 주기 설정]
*
* @param session_check_period
*/
public void setSession_check_period(int session_check_period);
/**
* <p>
* NE 통신 상태
* </p>
*
* @return
*/
public boolean isNe_session_state();
/**
* <p>
* NE 통신 사용 상태
* </p>
*
* @return
*/
public boolean isAdmin_state();
/**
* <p>
* NE 통신 사용 상태
* </p>
*
* @param admin_state
*/
public void setAdmin_state(boolean admin_state);
}
| true
|
1964a4713ce491296acc847970a5c91780e6e827
|
Java
|
PoisonMiao/project2
|
/track-ssis/tob-common/src/main/java/com/ifchange/tob/common/helper/StrCastHelper.java
|
UTF-8
| 9,413
| 2.46875
| 2
|
[] |
no_license
|
package com.ifchange.tob.common.helper;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public final class StrCastHelper {
private StrCastHelper() {
}
private static final String BLANK = "";
/** Form Data To Object **/
public static <T> T form2Bean(String parameters, Class<T> clazz) {
return BeanHelper.map2Bean(form2Json(parameters), clazz);
}
/** Form Data to json **/
public static JSONObject form2Json(String parameters) {
try {
if (StringHelper.isBlank(parameters)) {
return new JSONObject();
}
MultiMap multiMap = new MultiMap();
decodeTo(parameters, multiMap);
return new JSONObject(multiMap);
} catch (Exception e) {
throw new RuntimeException("form parameters to json error....", e);
}
}
/** XML Data to json **/
public static JSONObject xml2Json(String xml) {
try {
Document document = DocumentHelper.parseText(xml);
MultiMap multiMap = new MultiMap();
recursiveNode(multiMap, document.getRootElement());
return new JSONObject(multiMap);
} catch (Exception e) {
throw new RuntimeException("xml parameters to json error....", e);
}
}
private static void recursiveNode(MultiMap multiMap, Element node){
multiMap.add(node.getName(), node.getTextTrim());
//递归遍历当前节点所有的子节点
@SuppressWarnings("unchecked")
List<Element> elements = node.elements();
for(Element element: elements){
recursiveNode(multiMap, element);
}
}
private static void decodeTo(String content, MultiMap map) {
String key = null, value; int mark = -1; boolean encoded = false;
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
switch (c) {
case '&':
int l = i - mark - 1;
value = l == 0 ? BLANK : (encoded ? decodeString(content, (mark + 1), l) : content.substring(mark + 1, i));
mark = i;
encoded = false;
if (key != null) {
map.add(key, value);
} else if (value != null && value.length() > 0) {
map.add(value, BLANK);
}
key = null;
break;
case '=':
if (key != null)
break;
key = encoded ? decodeString(content, (mark + 1), (i - mark - 1)) : content.substring(mark + 1, i);
mark = i;
encoded = false;
break;
case '+':
encoded = true;
break;
case '%':
encoded = true;
break;
}
}
if (key != null) {
int l = content.length() - mark - 1;
value = l == 0 ? BLANK : (encoded ? decodeString(content, (mark + 1), l) : content.substring(mark + 1));
map.add(key, value);
} else if (mark < content.length()) {
key = encoded ? decodeString(content, (mark + 1), (content.length() - mark - 1)) : content.substring(mark + 1);
map.add(key, BLANK);
}
}
private static String decodeString(String encoded, int offset, int length) {
Utf8StringBuffer buffer = null;
for (int i = 0; i < length; i++) {
char c = encoded.charAt(offset + i);
if (c > 0xff) {
if (buffer == null) {
buffer = new Utf8StringBuffer(length);
buffer.getStringBuffer().append(encoded, offset, (offset + i + 1));
} else
buffer.getStringBuffer().append(c);
} else if (c == '+') {
if (buffer == null) {
buffer = new Utf8StringBuffer(length);
buffer.getStringBuffer().append(encoded, offset, (offset + i));
}
buffer.getStringBuffer().append(' ');
} else if (c == '%' && (i + 2) < length) {
if (buffer == null) {
buffer = new Utf8StringBuffer(length);
buffer.getStringBuffer().append(encoded, offset, (offset + i));
}
while (c == '%' && (i + 2) < length) {
try {
byte b = (byte) parseInt(encoded, (offset + i + 1));
buffer.append(b);
i += 3;
} catch (NumberFormatException nfe) {
buffer.getStringBuffer().append('%');
for (char next; ((next = encoded.charAt(++i + offset)) != '%'); )
buffer.getStringBuffer().append((next == '+' ? ' ' : next));
}
if (i < length)
c = encoded.charAt(offset + i);
}
i--;
} else if (buffer != null)
buffer.getStringBuffer().append(c);
}
if (buffer == null) {
if (offset == 0 && encoded.length() == length) {
return encoded;
}
return encoded.substring(offset, offset + length);
}
return buffer.toString();
}
private static int parseInt(String s, int offset) throws NumberFormatException {
int value = 0, base = 16;
for (int i = 0; i < 2; i++) {
char c = s.charAt(offset + i); int digit = c - '0';
if (digit < 0 || digit >= base || digit >= 10) {
digit = 10 + c - 'A';
if (digit < 10 || digit >= base) digit = 10 + c - 'a';
}
if (digit < 0 || digit >= base)
throw new NumberFormatException(s.substring(offset, offset + 2));
value = value * base + digit;
}
return value;
}
private static class Utf8StringBuffer {
StringBuffer _buffer; int _more, _bits; boolean _errors;
Utf8StringBuffer(int capacity) {
_buffer = new StringBuffer(capacity);
}
void append(byte b) {
if (b >= 0) {
if (_more > 0) {
_buffer.append('?');
_more = 0;
_bits = 0;
} else {
_buffer.append((char) (0x7f & b));
}
} else if (_more == 0) {
if ((b & 0xc0) != 0xc0) {
_buffer.append('?');
_more = 0;
_bits = 0;
} else if ((b & 0xe0) == 0xc0) {
_more = 1;
_bits = b & 0x1f;
} else if ((b & 0xf0) == 0xe0) {
_more = 2;
_bits = b & 0x0f;
} else if ((b & 0xf8) == 0xf0) {
_more = 3;
_bits = b & 0x07;
} else if ((b & 0xfc) == 0xf8) {
_more = 4;
_bits = b & 0x03;
} else if ((b & 0xfe) == 0xfc) {
_more = 5;
_bits = b & 0x01;
}
} else {
if ((b & 0xc0) == 0xc0) {
_buffer.append('?');
_more = 0;
_bits = 0;
_errors = true;
} else {
_bits = (_bits << 6) | (b & 0x3f);
if (--_more == 0)
_buffer.append((char) _bits);
}
}
}
StringBuffer getStringBuffer() {
return _buffer;
}
boolean isError() {
return _errors || _more > 0;
}
public String toString() {
return _buffer.toString();
}
}
private static class MultiMap extends HashMap<String, Object> implements Cloneable {
MultiMap() { }
void add(String name, Object value) {
Object lo = super.get(name);
Object ln = LazyList.add(lo, value);
if (lo != ln) super.put(name, ln);
}
}
private static class LazyList implements Cloneable, Serializable {
private LazyList() {}
static Object add(Object list, Object item) {
if (list == null) {
if (item instanceof List || item == null) {
List l = new ArrayList();
//noinspection unchecked
l.add(item);
return l;
}
return item;
}
if (list instanceof List) {
//noinspection unchecked
((List) list).add(item);
return list;
}
List l = new ArrayList();
//noinspection unchecked
l.add(list);
//noinspection unchecked
l.add(item);
return l;
}
}
}
| true
|
8ba2a718bf8df22f1f02fad8dd76d3cff030ca83
|
Java
|
Flav1-ann/Exceptions
|
/src/eu/ensup/service/EtudiantService.java
|
UTF-8
| 2,744
| 2.40625
| 2
|
[] |
no_license
|
package eu.ensup.service;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Set;
import eu.ensup.dao.EtudiantDao;
import eu.ensup.dao.IEtudiantDao;
import eu.ensup.dao.exceptions.DaoException;
import eu.ensup.domaine.Etudiant;
import eu.ensup.service.exception.CredentialException;
import eu.ensup.service.exception.etudiantExceptions.AddEtudiantServiceException;
import eu.ensup.service.exception.etudiantExceptions.DeleteEtudiantServiceException;
import eu.ensup.service.exception.etudiantExceptions.GetAllEtudiantServiceException;
import eu.ensup.service.exception.etudiantExceptions.GetEtudiantServiceException;
import eu.ensup.service.exception.etudiantExceptions.UpdateEtudiantServiceException;
/**
* The type Etudiant service.
*/
public class EtudiantService implements IEtudiantService{
private final IEtudiantDao etudiantDao = new EtudiantDao();
private final PersonnePhysiqueService personnePhysiqueService = new PersonnePhysiqueService();
@Override
public int create(Etudiant etudiant) throws AddEtudiantServiceException, CredentialException {
byte[] salt = personnePhysiqueService.createSalt();
String hash = null;
try {
hash = personnePhysiqueService.generateHashPassword(etudiant.getMotDePasse(),salt);
} catch (NoSuchAlgorithmException e) {
throw new CredentialException();
}
etudiant.setSalt(Base64.getEncoder().encodeToString(salt));
etudiant.setMotDePasse(hash);
try {
return etudiantDao.create(etudiant);
}
catch (DaoException e) {
throw new AddEtudiantServiceException();
}
}
@Override
public int update(Etudiant etudiant) throws UpdateEtudiantServiceException {
try {
return etudiantDao.update(etudiant);
}
catch (DaoException e) {
throw new UpdateEtudiantServiceException();
}
}
@Override
public int delete(int id) throws DeleteEtudiantServiceException {
try {
return etudiantDao.delete(id);
}
catch (DaoException e) {
throw new DeleteEtudiantServiceException();
}
}
@Override
public Etudiant get(int id) throws GetEtudiantServiceException {
try {
return etudiantDao.get(id);
}
catch (DaoException e) {
throw new GetEtudiantServiceException();
}
}
@Override
public Set<Etudiant> getAll() throws GetAllEtudiantServiceException {
try {
return etudiantDao.getAll();
}
catch (DaoException e) {
throw new GetAllEtudiantServiceException();
}
}
}
| true
|
7e853e4ac14d93c6ba1155b4699338eb27872d64
|
Java
|
kolibreath/j2eeProject
|
/code/j2eefinal/src/main/java/com/kolibreath/j2eefinal/repo/DepartmentRepo.java
|
UTF-8
| 313
| 1.96875
| 2
|
[] |
no_license
|
package com.kolibreath.j2eefinal.repo;
import com.kolibreath.j2eefinal.entity.Department;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface DepartmentRepo extends JpaRepository<Department,Integer> {
List<Department> findByDepartmentName(String name);
}
| true
|
53be6c8d278f2b587406de442591ad8d39f4dc88
|
Java
|
HuynhDuc1701/ExAdviceController
|
/src/main/java/com/nextpay/vimo/repository/CityRepository.java
|
UTF-8
| 268
| 1.648438
| 2
|
[] |
no_license
|
package com.nextpay.vimo.repository;
import com.nextpay.vimo.model.City;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends CrudRepository<City, Long> {
}
| true
|
be17382320ce8dc486f03e29e7215efbd882613f
|
Java
|
luoxi-1314/JavaStuday
|
/Java基础/src/Secondparts/InterfaceDemo0.java
|
UTF-8
| 546
| 3.609375
| 4
|
[] |
no_license
|
package Secondparts;
public class InterfaceDemo0 {
public static void main(String[] args) {
A a=new B();
a.method1();
a.method2();
B b=new B();
b.method1();
b.method2();
}
}
//接口是抽象化的类 里面没有完整方法
interface A{
void method1();
void method2();
}
//类可以被继承 接口可以被实现
class B implements A{
public void method1(){
System.out.println("method");
}
public void method2(){
System.out.println("method");
}
}
| true
|
e9d6e81946389d3ac1ecf31e579d07f3d61277af
|
Java
|
MichelangeloSorice/DS_showcase
|
/src/algorithms/Utility.java
|
UTF-8
| 4,474
| 3.484375
| 3
|
[] |
no_license
|
package algorithms;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Utility {
/**
* Rabin-Kap - PatternMatching O(S) P = patternLen S = Slen && S >= P
* We compute the hash of every window of length P and compare it with the hash of P
*/
public List<Integer> matchingIdx(String s, String p){
List<Integer> res = new ArrayList();
int sl = s.length(), pl = p.length();
long mod = (long)(1e9+7); // Big prime number
long wh = 0, ph = 0; // Sliding window and pattern hash;
long alphSz = 26; // Alphabet size 26 for lowercase english letters
long h = (long)(Math.pow(alphSz, pl-1));
for(int i = 0; i<pl; i++){
ph = (ph*alphSz + (long)(p.charAt(i)-'a'))%mod;
wh = (wh*alphSz + (long)(s.charAt(i)-'a'))%mod;
}
if(ph == wh){
// Should first check actual matching of chars and then
res.add(0);
}
for(int i = pl; i<sl; i++){
// First remove hash component associated with first char of previous window
wh = (wh - (long)(s.charAt(i-pl)-'a')*h);
// Be aware wh can be negative now
if(wh < 0) wh+=mod;
// The comupte hash including new character
wh = (wh * alphSz + (long)(s.charAt(i)-'a'))%mod;
if(wh == ph){
// Should first check actual matching of chars and then
res.add(i-pl+1);
}
}
return res;
}
// ================================================================================================================
/**
* RESERVOIR SAMPLING - Randomly select k elements from a set of M items or from a continuous stram of items
* Proof
* - For elements initially in reservoir prob of being in reservoir at the end is
* ProbOfNonSelFor(k+1) * ProbOfNonSelFor(k+2) * ... * ProbOfNonSelFor(N)
* k/k+1 * k+1/k+2 * ... * n-1/n = k/n
*
* - For elements at position i > k in items
* ProbOfBeingSel(i) * ProbOfNotBeingSelFor(i+1) * ..
* k/i * i/i+1 * ... * n-1/n = K/n
*
*/
public int[] sample(int[] items, int k){
// error condition
if(k > items.length) return null;
Random rand = new Random();
int[] out = new int[k];
// Filling up reservoir all elements have prob 1 to be selected now
for(int i = 0; i<k; i++) out[i] = items[i];
for(int i = k; i<items.length; i++){
// Pick in range [0, i] inclusive
int pick = rand.nextInt(i+1);
if(pick < k){
out[pick] = items[i];
}
}
return out;
}
// ================================================================================================================
/**
* Moore's Voting Algorithm - Find Majority Element (for array of length N appears at least N/2 times)
* The algorithm always identifies a candidate majority element even if no majority element is present
* thus requires a verification step
*/
public int majorityElement(int[] nums) {
int candidate = nums[0], count = 1;
for(int i = 1; i<nums.length; i++){
if(candidate == nums[i]) {
count++;
}else if(count == 0){
candidate = nums[i]; // Set up new candidate
count = 1;
}else{
count--;
}
}
// check if candidate is actually a majority element
count = 0;
for(int x : nums) if(x==candidate) count++;
return count >= nums.length/2 ? candidate : null;
}
// ================================================================================================================
/**
* GCD - Series of numbers
* NB gcd(a,b,c) = gcd(gcd(a,b),c) = gcd(gcd(c,b),a) = gcd(gcd(a,c),b)
*/
public int generalGcd(int[] values){
int res = values[0];
for(int i = 1; i<values.length; i++) {
res = gcd(res, values[i]);
}
return res;
}
/**
* Euclidean Algorithm for GCD - O(log(min(a,b)))
*/
public int gcd(int a, int b){
/*if(a == 0)
return b;
return gcd(b%a, a);*/ //recursive version
while(a != 0){
int tmp = b%a;
b = a;
a = tmp;
}
return a;
}
}
| true
|
fca06bba6f1eb2a7705b365edf45ce9ff1437c3c
|
Java
|
tmsvanier/tmspro
|
/src/java/tmsModelLayer/ClientConsider.java
|
UTF-8
| 1,401
| 2.125
| 2
|
[] |
no_license
|
/*
* 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 tmsModelLayer;
/**
*
* @author omid
*/
public class ClientConsider {
private int considerId;
private int transportId;
private long orderId;
private String cosiderDesc;
public ClientConsider() {
}
public ClientConsider(int considerId, int transportId, long orderId, String cosiderDesc) {
this.considerId = considerId;
this.transportId = transportId;
this.orderId = orderId;
this.cosiderDesc = cosiderDesc;
}
public int getConsiderId() {
return considerId;
}
public void setConsiderId(int considerId) {
this.considerId = considerId;
}
public int getTransportId() {
return transportId;
}
public void setTransportId(int transportId) {
this.transportId = transportId;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public String getCosiderDesc() {
return cosiderDesc;
}
public void setCosiderDesc(String cosiderDesc) {
this.cosiderDesc = cosiderDesc;
}
}
| true
|
a395aa41ce762179eb0aa98f74751134e2bf54dd
|
Java
|
abbashus/sql
|
/integ-test/src/test/java/org/opensearch/sql/legacy/ObjectFieldSelectIT.java
|
UTF-8
| 3,287
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package org.opensearch.sql.legacy;
import static org.opensearch.sql.legacy.TestsConstants.TEST_INDEX_DEEP_NESTED;
import static org.opensearch.sql.util.MatcherUtils.rows;
import static org.opensearch.sql.util.MatcherUtils.schema;
import static org.opensearch.sql.util.MatcherUtils.verifyDataRows;
import static org.opensearch.sql.util.MatcherUtils.verifySchema;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assume;
import org.junit.Test;
import org.opensearch.sql.legacy.utils.StringUtils;
/**
* Integration test for OpenSearch object field (and nested field).
* This class is focused on simple SELECT-FROM query to ensure right column
* number and value is returned.
*/
public class ObjectFieldSelectIT extends SQLIntegTestCase {
@Override
protected void init() throws Exception {
loadIndex(Index.DEEP_NESTED);
}
@Test
public void testSelectObjectFieldItself() {
JSONObject response = new JSONObject(query("SELECT city FROM %s"));
verifySchema(response, schema("city", null, "object"));
// Expect object field itself is returned in a single cell
verifyDataRows(response,
rows(new JSONObject(
"{\n"
+ " \"name\": \"Seattle\",\n"
+ " \"location\": {\"latitude\": 10.5}\n"
+ "}")
)
);
}
@Test
public void testSelectObjectInnerFields() {
JSONObject response = new JSONObject(query(
"SELECT city.location, city.location.latitude FROM %s"));
verifySchema(response,
schema("city.location", null, "object"),
schema("city.location.latitude", null, "double")
);
// Expect inner regular or object field returned in its single cell
verifyDataRows(response,
rows(
new JSONObject("{\"latitude\": 10.5}"),
10.5
)
);
}
@Test
public void testSelectNestedFieldItself() {
JSONObject response = new JSONObject(query("SELECT projects FROM %s"));
// Nested field is absent in OpenSearch Get Field Mapping response either hence "object" used
verifySchema(response, schema("projects", null, "object"));
// Expect nested field itself is returned in a single cell
verifyDataRows(response,
rows(new JSONArray(
"[\n"
+ " {\"name\": \"AWS Redshift Spectrum querying\"},\n"
+ " {\"name\": \"AWS Redshift security\"},\n"
+ " {\"name\": \"AWS Aurora security\"}\n"
+ "]")
)
);
}
@Test
public void testSelectObjectFieldOfArrayValuesItself() {
JSONObject response = new JSONObject(query("SELECT accounts FROM %s"));
// Only the first element of the list of is returned.
verifyDataRows(response, rows(new JSONObject("{\"id\": 1}")));
}
@Test
public void testSelectObjectFieldOfArrayValuesInnerFields() {
JSONObject response = new JSONObject(query("SELECT accounts.id FROM %s"));
// Only the first element of the list of is returned.
verifyDataRows(response, rows(1));
}
private String query(String sql) {
return executeQuery(
StringUtils.format(sql, TEST_INDEX_DEEP_NESTED),
"jdbc"
);
}
}
| true
|