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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
23a95a5c6ab73cb02f7ab38df1037b5f5f529744
|
Java
|
CedricGatay/portlet-container-custom
|
/container/src/java/com/sun/portal/container/service/policy/DistributionType.java
|
UTF-8
| 3,176
| 2.234375
| 2
|
[] |
no_license
|
/*
* CDDL HEADER START
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License). You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the License at
* http://www.sun.com/cddl/cddl.html and legal/CDDLv1.0.txt
* See the License for the specific language governing
* permission and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Copyright 2009 Sun Microsystems Inc. All Rights Reserved
* CDDL HEADER END
*/
package com.sun.portal.container.service.policy;
import java.util.Locale;
/**
* The DistributionType class represents the possible event distribution types.
* <P>
* This class defines a standard set of the distribution types.
* Additional distribution types may be defined by calling the constructor
* of this class.
*/
public class DistributionType {
/**
* This represents all portlets that is deployed.
* <p>
* The string value for this type is "ALL_PORTLETS".
*/
public final static DistributionType ALL_PORTLETS = new DistributionType("ALL_PORTLETS");
/**
* This represents all portlets on a page. This includes both visible and hidden portlets.
* <p>
* The string value for this mode is "ALL_PORTLETS_ON_PAGE".
*/
public final static DistributionType ALL_PORTLETS_ON_PAGE = new DistributionType("ALL_PORTLETS_ON_PAGE");
/**
* This represents all visible portlets on a page.
* <p>
* The string value for this mode is "VISIBLE_PORTLETS_ON_PAGE".
*/
public final static DistributionType VISIBLE_PORTLETS_ON_PAGE = new DistributionType("VISIBLE_PORTLETS_ON_PAGE");
/**
* This is used in case the events should not be distributed to any portlets.
* <p>
* The string value for this mode is "NO_PORTLETS".
*/
public final static DistributionType NO_PORTLETS = new DistributionType("NO_PORTLETS");
private String name;
private DistributionType() {
}
/**
* Creates a new channel mode with the given name.<br>
* Lower case letters in the name will be converted to
* upper case letters.
*
* @param name The name of the channel mode
*/
public DistributionType(String name) {
if (name == null) {
throw new IllegalArgumentException("DistributionType name can not be NULL");
}
this.name = name.toUpperCase(Locale.ENGLISH);
}
public String toString() {
return this.name;
}
public int hashCode() {
return this.name.hashCode();
}
public boolean equals(Object object) {
if(object != null){
return this.name.equals(((DistributionType)object).name);
}else{
return false;
}
}
}
| true
|
7e95e72ed6f2775291013a20bb45a6f07769f76c
|
Java
|
mdht/mdht-models
|
/generated/org.openhealthtools.mdht.uml.cda.consol2/src/org/openhealthtools/mdht/uml/cda/consol/impl/NutritionalStatusObservationImpl.java
|
UTF-8
| 6,030
| 1.804688
| 2
|
[] |
no_license
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.openhealthtools.mdht.uml.cda.consol.impl;
import java.lang.Iterable;
import java.util.Map;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.mdht.emf.runtime.util.Initializer;
import org.eclipse.mdht.uml.cda.impl.ObservationImpl;
import org.openhealthtools.mdht.uml.cda.consol.ConsolPackage;
import org.openhealthtools.mdht.uml.cda.consol.NutritionAssessment;
import org.openhealthtools.mdht.uml.cda.consol.NutritionalStatusObservation;
import org.openhealthtools.mdht.uml.cda.consol.operations.NutritionalStatusObservationOperations;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Nutritional Status Observation</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class NutritionalStatusObservationImpl extends ObservationImpl implements NutritionalStatusObservation {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected NutritionalStatusObservationImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ConsolPackage.Literals.NUTRITIONAL_STATUS_OBSERVATION;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationTemplateId(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationTemplateId(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationClassCode(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationClassCode(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationMoodCode(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationMoodCode(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationId(DiagnosticChain diagnostics, Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationId(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationCodeP(DiagnosticChain diagnostics, Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationCodeP(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationCode(DiagnosticChain diagnostics, Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationCode(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationStatusCode(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationStatusCode(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationStatusCodeP(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationStatusCodeP(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationEffectiveTime(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationEffectiveTime(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationValue(DiagnosticChain diagnostics, Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationValue(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationValueP(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationValueP(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean validateNutritionalStatusObservationNutritionAssessment(DiagnosticChain diagnostics,
Map<Object, Object> context) {
return NutritionalStatusObservationOperations.validateNutritionalStatusObservationNutritionAssessment(
this, diagnostics, context);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<NutritionAssessment> getNutritionAssessments() {
return NutritionalStatusObservationOperations.getNutritionAssessments(this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NutritionalStatusObservation init() {
return Initializer.Util.init(this);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NutritionalStatusObservation init(Iterable<? extends Initializer<? extends EObject>> initializers) {
Initializer.Util.init(this, initializers);
return this;
}
} // NutritionalStatusObservationImpl
| true
|
ba0b6d8205f7b842aa6080ddc6cde22430f4e3eb
|
Java
|
apalacioj/ST0245-001
|
/laboratorios/lab04/codigo/Octree.java
|
UTF-8
| 7,867
| 3.671875
| 4
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;
import java.io.IOException;
import java.util.Collections;
/**
*This is our data structure, Octree. This will be responsible for positioning each bee in a specific quadrant,
*so you can determine if it collides or not. Its main function will be divided into eight quadrants, in 3D.
*If more than one bee is found in a quadrant, this quadrant will be divided into multiple subOctrees, found
*in the limits of this, until the bee is alone, or within a diagonal quadrant of less than 100 meters in length.
*This is done to ensure that all the bees within this quadrant are in danger of colliding.
*Nota-->para realizar esta implementación del Octree, se utilizó parte del código_estudiante dado por el docente.
* @author: Daniel Otero Gomez, Rafael Mateus Carrion, Valentina Moreno Ramírez, Alejandra Palacio Jaramillo.
* @version: 2
* @see Octree
* @see abeja
*/
public class Octree
{
/**
*This will be the method that represents the Octree, on this method all the recursion will be done, here each bee will be assigned
*to its respective sector of the Octree, represented by an ArrayList of 8 spaces (each one representing each sector), where it will
*be stored in a LinkedList. The process of deciding which sector each bee goes to will be done by the hashing method. After each bee
*is located in a sector it will happen to create the sub-views of the Octree with the new method Octree. Before going on to create
*the new subdivisions of the Octree, it is asked if the octual diagonal is less than 100 meters, if so it will start printing the
*bees located in the sectors where there is more than one bee.
* @param LinkedList<abeja> abejas: ArrayList with all the bees.
* @param double[] mins: they are the minimum values of latitude, length and height of bees´s coordinates.
* @param double[] mids: they are the middle values of latitude, length and height of bees´s coordinates.
* @see hashing
* @see nuevoOct
*/
public void octree(LinkedList<abeja> abejas, double [] mins, double[] mids, double [] maxs)throws Exception{
LinkedList<abeja>[] octree = new LinkedList[8];
for (int i=0; i<octree.length; i++) {
LinkedList<abeja> abejasAux = new LinkedList();
octree[i] = abejasAux;
}
for (abeja a: abejas) {
LinkedList<abeja> abejasAux = octree[hashing(a, mins, mids)];
abejasAux.addFirst(a);
}
double diagonal=Math.sqrt(Math.pow(mids[0]*111111,2)+Math.pow(mids[1]*111111,2)+Math.pow(mids[2],2));
if (diagonal<=100) {
for (int i=0; i<octree.length; i++){
LinkedList<abeja> abejasAux = octree[i];
if(abejasAux.size()>0){
choque(abejasAux);
}
}
System.out.println("------------------------------------------");
}else if(diagonal>100){
for(LinkedList<abeja> list :octree){
if(list.size()>=2){
nuevoOctree(list,mins,mids,maxs);
}
}
}
}
/**
*This method will be responsible for receiving each bee that is in the octree, and place it in a certain sector of the data structure,
*so that it will be located in the space of the ArrayList table corresponding to the sector in which the bee is positioned. Determine the
*sector by comparing the minimum, that is, the vertices of the Octree, plus the average values of the Octree with which it is being worked.
* @param abeja abeja: abeja que sera ubicada.
* @param ArrayList<Double> mins: this ArrayList will contain the minimum, that is, the vertex composed by each coordinate. This parameter
*is necessary to be able to make an appropriate location for each bee, because the use of this parameter will simplify the code so that only
*one value will have to be added to determine if a bee is in a sector or in other.
* @return number of the sector the Bee is located in.
*/
private int hashing(abeja abeja, double[] mins, double[] mids) {
int hashNum = 0;
if(abeja.getX()<=(mins[0] + mids[0]/2) && abeja.getY()<=(mins[1] + mids[1]/2) && abeja.getZ()<=(mins[2]+mids[2]/2)){
hashNum = 0;
}
if(abeja.getX()<=(mins[0] + mids[0]/2) && abeja.getY()<=(mins[1] + mids[1]/2) && abeja.getZ()>(mins[2]+mids[2]/2)){
hashNum = 1;
}
if(abeja.getX()<=(mins[0] + mids[0]/2) && abeja.getY()>(mins[1] + mids[1]/2) && abeja.getZ()<=(mins[2]+mids[2]/2)){
hashNum = 2;
}
if(abeja.getX()<=(mins[0] + mids[0]/2) && abeja.getY()>(mins[1] + mids[1]/2) && abeja.getZ()>(mins[2]+mids[2]/2)){
hashNum = 3;
}
if(abeja.getX()>(mins[0] + mids[0]/2) && abeja.getY()<=(mins[1] + mids[1]/2) && abeja.getZ()<=(mins[2]+mids[2]/2)){
hashNum = 4;
}
if(abeja.getX()>(mins[0] + mids[0]/2) && abeja.getY()<=(mins[1] + mids[1]/2) && abeja.getZ()>(mins[2]+mids[2]/2)){
hashNum = 5;
}
if(abeja.getX()>(mins[0] + mids[0]/2) && abeja.getY()>(mins[1] + mids[1]/2) && abeja.getZ()<=(mins[2]+mids[2]/2)){
hashNum = 6;
}
if(abeja.getX()>(mins[0] + mids[0]/2) && abeja.getY()>(mins[1] + mids[1]/2) && abeja.getZ()>(mins[2]+mids[2]/2)){
hashNum = 7;
}
return hashNum;
}
/**
* This method is responsible for making the recursion, with respect to the main octree method. Receive the parameters corresponding to
*the bees located in the sector, and the vertices of this, which are in the ArrayLis mins. With the paramtero sector they identify how
*the vertices of the next sub-octree should be redefined, since these vary by sector.
* @param LinkedList<Bee> abejas: bees of the corresponding sector
* @param ArrayList<Double> mins: they are the minimum values of coordinates, to which other parameters will be added to redefine the
*vertex of the next Octree. Take it as if it were one of the vertex of the octree.
* @param int sector: sector in which it is located.
*/
public void nuevoOctree(LinkedList<abeja> abejas, double[] mins, double[] mids, double[]maxs) throws Exception{
double min0 = 1000000;
double min1 = 1000000;
double min2 = 1000000;
double max0 = -1000000;
double max1 = 0;
double max2 = 0;
for(int i = 0; i<abejas.size(); i++){
abeja a = abejas.get(i);
min0 = Math.min(min0,a.getX());
min1 = Math.min(min1,a.getY());
min2 = Math.min(min2,a.getZ());
max0 = Math.max(max0,a.getX());
max1 = Math.max(max1,a.getY());
max2 = Math.max(max2,a.getZ());
}
double mid0 = max0-min0;
double mid1 = max1-min1;
double mid2 = max2-min2;
mins[0] = min0;
mins[1] = min1;
mins[2] = min2;
maxs[0] = max0;
maxs[1] = max1;
maxs[2] = max2;
mids[0] = mid0/2;
mids[1] = mid1/2;
mids[2] = mid2/2;
octree(abejas,mins,mids,maxs);
}
/**
* This sector is in charge of printing all the coordinates of the bees of the sector, if it prints them is because
* all these Bees are in risk of colliding.
* @param LinkedList<Bee> abejas: bees of the sector
*/
public void choque(LinkedList<abeja> abejas) {
for (abeja abeja:abejas) {
System.out.println(abeja.mostrarCoordenada());
}
}
public static void main(String[]args) throws IOException, Exception{
Reader rm = new Reader();
System.out.println("Conjuntos de abejas que colisionarán");
rm.leer("100abejas.txt");
}
}
| true
|
dda3121fe02debfb4398bbe06703748c88d02f36
|
Java
|
GabrielNew/CursoUdemyJava
|
/src/cursoUdemyJavaV/Main.java
|
UTF-8
| 1,984
| 3.609375
| 4
|
[] |
no_license
|
package cursoUdemyJavaV;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner ler = new Scanner(System.in);
// Início do programa da classe Retangulo
Retangulo ret = new Retangulo();
System.out.println("Digite o valor da altura e da largura do retângulo");
ret.altura = ler.nextDouble();
ret.largura = ler.nextDouble();
System.out.println("Área = " + ret.Area());
System.out.println("Perímetro = " + ret.Perimetro());
System.out.println("Diagonal = " + ret.Diagonal());
// Término do Programa
System.out.println();
ler.nextLine();
// Início do programa da classe Funcionario
Funcionario func = new Funcionario();
System.out.print("Nome: ");
func.Nome = ler.nextLine();
System.out.print("Salário Bruto: ");
func.Salario_Bruto = ler.nextDouble();
System.out.print("Imposto: ");
func.Imposto = ler.nextDouble();
System.out.println("Funcionário: " + func.Nome + ", $" + func.SalarioLiquido());
System.out.print("Em qual porcentagem deseja aumentar o salário? ");
double porcentagem = ler.nextDouble();
func.AumentaSalario(porcentagem);
// Término do programa
System.out.println();
ler.nextLine();
// Inicio do Programa da classe Estudante
Estudante estudante = new Estudante();
System.out.print("Nome do Estudante: ");
estudante.Nome = ler.nextLine();
System.out.println("Suas três notas: ");
estudante.nota1 = ler.nextFloat();
estudante.nota2 = ler.nextFloat();
estudante.nota3 = ler.nextFloat();
estudante.Situacao();
// Término do Programa
System.out.print("Qual é a cotação atual do dólar? R$");
double cotacao = ler.nextDouble();
System.out.print("Quantos dólares você deseja comprar? ");
double qtd_Dolar = ler.nextDouble();
System.out.printf("O valor da compra em reais é: R$ %.2f ", ConversorMoeda.conversor(cotacao, qtd_Dolar));
ler.close();
}
}
| true
|
33d9e90b75acde3de1f51d6d05769c3a45fd1dbd
|
Java
|
professor-lol/professor-lol
|
/professorlol-riot-api/src/main/java/com/ccs/professorlol/ddragon/DdragonRestTemplate.java
|
UTF-8
| 730
| 2.015625
| 2
|
[] |
no_license
|
package com.ccs.professorlol.ddragon;
import com.ccs.professorlol.ddragon.dto.RealmsDto;
import com.ccs.professorlol.ddragon.dto.champion.DdragonChampionDto;
import com.ccs.professorlol.ddragon.dto.champion.DdragonChampionFullsDto;
import com.ccs.professorlol.ddragon.dto.champion.DdragonChampionSimplesDto;
import com.ccs.professorlol.ddragon.dto.item.ItemDataDto;
public interface DdragonRestTemplate {
//ddragon의 버전정보
RealmsDto getCurrentRealms();
DdragonChampionSimplesDto getChampionSimples(String version);
DdragonChampionFullsDto getChampionFulls(String version);
DdragonChampionDto getIndividualChampion(String version, String championName);
ItemDataDto getItems(String version);
}
| true
|
3565e52e0703355346968d9636adf8c599dcb70d
|
Java
|
ravi26067/Coding
|
/coding/LeetcodeJune contest/Average.java
|
UTF-8
| 360
| 3.28125
| 3
|
[] |
no_license
|
class Solution {
public double average(int[] salary) {
int k = salary.length -2;
double sum = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i=0;i<salary.length;i++) {
if(min>salary[i])
min = salary[i];
if(max<salary[i])
max = salary[i];
sum+=salary[i];
}
sum = (sum-(min+max))/k;
return sum;
}
}
| true
|
b5b7fbd7c38c3756948899e976f771fb1c231182
|
Java
|
nanbingf2/my-work
|
/spring4/chapter3/src/main/java/com/rogercw/dao/UserDao.java
|
UTF-8
| 292
| 1.867188
| 2
|
[] |
no_license
|
package com.rogercw.dao;
import com.rogercw.domain.User;
/**
* Created by 1 on 2018/4/16.
*/
public interface UserDao {
public int getMatchCount(String userName,String password);
public User findUserByUserName(String userName);
public void updateUserLoginInfo(User user);
}
| true
|
690fc8e4bd95171cd2b8dff0d6bc195c6ea0b567
|
Java
|
wrail/videos-admin
|
/videos-admin-service/src/main/java/com/wrial/service/UsersService.java
|
UTF-8
| 207
| 1.640625
| 2
|
[] |
no_license
|
package com.wrial.service;
import com.wrial.pojo.Users;
import com.wrial.utils.PagedResult;
public interface UsersService {
public PagedResult queryUsers(Users user, Integer page, Integer pageSize);
}
| true
|
7447564040d91dc37c2bf3ae0fbadeb22b2798df
|
Java
|
massarfusion/EclipseBackUp2020
|
/Chapter_four/src/bank_account/MajorTest.java
|
UTF-8
| 460
| 2.59375
| 3
|
[] |
no_license
|
package bank_account;
import java.util.Scanner;
public class MajorTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
SavingsAccount sa= new SavingsAccount(in.next(),in.nextDouble(),in.nextInt(),in.nextDouble());
CurrentAccount ca= new CurrentAccount(in.next(),in.nextDouble(),in.nextInt(),in.nextDouble());
sa.calc();
ca.calc();
sa.printmeSA();
ca.printmeCA();
}
}
| true
|
1087e4e84a27c748553d94b529017ca023647367
|
Java
|
lonecloud/fly-tools
|
/tool-object/src/main/java/cn/lonecloud/tools/obj/ObjectsUtils.java
|
UTF-8
| 2,817
| 3
| 3
|
[] |
no_license
|
package cn.lonecloud.tools.obj;
import cn.lonecloud.tools.obj.exception.ObjectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Object 工具类
*
* @author lonecloud
* @version v1.0
* @date 2018-09-17 19:46
*/
public class ObjectsUtils {
private static Logger logger = LoggerFactory.getLogger(ObjectsUtils.class);
/**
* @param from
* @param dist
* @param clazz
* @param <T>
* @return
*/
public static <T> T getNosSameObj(Object from, Object dist, Class<T> clazz) {
final T result = getInstance(clazz);
Field[] fromFields = from.getClass().getDeclaredFields();
Field[] distFields = dist.getClass().getDeclaredFields();
List<String> sameNameList = new ArrayList<>();
//获取相同Field
for (Field field : fromFields) {
String name = field.getName();
for (Field fromField : distFields) {
String fromName = fromField.getName();
if (fromName.equals(name)) {
sameNameList.add(name);
break;
}
}
}
//然后进行比较咯
sameNameList.forEach(name -> {
PropertyDescriptor fromPd, distPd, resultPd;
try {
fromPd = new PropertyDescriptor(name, from.getClass());
distPd = new PropertyDescriptor(name, dist.getClass());
resultPd = new PropertyDescriptor(name, clazz);
//获取对象
Method fromMethod = fromPd.getReadMethod();
Method distMethod = distPd.getReadMethod();
Method writeMethod = resultPd.getWriteMethod();
Object o1 = fromMethod.invoke(from);
Object o2 = distMethod.invoke(dist);
//比较
if (Objects.nonNull(o1) && Objects.nonNull(o2) && o1.equals(o2)) {
writeMethod.invoke(result, o1);
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
});
return result;
}
public static <T> T getInstance(Class<T> clazz) {
try {
return clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
logger.error("can't new Instance a object{}", clazz.getName());
throw new ObjectException("can't new Instance a object", e);
}
}
}
| true
|
bb800ded838db552a8e57ac1fbe1d8b31a24f863
|
Java
|
lotacmonster/demo
|
/source/ThapSangTriThuc/src/client/giaodien/GiaoDienChatRoom.java
|
UTF-8
| 2,576
| 2.328125
| 2
|
[] |
no_license
|
package client.giaodien;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import client.main.MainClient;
public class GiaoDienChatRoom extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
public JTextArea tinNhanDen;
JTextField tinNhanDi;
String actionSend = "send";
MainClient mainClient;
JTextField idClient;
Calendar calendar;
String time;
public GiaoDienChatRoom(MainClient main) {
// TODO Auto-generated constructor stub
super("Chat TSTT");
mainClient=main;
this.add(taoPanelChinh());
this.setSize(700, 500);
this.addWindowListener(main);
}
JPanel taoPanelChinh()
{
JPanel panel= new JPanel(new BorderLayout());
panel.add(taoPanelCenter(), BorderLayout.CENTER);
panel.add(taoPanelChat(), BorderLayout.SOUTH);
panel.add(taoPanelTop(), BorderLayout.NORTH);
return panel;
}
JPanel taoPanelTop()
{
JPanel panel = new JPanel();
panel.add(taoNhan("Gui tin nhan den server: "));
return panel;
}
JPanel taoPanelCenter()
{
JPanel panel = new JPanel();
tinNhanDen = new JTextArea(30, 50);
panel.add(tinNhanDen);
return panel;
}
JPanel taoPanelChat()
{
JPanel panel = new JPanel();
tinNhanDi = new JTextField(20);
panel.add(taoNhan("Tin nhan: "));
panel.add(tinNhanDi);
panel.add(taoNut("Gui", actionSend));
return panel;
}
JLabel taoNhan(String tenNhan)
{
JLabel label = new JLabel(tenNhan);
return label;
}
JButton taoNut(String tenNut, String action)
{
JButton nut = new JButton(tenNut);
nut.setActionCommand(action);
nut.addActionListener(this);
return nut;
}
public void hienThi()
{
this.setVisible(true);
}
public void thoat()
{
this.setVisible(false);
}
public void hienThiTinNhan(String tinNhan)
{
//if(tinNhanDen.getText().length()>50)tinNhanDen.setText("");
tinNhanDen.setText(tinNhanDen.getText()+"\n"+tinNhan);
}
@Override
public void actionPerformed(ActionEvent ev) {
// TODO Auto-generated method stub
if(ev.getActionCommand().equals(actionSend))
{
mainClient.guiTinNhan(tinNhanDi.getText());
tinNhanDen.setText(tinNhanDen.getText()+"\nBan: "+tinNhanDi.getText());
tinNhanDi.setText("");
}
}
}
| true
|
c759f1664a61a6ebc9ffe9bc84cdbdeda0d7a462
|
Java
|
jcreyes72/cpsc2150
|
/course_lab/Lab10/src/cpsc2150/banking/controllers/MortgageController.java
|
UTF-8
| 901
| 2.984375
| 3
|
[] |
no_license
|
package cpsc2150.banking.controllers;
import cpsc2150.banking.models.Customer;
import cpsc2150.banking.models.IMortgage;
import cpsc2150.banking.views.IMortgageView;
public class MortgageController implements IMortgageController {
// This constant will ensure we do not exceed the maximum amount for credit score
int CREDIT_MAX = 850;
// Our private view variable we will use to utilize our view
private IMortgageView ourView;
// The cost of our house, monthly debt payment, income, and down payment (in that order)
double houseCost, monthlyDebtPayment, income, downPayment;
// Our credit score and years
int creditScore, yrs;
// Name for user
String name;
public MortgageController(IMortgageView view){
ourView = view;
}
@Override
public void submitApplication() {
ourView.printToUser("What's your name?");
}
}
| true
|
73fcf806f9d709cebee1b378a3bd55d42203bf27
|
Java
|
Good-Old-Living/application
|
/Application-ECom/src/main/java/meru/application/security/action/ResetPasswordOTPAction.java
|
UTF-8
| 1,294
| 2.40625
| 2
|
[] |
no_license
|
package meru.application.security.action;
import java.io.IOException;
import app.domain.security.User;
import meru.app.binding.http.HttpAppRequest;
import meru.application.AppType;
import meru.exception.AppException;
import meru.sys.lang.StringHelper;
import meru.template.TemplateStringData;
public class ResetPasswordOTPAction extends AccountAction {
@Override
public void perform(HttpAppRequest appRequest) throws IOException {
String mobile = appRequest.getSingleParameter("mobile");
if (StringHelper.isNullOrEmpty(mobile)) {
throw new AppException("Please provide mobile number");
}
User user = getUser(mobile);
if (user == null) {
throw new AppException(mobile + " has not been registered with us");
}
updateUserOTP(user,
AppType.WEB);
sendResponse("password-reset-otp.html",
new TemplateStringData("An OTP has been sent to your mobile"),
appRequest.getResponse().getWriter());
}
@Override
protected void onFailure(HttpAppRequest appRequest,
Exception e) throws IOException {
sendResponse("password-reset-failure.html",
new TemplateStringData(e.getMessage()),
appRequest.getResponse().getWriter());
}
}
| true
|
f16e8ff064bf5903f369787bd53a5f3271bedb67
|
Java
|
rohituppalapati/kylo-source
|
/integrations/spark/spark-validate-cleanse/spark-validate-cleanse-spark-v1/src/main/java/com/thinkbiganalytics/spark/datavalidator/functions/PartitionLevelCountsV1.java
|
UTF-8
| 2,219
| 2.328125
| 2
|
[
"WTFPL",
"CDDL-1.0",
"MIT",
"CC0-1.0",
"EPL-1.0",
"PostgreSQL",
"BSD-3-Clause",
"LGPL-2.1-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-protobuf",
"OFL-1.1"
] |
permissive
|
package com.thinkbiganalytics.spark.datavalidator.functions;
/*-
* #%L
* kylo-spark-validate-cleanse-spark-v1
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.thinkbiganalytics.spark.datavalidator.CleansedRowResult;
import org.apache.spark.api.java.function.FlatMapFunction;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Get partition-level counts of invalid columns, and total valid and invalid rows (Spark 1)
*/
public class PartitionLevelCountsV1 implements FlatMapFunction<Iterator<CleansedRowResult>, long[]> {
private int schemaLen = 0;
public PartitionLevelCountsV1(int schemaLength) {
this.schemaLen = schemaLength;
}
@Override
public Iterator<long[]> call(Iterator<CleansedRowResult> cleansedRowResultIterator) throws Exception {
long[] validationCounts = new long[schemaLen + 2];
while (cleansedRowResultIterator.hasNext()) {
CleansedRowResult cleansedRowResult = cleansedRowResultIterator.next();
for (int idx = 0; idx < schemaLen; idx++) {
if (!cleansedRowResult.isColumnValid(idx)) {
validationCounts[idx] = validationCounts[idx] + 1L;
}
}
if (cleansedRowResult.isRowValid()) {
validationCounts[schemaLen] = validationCounts[schemaLen] + 1L;
} else {
validationCounts[schemaLen + 1] = validationCounts[schemaLen + 1] + 1L;
}
}
List<long[]> results = new LinkedList<>();
results.add(validationCounts);
return results.iterator();
}
}
| true
|
0c1a1c48b0e8513139dcea2ec1f01c8d3f3a9680
|
Java
|
silentbalanceyh/vertx-zero
|
/vertx-gaia/vertx-ams/src/main/qas/io/modello/specification/atom/HAtom.java
|
UTF-8
| 6,708
| 2.125
| 2
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
package io.modello.specification.atom;
import io.macrocosm.specification.program.HArk;
import io.modello.atom.normalize.KMarkAtom;
import io.modello.specification.action.HDiff;
import io.modello.specification.meta.HMetaAtom;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
/**
* Zero中的模型结构处理,主要包括:
* <pre><code>
* -- Zero核心框架建模(Hybrid建模方式)
* -- Zero扩展框架建模(zero-atom中的动态建模方式)
* -- Zero规范建模(EMF建模,依赖Ecore模型)
* </code></pre>
*
* 此处提供了所有基于Zero中支持的不同种类的模型定义:
* <pre><code>
* -- 动态模型:
* 内置于扩展模块( zero-atom )中的 `M_X` 系列表结构存储元模型数据的建模,该模型的子类将被转换为
* DataAtom 类型
*
* -- 静态模型:
* (依赖代码生成)Jooq生成(Pojo/Dao)模块,是Zero框架中的标准模块,面相开发人员的常用建模。
*
* -- 集成模型:
* 针对系统集成的第三方建模方式,可直接开启 模型通道,针对属性进行强定制。
*
* -- 工业模型:
* 可直接转换成工业规范的模型,提供工业规范序列化,如 ISO-XXXXX,实现工业规范的完整对接,直接将模型
* 转换成工业标准实现对接,核心建模框架直接使用 EMF。
*
* -- 采集模型:
* 对接 JPython 或 Python 实现数据分析统一模型,后续会形成子接口对接数据分析核心算法,搭载分析模块
* 针对常用业务场景实现数据分析流程。
*
* -- 流程模型:
* 对接 Camunda 流程引擎(Hybrid混合方式),针对工作流中的模型进行可拓展管理模式的核心模型
*
* -- 监控模型(面向运维):
* 对接 K8S 的监控平台实现针对模型本身的前端建模方式,可监控模型的所有变化,实现通知和变化感知
*
* -- 设计模型(面向设计):
* 实现低代码所见即所得的设计界面交互模式的模型,可直接在界面中进行模型的设计,实现低代码的可视化
*
* -- 开发模型(面向开发):
* 在系统中直接提供调试、断点、语言级的建模方式,实现面相开发人员的建模。
*
* </code></pre>
*
* @author lang
*/
public interface HAtom extends
HDiff, // 模型比较器,返回当前模型的 Vs 接口
HAtomAttribute, // 模型属性专用接口
HAtomRule, // 标识规则专用接口
HAtomIo // 属性标识符专用接口
{
/**
* 基于当前模型定义创建模型副本,该副本和模型定义拥有同样的 namespace,但是拥有不同的 identifier
* 快速创建模型定义的专有方法,而且防止模型副本本身被改动。
*
* @param identifier 模型副本的标识符
*
* @return 模型副本
*/
HAtom copy(String identifier);
// =================== Cross Method between two atoms ===========
/**
* (Metadata)返回当前模型定义中的元模型信息,里面包含了核心建模内置定义
*
* @return 元模型信息
*/
HMetaAtom shape();
/**
* (Modeler)返回当前模型定义中的元模型消费信息,里面包含了消费层所需的真实模型定义
*
* @param <T> 模型类型
*
* @return 消费模型信息
*/
<T extends HModel> T model();
// =================== 模型元数据基础 ===========
String identifier();
HArk ark();
// ==================== Reference Information ================
HReference reference();
}
// ==================== 属性标记 =====================
/**
* 返回模型的属性标记
*/
interface HAtomIo {
/**
* 直接引用模型级的属性标记类,记录了当前模型两级配置
* <pre><code>
* 1. 模型是否可追踪
* 2. 在可追踪和不可追踪模式下的属性标记信息(每个属性中会包含 {@link io.modello.atom.normalize.KMarkAttribute})
* </code></pre>
*
* @return {@link KMarkAtom}
*/
KMarkAtom marker();
}
// ==================== 标识规则 =====================
/**
* 返回模型中不同标识规则之下的内容
*/
interface HAtomRule {
/**
* 「低优先级」返回模型的约束信息,此处返回约束为 Master 约束,通常是配置在元模型仓库中
* (存储在数据库),但该约束的优先级会低于通道级的约束,允许部分行为对其执行变更。
*
* @return {@link HRule}
*/
HRule ruleAtom();
/**
* 「高优先级」返回模型的通道级约束,同一个模型在不同通道中的约束信息可以不相同,通常是
* 编程模式可变更的动态约束,例如:在不同通道中,同一个模型的属性名可以不同。
*
* @return {@link HRule}
*/
HRule rule();
/**
* 标识规则搜索模式,动态返回当前模型启用的标识规则:
* <pre><code>
* 1. 如果当前模型启用了通道级的标识规则,则返回通道级的标识规则
* 2. 如果当前模型没有启用通道级的标识规则,则返回模型级的标识规则
* </code></pre>
*
* @return {@link HRule}
*/
HRule ruleSmart();
/**
* 该方法仅会在执行器部分被调用,主要用于动态绑定当前环境生效的标识规则
*
* @param rule 标识规则
* @param <T> 标识规则类型
*
* @return {@link HRule}
*/
<T extends HAtom> T rule(HRule rule);
}
// ==================== 属性部分 =====================
/**
* Atom模型的属性部分,用于描述模型的属性相关信息
*
* @author lang
*/
interface HAtomAttribute {
/**
* 返回当前模型的所有属性名
*
* @return 属性名集合
*/
Set<String> attribute();
/**
* 返回属性名的UI呈现信息 name = alias
* 移除旧接口:
* <pre><code>
* / String alias(String name)
* </code></pre>
*
* @return 属性名集合
*/
ConcurrentMap<String, String> alias();
/**
* 返回当前模型指定的属性名 {@link HAttribute}
*
* @param name 属性名
*
* @return 属性
*/
HAttribute attribute(String name);
/**
* 返回所有属性类型信息
* 移除旧接口:
* <pre><code>
* / Class<?> type(String name);
* </code></pre>
*
* @return 类型集合
*/
ConcurrentMap<String, Class<?>> type();
}
| true
|
1a0301d165b0eb91a768574c848b4d3487bfa9f6
|
Java
|
kielbi12/programowanie_2
|
/src/main/java/day3/dhl/Adress.java
|
UTF-8
| 241
| 1.820313
| 2
|
[] |
no_license
|
package day3.dhl;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class Adress {
private String street;
private String postCode;
private String city;
private int homeNumber;
}
| true
|
ffdcfc07b8ecf00da2b39190cac67ef8ad7eb30e
|
Java
|
rjssouza/AppVendas
|
/app/src/main/java/com/app/appvenda/dao/ConfiguracaoDAO.java
|
UTF-8
| 2,440
| 2.140625
| 2
|
[] |
no_license
|
package com.app.appvenda.dao;
import android.content.Context;
import com.app.appvenda.entidade.Configuracao;
import com.app.appvenda.enums.EnumTipoConfiguracao;
import com.app.appvenda.modelos.MConfiguracao;
import com.app.appvenda.modelos.MEstoque;
import com.app.appvenda.repositorio.RPConfiguracao;
import com.app.bdframework.baseEntidade.Repositorio;
import com.app.bdframework.conversor.ConversorHelper;
/**
* Created by Robson on 03/12/2016.
*/
public class ConfiguracaoDAO extends BaseDAO<MConfiguracao, Configuracao> {
public ConfiguracaoDAO(Context context) {
super(context, Configuracao.class, MConfiguracao.class);
}
@Override
protected void posSalvar(Configuracao configuracao, String[] regrasIgnorar) {
}
@Override
protected void preDeletar(Configuracao configuracao, String[] regrasIgnorar) {
}
@Override
protected Repositorio<Configuracao> obterRepositorio(Context context) {
return new RPConfiguracao(context);
}
public MConfiguracao obterConfiguracao(EnumTipoConfiguracao tipoConfiguracao) {
Configuracao configuracao = this.repositorio.executarUnico(Configuracao.getTodasColunas(Configuracao.class), Configuracao.TIPO_CONFIG + " = ?", false, new String[]{
tipoConfiguracao.getNumVal().toString()
});
return ConversorHelper.converterParaDe(configuracao, MConfiguracao.class);
}
public MConfiguracao obterConfiguracaoAtiva() {
Configuracao configuracao = this.repositorio.executarUnico(Configuracao.getTodasColunas(Configuracao.class), Configuracao.PRINCIPAL + " = ?", false, new String[]{
"1"
});
return ConversorHelper.converterParaDe(configuracao, MConfiguracao.class);
}
public MConfiguracao obterConfiguracaoSecundaria() {
Configuracao configuracao = this.repositorio.executarUnico(Configuracao.getTodasColunas(Configuracao.class), Configuracao.PRINCIPAL + " = ?", false, new String[]{
"0"
});
return ConversorHelper.converterParaDe(configuracao, MConfiguracao.class);
}
public void transformarPrincipal(EnumTipoConfiguracao tipoConfiguracao) {
MConfiguracao mConfiguracao = obterConfiguracao(tipoConfiguracao);
if (mConfiguracao != null && !mConfiguracao.isPrincipal()) {
mConfiguracao.setPrincipal(true);
salvar(mConfiguracao, null);
}
}
}
| true
|
055f2ac3e8133d10e6294c8e4f56ef1d75ad3aa9
|
Java
|
eliseyles/DocFilling
|
/src/main/java/by/bntu/kharaneka/enrolleedocfillingmvp/repository/ContractRepository.java
|
UTF-8
| 401
| 1.945313
| 2
|
[] |
no_license
|
package by.bntu.kharaneka.enrolleedocfillingmvp.repository;
import by.bntu.kharaneka.enrolleedocfillingmvp.entity.Contract;
import by.bntu.kharaneka.enrolleedocfillingmvp.entity.Personality;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ContractRepository extends JpaRepository<Contract, Integer> {
public Contract findByPersonality(Personality personality);
}
| true
|
f39f552d97fd976ec75e1486f367cd653f4cc1f5
|
Java
|
zzjzhang/zzj-maven-redis
|
/src/main/java/com/core/App.java
|
UTF-8
| 556
| 2.109375
| 2
|
[] |
no_license
|
package com.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* GitHub: (示例代码)
* https://github.com/josiahcarlson/redis-in-action/tree/master/java/src/main/java
*
* 数据类型:
* 1. STRING
* 2. LIST
* 3. SET
* 4. HASH
* 5. ZSET
*
*/
@SpringBootApplication
public class App {
public static void main( String[] args ) {
SpringApplication.run(App.class, args);
System.out.println( "Hello World!" );
}
}
| true
|
003ae1a07b44b80f92e975d04054724ab4c3fa41
|
Java
|
shanghaif/supplychain
|
/rpc-supplychain-jst-api/src/main/java/cn/com/glsx/supplychain/jst/enums/LoginTypeEnum.java
|
UTF-8
| 381
| 2.046875
| 2
|
[] |
no_license
|
package cn.com.glsx.supplychain.jst.enums;
public enum LoginTypeEnum {
/**
* 手机号授权
*/
LOGIN_TYPE_PH("PH"),
/**
* 商户号密码
*/
LOGIN_TYPE_PS("PW");
String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
private LoginTypeEnum(String value) {
this.value = value;
}
}
| true
|
121bf7c99ea390d33ca594bf33db78b8c6660ee2
|
Java
|
AvocadosConstant/coding-competitions
|
/codecon-2015/codeCon3.java
|
UTF-8
| 2,063
| 3.46875
| 3
|
[] |
no_license
|
//Problem : Funny Elevators
//Language : Java
//Compiled Using : javac
//Version : Java 1.7.0_75
//Input for your program will be provided from STDIN
//Print out all output from your program to STDOUT
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
// THIS CODE IS NON-FUNCTIONAL
// RAN OUT OF TIME AND READ THE QUESTION INCORRECTLY
public class codeCon3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int floors = in.nextInt();
int e = in.nextInt();
int start = in.nextInt();
int end = in.nextInt();
int[][] elevators = new int[e][2];
int min = floors;
int max = 0;
for(int i = 0; i < e ; i ++) {
int a = in.nextInt();
int b = in.nextInt();
if(a < min) min = a;
if(b < min) min = b;
if(a > max) max = a;
if(b > max) max = b;
elevators[i][0] = (a<b) ? a : b;
elevators[i][1] = (a>b) ? a : b;
}
int lower = (start<end) ? start : end;
int higher = (start>end) ? start : end;
boolean possible = false;
while(higher - lower > 0) {
if(max < higher || min > lower) {
break;
}
boolean movedUp = false;
for(int i = e-1; i >= 0; i--) {
if(elevators[i][0] <= lower) {
lower = elevators[i][1];
movedUp = true;
//System.out.printf("lower : %d", lower);
if(lower >= higher) {
possible = true;
}
}
}
if(movedUp == false) {
//System.out.println("moved Up = false");
break;
}
}
String s = "HI";
if(possible) {
s = "1";
}
else {
s = "0";
}
System.out.println(s);
}
}
| true
|
04b36408ff46cb750d21edccf4f1b4095702f65b
|
Java
|
domivds/asquaretest
|
/service/src/main/java/zone/cogni/asquare/service/queryapi/filter/value/LatestDatePipe.java
|
UTF-8
| 2,575
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package zone.cogni.asquare.service.queryapi.filter.value;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.joda.time.DateTime;
import zone.cogni.asquare.access.ApplicationView.AttributeMatcher;
import zone.cogni.asquare.applicationprofile.model.basic.ApplicationProfile.Attribute;
import zone.cogni.asquare.rdf.RdfValue;
import zone.cogni.asquare.rdf.TypedResource;
import zone.cogni.asquare.service.queryapi.filter.AbstractDepthFilterPipe;
import javax.annotation.Nullable;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;
public class LatestDatePipe extends AbstractDepthFilterPipe implements ValueFilterPipe {
private final String attributeId;
private final String parentAttributeId;
@JsonCreator
public LatestDatePipe(
@JsonProperty(value = "startDepth") Integer startDepth,
@JsonProperty(value = "endDepth") Integer endDepth,
@JsonProperty(value = "attributeId", required = true) String attributeId,
@JsonProperty(value = "parentAttributeId") String parentAttributeId) {
super(startDepth, endDepth);
this.attributeId = attributeId;
this.parentAttributeId = parentAttributeId;
}
public LatestDatePipe(String attributeId, @Nullable String parentAttributeId) {
this.attributeId = attributeId;
this.parentAttributeId = parentAttributeId;
}
@Override
public <T extends RdfValue> Stream<T> filterStream(Attribute attribute, Stream<T> values) {
if (parentAttributeId != null && attribute == null) return values;
if (parentAttributeId != null && !attribute.getAttributeId().equals(parentAttributeId)) return values;
return values
// .filter(v -> ((TypedResource) v).getValue(attributeId) != null)
.max(compareDates())
.map(Stream::of)
.orElseGet(Stream::empty);
}
private <T extends RdfValue> Comparator<T> compareDates() {
return Comparator.comparing(v -> getDateValue((TypedResource) v, attributeId));
}
private DateTime getDateValue(TypedResource typedResource, String attribute) {
return Optional.ofNullable(typedResource.getValue(attribute))
.map(val -> ((RdfValue) val).getLiteral().getString())
.map(DateTime::parse)
.orElse(new DateTime(Long.MIN_VALUE));
}
@Override
public Optional<AttributeMatcher> asAttributeMatcher() {
return Optional.empty();
}
public String getAttributeId() {
return attributeId;
}
public String getParentAttributeId() {
return parentAttributeId;
}
}
| true
|
0e8f00c6f670bb18b60938f9e13511a71ead9f64
|
Java
|
jforge/vaadin
|
/uitest/src/test/java/com/vaadin/tests/components/datefield/DateTimeFieldPopupTest.java
|
UTF-8
| 2,725
| 1.929688
| 2
|
[
"CC-BY-ND-2.0",
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* 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.vaadin.tests.components.datefield;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.vaadin.testbench.By;
import com.vaadin.testbench.elements.DateTimeFieldElement;
import com.vaadin.tests.tb3.MultiBrowserTest;
public class DateTimeFieldPopupTest extends MultiBrowserTest {
@Test
public void testOpenCloseOpen_popupShouldBeOpen() throws Exception {
openTestURL();
WebElement toggleButton = $(DateTimeFieldElement.class).first()
.findElement(By.className("v-datefield-button"));
toggleButton.click();
assertThatPopupIsVisible();
toggleButton.click();
assertThatPopupIsInvisible();
// We should be able to immediately open the popup from the popup after
// clicking the button to close it. (#8446)
toggleButton.click();
assertThatPopupIsVisible();
}
private void assertThatPopupIsVisible() {
waitUntil(ExpectedConditions.visibilityOfElementLocated(
org.openqa.selenium.By.className("v-datefield-popup")));
}
private void assertThatPopupIsInvisible() {
// ExpectedConditions.invisibilityOfElementLocated doesn't work
// with PhantomJS when running with a hub:
// https://code.google.com/p/selenium/issues/detail?id=5000
// so we need to make our own.
waitUntil(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver input) {
try {
return !(findElement(org.openqa.selenium.By
.className("v-datefield-popup")).isDisplayed());
} catch (Exception e) {
return true;
}
}
@Override
public String toString() {
// Timed out after 10 seconds waiting for ...
return "popup to not be visible";
}
});
}
}
| true
|
177862f3a82aa58e96fbb4ea55febbc9778dbdbf
|
Java
|
devsystem123/MobileHHealth
|
/app/src/main/res/drawable/adapter/AdapterCursosPersonalizado.java
|
UTF-8
| 2,126
| 2.5
| 2
|
[] |
no_license
|
package br.com.alura.cursos.adapter;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import br.com.alura.cursos.R;
/**
* Created by alex on 02/07/17.
*/
public class AdapterCursosPersonalizado extends BaseAdapter {
private final List<br.com.alura.cursos.model.Curso> cursos;
private final Activity act;
public AdapterCursosPersonalizado(List<br.com.alura.cursos.model.Curso> cursos, Activity act) {
this.cursos = cursos;
this.act = act;
}
@Override
public int getCount() {
return cursos.size();
}
@Override
public Object getItem(int position) {
return cursos.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = act.getLayoutInflater().inflate(R.layout.lista_curso_personalizada, parent, false);
br.com.alura.cursos.model.Curso curso = cursos.get(position);
TextView nome = (TextView)
view.findViewById(R.id.lista_curso_personalizada_nome);
TextView descricao = (TextView)
view.findViewById(R.id.lista_curso_personalizada_descricao);
ImageView imagem = (ImageView)
view.findViewById(R.id.lista_curso_personalizada_imagem);
nome.setText(curso.getNome());
descricao.setText(curso.getDescricao());
br.com.alura.cursos.model.Categoria categoria = curso.getCategoria();
if (categoria.equals(br.com.alura.cursos.model.Categoria.JAVA)) {
imagem.setImageResource(R.drawable.java);
} else if (categoria.equals(br.com.alura.cursos.model.Categoria.ANDROID)) {
imagem.setImageResource(R.drawable.android);
} else if (categoria.equals(br.com.alura.cursos.model.Categoria.HTML)) {
imagem.setImageResource(R.drawable.html);
}
return view;
}
}
| true
|
c7749fea38ab09d6c0d981e16968a34575d8e936
|
Java
|
alex0730/blog_code_management
|
/src/main/java/com/lee/entity/RoleOperationModel.java
|
UTF-8
| 2,314
| 2.46875
| 2
|
[] |
no_license
|
package com.lee.entity;
import java.io.Serializable;
/**
* <p>Description: [角色操作权限关系表(对数据或资源的增删改查等)model]</p>
* Created on 2021年02月01日
* @author <a href="mailto: wuyingya@oristartech.com">吴迎亚</a>
* @version 1.0
*/
public class RoleOperationModel implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键Id
*/
private Integer id;
/**
* role表业务主键
*/
private String roleWorkId;
/**
* menu表业务住家
*/
private String operationWorkId;
/**
* 角色操作权限关系(0:启用;1:停用;默认:0)
*/
private Integer roleOperationStatus;
// setter and getter
/**
* <p>Discription:[主键Id]</p>
* Created on 2021年02月01日
* @return Integer
* @author:吴迎亚
*/
public Integer getId(){
return id;
}
/**
* <p>Discription:[主键Id]</p>
* Created on 2021年02月01日
* @author:吴迎亚
*/
public void setId(Integer id){
this.id = id;
}
/**
* <p>Discription:[role表业务主键]</p>
* Created on 2021年02月01日
* @return String
* @author:吴迎亚
*/
public String getRoleWorkId(){
return roleWorkId;
}
/**
* <p>Discription:[role表业务主键]</p>
* Created on 2021年02月01日
* @author:吴迎亚
*/
public void setRoleWorkId(String roleWorkId){
this.roleWorkId = roleWorkId;
}
/**
* <p>Discription:[menu表业务住家]</p>
* Created on 2021年02月01日
* @return String
* @author:吴迎亚
*/
public String getOperationWorkId(){
return operationWorkId;
}
/**
* <p>Discription:[menu表业务住家]</p>
* Created on 2021年02月01日
* @author:吴迎亚
*/
public void setOperationWorkId(String operationWorkId){
this.operationWorkId = operationWorkId;
}
/**
* <p>Discription:[角色操作权限关系(0:启用;1:停用;默认:0)]</p>
* Created on 2021年02月01日
* @return Integer
* @author:吴迎亚
*/
public Integer getRoleOperationStatus(){
return roleOperationStatus;
}
/**
* <p>Discription:[角色操作权限关系(0:启用;1:停用;默认:0)]</p>
* Created on 2021年02月01日
* @author:吴迎亚
*/
public void setRoleOperationStatus(Integer roleOperationStatus){
this.roleOperationStatus = roleOperationStatus;
}
}
| true
|
0fd9f909908c182fc438b5f4caab99645c5f1612
|
Java
|
Akshay790/java-Exception
|
/Checked/Demo.java
|
UTF-8
| 411
| 2.359375
| 2
|
[] |
no_license
|
package Checked;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Demo {
public static void main(String[] args)
{
try {
FileInputStream fs=new FileInputStream("d://data.text");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int i=10,m=4;
int c=i+m;
System.out.println("ADD :"+c);
}
}
| true
|
c2c85424aba1c929108dccca92ab25514ba6b0dc
|
Java
|
lm50666/dronkaShopNew
|
/pl/edu/agh/dronka/shop/model/Category.java
|
UTF-8
| 340
| 2.625
| 3
|
[] |
no_license
|
package pl.edu.agh.dronka.shop.model;
public enum Category {
BOOKS("Books"), ELECTRONICS("Electronics"), FOOD("Food"), MUSIC("Music"), SPORT("Sport");
private String displayName;
public String getDisplayName() {
return displayName;
}
private Category(String displayName) {
this.displayName = displayName;
}
}
| true
|
0f1249fdcf46a904b7c789707a52fb5eea1c0b46
|
Java
|
Undergrounder/neusta-code-challenge-2017
|
/facades/src/main/java/de/neustasd/roomsmanager/facades/imprt/converter/impl/CsvImportDataConverterImpl.java
|
UTF-8
| 1,520
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package de.neustasd.roomsmanager.facades.imprt.converter.impl;
import de.neustasd.roomsmanager.core.services.converters.ConverterUtils;
import de.neustasd.roomsmanager.core.services.data.ImportData;
import de.neustasd.roomsmanager.core.services.data.RoomData;
import de.neustasd.roomsmanager.facades.imprt.converter.CsvImportDataConverter;
import de.neustasd.roomsmanager.facades.imprt.converter.CsvRoomDataConverter;
import de.neustasd.roomsmanager.facades.imprt.csv.parser.data.CsvImportData;
import de.neustasd.roomsmanager.facades.imprt.csv.parser.data.CsvRoomData;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/** Created by Adrian Tello on 09/12/2017. */
@Component
public class CsvImportDataConverterImpl implements CsvImportDataConverter {
private final CsvRoomDataConverter csvRoomDataConverter;
@Autowired
public CsvImportDataConverterImpl(final CsvRoomDataConverter csvRoomDataConverter) {
this.csvRoomDataConverter = csvRoomDataConverter;
}
@Override
public ImportData convert(final CsvImportData source) throws ConversionException {
final List<CsvRoomData> sourceRoomDataList = source.getRoomDataList();
final List<RoomData> roomDataList =
ConverterUtils.convertAll(sourceRoomDataList, getCsvRoomDataConverter());
return ImportData.builder().roomDataList(roomDataList).build();
}
private CsvRoomDataConverter getCsvRoomDataConverter() {
return csvRoomDataConverter;
}
}
| true
|
b890605ce115057de1c32825e803d0b078f1f833
|
Java
|
tghising/shop-model-simulator
|
/src/shopmodelsimulator/IScheduler.java
|
UTF-8
| 277
| 2.484375
| 2
|
[] |
no_license
|
package shopmodelsimulator;
/**
* IScheduler interface is implements by simulation to schedule(add new events) on the basis of event occur time
*
* @author tghising
*/
public interface IScheduler {
// method to schedule the event
public void schedule(Event e);
}
| true
|
5f2dbfa719e650ad30c9b0bce931f85a08f081a8
|
Java
|
Marcos3yk/Projeto-Vetra
|
/src/telascontroller/OrcamentoController.java
|
UTF-8
| 13,433
| 2.09375
| 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 telascontroller;
import DAO.PessoaDAOImpl;
import DAO.VeiculoDAOImpl;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import model.Orcamento;
import model.Pessoa;
import model.Veiculo;
import org.controlsfx.control.Notifications;
/**
* FXML Controller class
*
* @author MarcosVinicius
*/
public class OrcamentoController implements Initializable {
@FXML
private TextField tfNome, tfModelo, tfPlaca, tfEmail, tfCidade, tfNumero, tfCpfCnpj, tfComplemento;
@FXML
private TextField tfBairro, tfValor, tfRua, tfFone, tfValidade;
@FXML TextArea taServico;
@FXML
private ComboBox cbEstado, cbMarca;
@FXML DatePicker dpData;
@FXML ImageView imgRelatorio;
@FXML Label lbAviso;
boolean valida = true;
PessoaDAOImpl pesDao;
Pessoa pessoa;
VeiculoDAOImpl veiDao;
Veiculo veiculo;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
return dateFormat.format(date);
}
Orcamento orc = new Orcamento();
@FXML
private void gerarOrcamento(ActionEvent event){
orc.setNome(tfNome.getText());
orc.setCpfCnpj(tfCpfCnpj.getText());
orc.setEmail(tfEmail.getText());
orc.setRua(tfRua.getText());
orc.setCidade(tfCidade.getText());
orc.setComplemento(tfComplemento.getText());
orc.setNumero(tfNumero.getText());
orc.setBairro(tfBairro.getText());
orc.setDescrição(taServico.getText());
orc.setPlaca(tfPlaca.getText());
orc.setModelo(tfModelo.getText());
orc.setMarca(cbMarca.getValue().toString());
orc.setEstado(cbEstado.getValue().toString());
orc.setData(dpData.getValue().toString());
orc.setValor(Double.parseDouble(tfValor.getText()));
orc.setFone(tfFone.getText());
orc.setValidade(tfValidade.getText());
try {
gerarPDF(orc);
Notifications.create().title("Sucesso").position(Pos.CENTER).text("Orçamento gerado com sucesso!").showInformation();
//lbAviso.setVisible(true);
} catch (DocumentException ex) {
Logger.getLogger(OrcamentoController.class.getName()).log(Level.SEVERE, null, ex);
lbAviso.setText("Deu erro");
lbAviso.setVisible(true);
} catch (IOException ex) {
Logger.getLogger(OrcamentoController.class.getName()).log(Level.SEVERE, null, ex);
lbAviso.setText("Deu erro 2");
lbAviso.setVisible(true);
}
}
public void gerarPDF(Orcamento orc) throws FileNotFoundException, DocumentException, IOException{
Document doc = null;
OutputStream os = null;
try {
Date data = new Date();
//cria o documento tamanho A4, margens de 2,54cm
doc = new Document(PageSize.A4, 72, 72, 72, 72);
//cria a stream de saída
os = new FileOutputStream("Orçamento "+orc.getNome()+".pdf");
//associa a stream de saída ao
PdfWriter.getInstance(doc, os);
//abre o documento
doc.open();
//adiciona o texto ao PDF
Image img = Image.getInstance("C:\\Users\\MarcosVinicius\\Desktop\\TCC\\ProjetoVetra\\src\\icones\\vetra2.jpg");
img.setAlignment(Element.ALIGN_LEFT);
doc.add(img);
Font f = new Font(FontFamily.TIMES_ROMAN, 22, Font.BOLD);
Paragraph p1 = new Paragraph("Vetra Veiculos Transformados.", f);
doc.add(p1);
p1.setSpacingAfter(20);
Paragraph p3 = new Paragraph("Endereço: Rua Coronel Camisão, 17 A");
doc.add(p3);
p3.setSpacingBefore(20);
Paragraph p4 = new Paragraph("Bairro: Bairro Amambaí - Campo Grande-MS.");
doc.add(p4);
p4.setSpacingBefore(20);
Paragraph p5 = new Paragraph("Fone: (67)3044 6541 Email: vetra.veiculostransformados@gmail.com ");
doc.add(p5);
Paragraph p6 = new Paragraph("___________________________________________________________________");
doc.add(p6);
//Paragraph p2 = new Paragraph("Data: "+getDateTime());
//doc.add(p2);
//Paragraph p2_1 = new Paragraph("CPF/CNPJ: "+orc.getCpfCnpj());
//p2_1.setAlignment(Element.ALIGN_CENTER);
Paragraph p6_1 = new Paragraph("Proposta de Orçamento");
p6_1.setAlignment(Element.ALIGN_CENTER);
doc.add(p6_1);
Paragraph p6_3 = new Paragraph("Dados do Cliente");
doc.add(p6_3);
Paragraph p6_2 = new Paragraph("Data: "+getDateTime()+ " CPF/CNPJ: "+orc.getCpfCnpj()+"\n"
+ "Nome: "+orc.getNome()+" Email: "+orc.getEmail()+" \n"
+ "Endereço: "+orc.getRua()+" Complemento: "+orc.getComplemento());
p6_2.setSpacingBefore(20);
p6_2.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
doc.add(p6_2);
Paragraph p7 = new Paragraph("Bairro: "+orc.getBairro()+" Numero: "+orc.getNumero()+"\n"
+ " Cidade: "+orc.getCidade()+" Estado: "+orc.getEstado());
p7.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
doc.add(p7);
Paragraph p7_1 = new Paragraph("Telefone: "+orc.getFone());
doc.add(p7_1);
Paragraph p8 = new Paragraph("___________________________________________________________________");
doc.add(p8);
Paragraph p9 = new Paragraph("Dados do Serviço");
p9.setSpacingBefore(10);
p9.setSpacingAfter(20);
doc.add(p9);
Paragraph p9_1 = new Paragraph("Veiculo: "+orc.getModelo()+ " Marca: "+orc.getMarca());
p9_1.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
doc.add(p9_1);
Paragraph p9_2 = new Paragraph("Placa: "+orc.getPlaca());
doc.add(p9_2);
Paragraph p9_3 = new Paragraph("Descrição do Serviço: "+orc.getDescrição());
doc.add(p9_3);
Paragraph p10 = new Paragraph("Validade deste Orçamento: "+orc.getValidade()+" Valor do Serviço: R$ "+orc.getValor());
p10.setAlignment(Element.ALIGN_JUSTIFIED_ALL);
doc.add(p10);
Paragraph p10_1 = new Paragraph("Previsão de Término: "+orc.getData());
p10_1.setSpacingAfter(80);
doc.add(p10_1);
Paragraph p11 = new Paragraph("______________________________");
p11.setAlignment(Element.ALIGN_CENTER);
doc.add(p11);
Paragraph p12 = new Paragraph("Vetra Veiculos Transformados");
p12.setAlignment(Element.ALIGN_CENTER);
doc.add(p12);
} finally {
if (doc != null) {
//fechamento do documento
doc.close();
}
if (os != null) {
//fechamento da stream de saída
os.close();
}
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
valida = false;
cbEstado.setValue("Selecione");
cbMarca.setValue("Selecione");
tfCpfCnpj.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
pesDao = new PessoaDAOImpl();
pessoa = new Pessoa();
try {
pessoa = pesDao.buscarPorId(tfCpfCnpj.getText());
} catch (Exception e) {
}
if(pessoa != null){
//Notifications.create().title("Aviso").position(Pos.CENTER).text("CPF/CNPJ ja cadastrado no sistema!").showInformation();
populaDadosCliente(pessoa);
}
}
});
tfNome.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
pesDao = new PessoaDAOImpl();
pessoa = new Pessoa();
try {
pessoa = pesDao.buscarPorId(tfCpfCnpj.getText());
} catch (Exception e) {
}
if(pessoa != null){
//Notifications.create().title("Aviso").position(Pos.CENTER).text("CPF/CNPJ ja cadastrado no sistema!").showInformation();
populaDadosCliente(pessoa);
}
}
});
tfPlaca.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
veiDao = new VeiculoDAOImpl();
veiculo = new Veiculo();
try {
veiculo = veiDao.buscarPorPlaca(tfPlaca.getText());
} catch (Exception e) {
}
if(veiculo != null){
//Notifications.create().title("Aviso").position(Pos.CENTER).text("CPF/CNPJ ja cadastrado no sistema!").showInformation();
populaDadosVeiculo(veiculo);
}
}
});
cbMarca.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
veiDao = new VeiculoDAOImpl();
veiculo = new Veiculo();
try {
veiculo = veiDao.buscarPorPlaca(tfPlaca.getText());
} catch (Exception e) {
}
if(veiculo != null){
//Notifications.create().title("Aviso").position(Pos.CENTER).text("CPF/CNPJ ja cadastrado no sistema!").showInformation();
populaDadosVeiculo(veiculo);
}
}
});
}
public void populaDadosCliente(Pessoa pessoa){
tfNome.setText(pessoa.getNomerazaoSocial());
tfEmail.setText(pessoa.getEmail());
if(pessoa.getTelefone() == null){
tfFone.setText(pessoa.getCelular());
}else{
tfFone.setText(pessoa.getTelefone());
}
tfRua.setText(pessoa.getEndereco().getRua());
tfCidade.setText(pessoa.getEndereco().getCidade());
tfBairro.setText(pessoa.getEndereco().getBairro());
tfNumero.setText(Integer.toString(pessoa.getEndereco().getNumero()));
cbEstado.setValue(pessoa.getEndereco().getEstado());
if(pessoa.getEndereco().getComplemento() != null){
tfComplemento.setText(pessoa.getEndereco().getComplemento());
}
}
public void populaDadosVeiculo(Veiculo veiculo){
tfPlaca.setText(veiculo.getPlaca());
tfModelo.setText(veiculo.getNomeVeiculo());
cbMarca.setValue(veiculo.getMarca());
}
}
| true
|
d5b6308c08516e310b1d0cfaa51f7d7accec3355
|
Java
|
threeoldman/com.maikun.service.product
|
/src/main/java/com/maikun/service/buyer/restaurant/Restaurant.java
|
UTF-8
| 932
| 1.984375
| 2
|
[] |
no_license
|
package com.maikun.service.buyer.restaurant;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @program: products
* @Description: 饭店详细信息
* @author: Mr.Cheng
* @date: 2018/9/5 下午5:29
*/
@Data
public class Restaurant implements Serializable {
private static final long serialVersionUID = 4756892740316205407L;
private String restaurantId;
/** 餐厅名字. */
private String restaurantName;
/** 餐厅描述. */
private String restaurantDescription;
/** 餐厅缩略图. */
private String restaurantIcon;
/** 餐厅地址. */
private String restaurantAddress;
/** 餐厅营业时间. */
private String shopHours;
/** 餐厅联系方式. */
private String phone;
/** 餐厅周围环境. */
private List<String> restaurantEnvironment;
/** 餐厅资质. */
private List<String> restaurantCredentials;
}
| true
|
92697be3912e5b3e39771638f3253722058288e5
|
Java
|
Abrar051/ArrayList
|
/ArrayList-master/VectorPractice/VectorPractice.java
|
UTF-8
| 394
| 2.828125
| 3
|
[] |
no_license
|
package VectorPractice;
import java.util.Vector;
import java.util.*;
public class VectorPractice {
public static void main (String args[])
{
Vector obj = new Vector();
ArrayList obj1 = new ArrayList();
obj.add("1");
obj.add(34);
obj1.add("string");
obj1.add(23);
System.out.println(obj);
System.out.println(obj1);
}
}
| true
|
ca46574e742ab7e953ebfc8465acd632f0cf1b1e
|
Java
|
danteidbratt/GymSystem
|
/PT_App/Models/Note.java
|
UTF-8
| 587
| 2.46875
| 2
|
[] |
no_license
|
package Models;
public class Note {
private String comment;
private IndividualSession individualSession;
public Note() {
individualSession = new IndividualSession();
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public IndividualSession getIndividualSession() {
return individualSession;
}
public void setIndividualSession(IndividualSession individualSession) {
this.individualSession = individualSession;
}
}
| true
|
992324c9c1183e9a02485a0fbd4429ddd3762710
|
Java
|
jefferson-fidencio/FamilystRestAPI
|
/src/main/java/api/resources/UsuariosResources.java
|
UTF-8
| 4,023
| 2.59375
| 3
|
[] |
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 api.resources;
import api.model.Usuario;
import database.DAO.UsuarioDAO;
import interfaces.api.resources.IUsuariosResources;
import java.net.URI;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
*
* @author jdfid
*/
@Path("usuarios")
public class UsuariosResources implements IUsuariosResources {
@GET
@Path("{idUsuario}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Override
public Response buscarUsuario(@PathParam("idUsuario") int idUsuario) {
try {
Usuario usuario = new UsuarioDAO().buscarUsuario(idUsuario);
return Response.status(Response.Status.OK).entity(usuario).build();
} catch (Exception e) {
switch (e.getMessage())
{
//CODE 404
case "Usuario nao encontrado.":
return Response.status(Response.Status.NOT_FOUND).build();
//CODE 500
default:
return Response.serverError().entity(e.getMessage()).build();
}
}
}
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Override
public Response inserirUsuario(Usuario usuario){
try {
int idUsuario = new UsuarioDAO().inserirUsuario(usuario);
URI insertUri = new URI("/" + idUsuario);
//CODE 201
return Response.created(insertUri).build();
} catch (Exception e) {
switch (e.getMessage())
{
//CODE 409
case "Recurso já existente na base.":
return Response.status(Response.Status.CONFLICT).entity("Email já cadastrado.").build();
//CODE 500
default:
return Response.serverError().entity(e.getMessage()).build();
}
}
}
@PUT
@Path("{idUsuario}")
@Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
@Override
public Response editarUsuario(@PathParam("idUsuario") Integer idUsuario, Usuario usuario) {
try {
new UsuarioDAO().editarUsuario(idUsuario, usuario);
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
switch (e.getMessage())
{
//CODE 404
case "Usuario nao encontrado.":
return Response.status(Response.Status.NOT_FOUND).build();
//CODE 204
case "Usuario nao alterado.":
return Response.status(Response.Status.NO_CONTENT).build();
//CODE 500
default:
return Response.serverError().entity(e.getMessage()).build();
}
}
}
@DELETE
@Path("{idUsuario}")
@Override
public Response removerUsuario(@PathParam("idUsuario") Integer idUsuario) {
UsuarioDAO usuarioDAO = new UsuarioDAO();
try {
usuarioDAO.removerUsuario(idUsuario);
return Response.status(Response.Status.OK).build();
} catch (Exception e) {
switch (e.getMessage())
{
//CODE 404
case "Usuario nao encontrado.":
return Response.status(Response.Status.NOT_FOUND).build();
//CODE 500
default:
return Response.serverError().entity(e.getMessage()).build();
}
}
}
}
| true
|
14cd5dab6f3dd26e41564ef4a1348a595390e71c
|
Java
|
Urtar/VetClinic
|
/src/main/java/pl/coderslab/entity/Visit.java
|
UTF-8
| 1,765
| 2.5625
| 3
|
[] |
no_license
|
package pl.coderslab.entity;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
import java.util.List;
@Entity
public class Visit {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private LocalDateTime dateOfVisit;
private LocalDateTime updated;
@NotEmpty
private String description;
@OneToMany(mappedBy = "visit")
private List<Recipe> recipes;
@ManyToOne
private Vet vet;
@ManyToOne
private Pet pet;
public Visit() {
}
@PrePersist
public void prePersist() {
dateOfVisit = LocalDateTime.now();
}
@PreUpdate
public void preUpdate() {updated = LocalDateTime.now();}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public LocalDateTime getDateOfVisit() {
return dateOfVisit;
}
public void setDateOfVisit(LocalDateTime dateOfVisit) {
this.dateOfVisit = dateOfVisit;
}
public LocalDateTime getUpdated() {
return updated;
}
public void setUpdated(LocalDateTime updated) {
this.updated = updated;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Recipe> getRecipes() {
return recipes;
}
public void setRecipes(List<Recipe> recipes) {
this.recipes = recipes;
}
public Vet getVet() {
return vet;
}
public void setVet(Vet vet) {
this.vet = vet;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
}
| true
|
e8fc9106992ffd9d6950a27fdfbedc6951817bba
|
Java
|
tferenc/Plage-inc.
|
/server/ServerTest.java
|
UTF-8
| 211
| 1.6875
| 2
|
[] |
no_license
|
package server;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) {
}
}
| true
|
68118fa54836ab8166dcceb5e4dce55c462b1b97
|
Java
|
janaldous/offspringy
|
/src/main/java/com/janaldous/offspringy/business/activity/EventFullException.java
|
UTF-8
| 199
| 1.882813
| 2
|
[] |
no_license
|
package com.janaldous.offspringy.business.activity;
@SuppressWarnings("serial")
public class EventFullException extends Exception {
public EventFullException() {
super("Event is full");
}
}
| true
|
7fc0d843dc3aac8c5e7028175a9acdfdd18c15c2
|
Java
|
codebbgr/cbbini4j
|
/src/main/java/gr/codebb/cbbini4j/spi/IniBuilder.java
|
UTF-8
| 917
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2013-2020
* codebb.gr
*/
/**
* Changelog ========= 04/04/2020 (gmoralis) - Change "AbstractProfileBuilder" members visibility
* correspondingly 03/04/2020 (gmoralis) - Initial commit from ini4j project
*/
package gr.codebb.cbbini4j.spi;
import gr.cobebb.cbbini4j.Config;
import gr.cobebb.cbbini4j.Ini;
import gr.cobebb.cbbini4j.Profile;
public class IniBuilder extends AbstractProfileBuilder implements IniHandler {
private Ini _ini;
public static IniBuilder newInstance(Ini ini) {
IniBuilder instance = newInstance();
instance.setIni(ini);
return instance;
}
public void setIni(Ini value) {
_ini = value;
}
@Override
protected Config getConfig() {
return _ini.getConfig();
}
@Override
protected Profile getProfile() {
return _ini;
}
private static IniBuilder newInstance() {
return ServiceFinder.findService(IniBuilder.class);
}
}
| true
|
82dfe04636331308be414299162ba641b04b7581
|
Java
|
felipef78/school-homework-java
|
/ft045_MST/src/ft045_mst/Edge.java
|
UTF-8
| 1,083
| 3.265625
| 3
|
[] |
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 ft045_mst;
/**
*
* @author Felipe
*/
class Edge implements Comparable<Edge>{
private Node no1;
private Node no2;
private double dist;
public Edge(Node no1, Node no2, double dist) {
this.no1 = no1;
this.no2 = no2;
this.dist = dist;
}
public Node getNo1() {
return no1;
}
public void setNo1(Node no1) {
this.no1 = no1;
}
public Node getNo2() {
return no2;
}
public void setNo2(Node no2) {
this.no2 = no2;
}
public double getDist() {
return dist;
}
public void setDist(double dist) {
this.dist = dist;
}
@Override
public int compareTo(Edge o) {
if(this.dist == o.getDist()){
return 0;
}
if(this.dist < o.getDist()){
return -1;
}else{
return 1;
}
}
}
| true
|
088de1faa1f504b7667a4491b4b5a13601800416
|
Java
|
deepakot/RopoTest
|
/app/src/main/java/com/deepak/roposotest/Models/StoryData.java
|
UTF-8
| 3,258
| 2.390625
| 2
|
[] |
no_license
|
package com.deepak.roposotest.Models;
/**
* Created by Sharma on 5/16/2016.
*/
public class StoryData {
private String description;
private String id;
private String url;
private String verb;
private String db;
private String si;
private String type;
private String title;
private boolean like_flag;
private int likes_count;
private int comment_count;
private boolean is_following;
private int[] liked,comment,commented;
public StoryData() {
}
public StoryData(String description, String id, String url, String verb, String db, String si, String type, String title, boolean like_flag, int likes_count, int comment_count,boolean is_following) {
this.description = description;
this.id = id;
this.verb = verb;
this.db = db;
this.si = si;
this.type = type;
this.url = url;
this.title = title;
this.like_flag = like_flag;
this.likes_count = likes_count;
this.comment_count = comment_count;
this.is_following = is_following;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getVerb() {
return verb;
}
public void setVerb(String verb) {
this.verb = verb;
}
public String getDb() {
return db;
}
public void setDb(String db) {
this.db = db;
}
public String getSi() {
return si;
}
public void setSi(String si) {
this.si = si;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isLike_flag() {
return like_flag;
}
public void setLike_flag(boolean like_flag) {
this.like_flag = like_flag;
}
public int getLikes_count() {
return likes_count;
}
public void setLikes_count(int likes_count) {
this.likes_count = likes_count;
}
public int getComment_count() {
return comment_count;
}
public void setComment_count(int comment_count) {
this.comment_count = comment_count;
}
public boolean is_following() {
return is_following;
}
public void setIs_following(boolean is_following) {
this.is_following = is_following;
}
public int[] getLiked() {
return liked;
}
public void setLiked(int[] liked) {
this.liked = liked;
}
public int[] getComment() {
return comment;
}
public void setComment(int[] comment) {
this.comment = comment;
}
public int[] getCommented() {
return commented;
}
public void setCommented(int[] commented) {
this.commented = commented;
}
}
| true
|
3465c3b174f54d5f54e9e6690de634582df25853
|
Java
|
mikhaylov97/ZombieLandGame
|
/src/main/java/com/zombieland/source/controller/CommonController.java
|
UTF-8
| 289
| 1.601563
| 2
|
[] |
no_license
|
package com.zombieland.source.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class CommonController {
@GetMapping("/")
public String getGameMainPage() {
return "index";
}
}
| true
|
11cd28586eb4d771a28d9907537b72f609429489
|
Java
|
Girish-93/AutomationProject
|
/src/SeleniumSessions/ExtraLocators.java
|
UTF-8
| 1,123
| 2.171875
| 2
|
[] |
no_license
|
package SeleniumSessions;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class ExtraLocators {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\91821\\Downloads\\chrome v-83\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();// launch chrome
driver.get("https://www.facebook.com");
//
// driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//
// driver.findElement(new ByAll(By.name("firstname12"),By.id("u_0_m12"),By.xpath("//input[@id='u_0_m']"))).sendKeys("girish");
// driver.findElement(new ByIdOrName("firstname")).sendKeys("girish");
driver.findElement(new ByChained(By.id("u_0_l"),By.xpath("//div[@class='uiStickyPlaceholderInput uiStickyPlaceholderEmptyInput']"),
By.name("firstname"))).sendKeys("girish");
}
}
| true
|
ae83c7f4ee37e8ba8c42bc94ba6c3949145e8581
|
Java
|
katfish125/ctci
|
/ch2/src/RemoveDups.java
|
UTF-8
| 1,383
| 3.328125
| 3
|
[] |
no_license
|
import java.util.HashSet;
public class RemoveDups {
public static void main(String[] args) {
LinkedList test = new LinkedList(0);
test.append(0);
test.append(1);
test.append(2);
test.append(2);
test.append(3);
test.append(3);
test.append(3);
test.append(4);
removeDups(test);
// removeDupsNoBuffer(test);
test.printAll();
}
// before learning how to implement hash
private static void removeDupsNoBuffer(LinkedList test) {
Node currOne = test.head;
while (currOne != null) {
Node find = currOne.next;
while (find != null) {
if (currOne.data == find.data) {
test.remove(currOne.data);
break;
}
find = find.next;
}
currOne = currOne.next;
}
}
// with hash set
private static void removeDups(LinkedList test) {
HashSet seen = new HashSet();
Node currOne = test.head;
while (currOne != null) {
if (seen.contains(currOne.data)) {
test.remove(currOne.data);
}
else {
seen.add(currOne.data);
}
currOne = currOne.next;
}
}
}
| true
|
f734b09d9ad370a91f375abf91c3335e2778fb7c
|
Java
|
jmatheuss/indra-jpa
|
/desafio-back/src/main/java/com/indracompany/desafio/repositories/MunicipioRepository.java
|
UTF-8
| 553
| 2.015625
| 2
|
[] |
no_license
|
package com.indracompany.desafio.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.indracompany.desafio.domain.Municipio;
@Repository
public interface MunicipioRepository extends JpaRepository<Municipio, Long>{
@Query("SELECT m FROM Municipio m WHERE descricao = :nomeMunicipio")
public Municipio findByNome(@Param("nomeMunicipio") String nome);
}
| true
|
a22aaf26b23758c0013948ec560b9deb63a9ee2d
|
Java
|
1054522381/my-jpa-demos
|
/my-jpa-demo01-simple-crud/src/test/java/cn/com/fubon/entity/EmployeeTest.java
|
UTF-8
| 6,599
| 2.859375
| 3
|
[] |
no_license
|
package cn.com.fubon.entity;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* 单表增删改查
*/
public class EmployeeTest {
private EntityManager manager;
private EntityManagerFactory factory;
@Before
public void setup(){
Map<String,Object> properties = new HashMap<>();
properties.put("hibernate.show_sql", true);
factory = Persistence.createEntityManagerFactory("unit1", properties);
//factory = Persistence.createEntityManagerFactory("unit1");
manager = factory.createEntityManager();
}
@After
public void teardown(){
if(manager != null){
manager.close();
}
factory.close();
}
/**
* 查看自动生成的表
*/
@Test
public void createTable() {
}
@Test
public void testInsert() {
Employee employee = new Employee();
employee.setType(EmployeeType.FULL_TIME_EMPLOYEE);
manager.getTransaction().begin();
manager.persist(employee);
manager.getTransaction().commit();
System.out.println(String.format("id==>%s,type==>%s",employee.getId(),employee.getType()));
}
/*
* persist一个已经是持久化状态的对象,会什么也不做,不会产生insert或者update。
*/
@Test
public void testPersist1() {
Employee employee = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
manager.persist(employee);
manager.getTransaction().commit();
}
/*
* persist一个游离状态的对象,有id,但没有和持久化上下文关联。
*/
@Test
public void testPersist2() {
Employee employee = new Employee();
employee.setId(2L);
employee.setType(EmployeeType.PART_TIME_EMPLOYEE);
manager.getTransaction().begin();
manager.persist(employee); //会抛异常javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cn.com.fubon.entity.Employee
manager.getTransaction().commit();
}
/*
* persist一个删除状态的对象。先remove,不提交,再persist,转成持久化状态。
*/
@Test
public void testPersist3() {
Employee employee = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
manager.remove(employee);
manager.persist(employee);
System.out.println("--------type-------" + employee.getType());
employee.setType(EmployeeType.PART_TIME_EMPLOYEE);
manager.getTransaction().commit();
}
@Test
public void testUpdate() {
Employee employee = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
employee.setType(EmployeeType.CONTRACT_EMPLOYEE);
manager.getTransaction().commit();
System.out.println(String.format("type==>%s", employee.getType()));
}
@Test
public void testFindById() {
Employee employee = manager.find(Employee.class, 1L);
System.out.println("--------------------");
System.out.println(String.format("class==>%s,type==>%s",employee.getClass().getName(), employee.getType()));
}
/**
* 查不到记录会抛异常,返回的是代理对象
*/
@Test
public void testGetReferenceById() {
Employee employee = manager.getReference(Employee.class, 1L);
// manager.close(); //org.hibernate.LazyInitializationException: could not initialize proxy - no Session
System.out.println("--------------------");
System.out.println(String.format("class==>%s,type==>%s",employee.getClass().getName(), employee.getType()));
}
@Test
public void testRemove() {
Employee employee = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
manager.remove(employee);
manager.getTransaction().commit();
}
/**
* new对象merge入库会返回一个带有id的新对象
*/
@Test
public void testMergeNew() {
Employee employee1 = new Employee();
employee1.setType(EmployeeType.PART_TIME_EMPLOYEE);
manager.getTransaction().begin();
Employee employee2 = manager.merge(employee1);
manager.getTransaction().commit();
System.out.println(
String.format("employee1.id==>%s,employee2.id==>%s",employee1.getId(),employee2.getId()));
}
/**
* 游离(脱管)对象merge:
* manager缓存中不存在且数据库中不存在时,会根据该游离对象复制一个新的对象做insert;
* 比如,该测试中的employee1.id=100L并不会被持久化。
*/
@Test
public void testMergeDetachedNotExistsInDBAndCache() {
Employee employee1 = new Employee();
employee1.setType(EmployeeType.PART_TIME_EMPLOYEE);
employee1.setId(100L);
manager.getTransaction().begin();
Employee employee2 = manager.merge(employee1);
manager.getTransaction().commit();
System.out.println(
String.format("employee1.id==>%s,employee2.id==>%s",employee1.getId(),employee2.getId()));
}
/**
* 游离(脱管)对象merge:
* manager缓存中不存在但数据库中存在时,会查询该游离对象复制该游离对象的属性做update;
*/
@Test
public void testMergeDetachedNotExistsInCache() {
Employee employee1 = new Employee();
employee1.setType(EmployeeType.CONTRACT_EMPLOYEE);
employee1.setId(1L);
manager.getTransaction().begin();
Employee employee2 = manager.merge(employee1);
manager.getTransaction().commit();
System.out.println("==>" + (employee1 == employee2));
}
/**
* 游离(脱管)对象merge:
* manager缓存中存在对应的游离对象,会复制该游离对象至缓存对象,对缓存对象做update;
*/
@Test
public void testMergeDetachedExistsInCache() {
Employee employee1 = new Employee();
employee1.setType(EmployeeType.PART_TIME_EMPLOYEE);
employee1.setId(1L);
Employee employee2 = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
manager.merge(employee1);
manager.getTransaction().commit();
System.out.println("==>" + (employee1 == employee2));
}
@Test
public void testFlush(){
Employee employee = manager.find(Employee.class, 1L);
manager.getTransaction().begin();
employee.setType(EmployeeType.FULL_TIME_EMPLOYEE);
manager.flush(); //flush在事务提交之前会发出 update SQL
System.out.println("----------------");
manager.getTransaction().commit(); //正常是在事务提交的时候发出 update SQL
}
/**
* 由于存在一级缓存只会发一条查询SQL,refresh的话会多发一条。
*/
@Test
public void testRefresh(){
Employee employee = manager.find(Employee.class, 1L);
employee = manager.find(Employee.class, 1L);
System.out.println("-------------------");
manager.refresh(employee);
}
}
| true
|
eb4437be438cfa60b65e975de259c336d6173033
|
Java
|
leqianbao/leqianbao
|
/src/cn/lc/dao/FinanceDao.java
|
UTF-8
| 5,307
| 2.375
| 2
|
[] |
no_license
|
package cn.lc.dao;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.lc.beans.Finance;
import cn.lc.beans.OrderDetial;
import cn.lc.beans.Pager;
public class FinanceDao {
QueryRunner qR = new QueryRunner();
//@APP--购买理财产品
public boolean addFinance(Finance f){
boolean result = false;
Connection connection = null;
try {
connection = DBUtils.getConnection();
String sql = "INSERT INTO lc_finance (finance_num,finance_money,user_id,product_id,created_by,stamp_created,updated_by,stamp_updated,state) VALUES (?,?,?,?,?,?,?,?,?)";
String sql2 = "INSERT INTO lc_message (msg_title,msg_type,user_id,msg_content,created_by,stamp_created,updated_by,stamp_updated,state) VALUES (?,?,?,?,?,?,?,?,?)";
SimpleDateFormat gs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DecimalFormat df = new DecimalFormat("######0.00");
StringBuffer cont = new StringBuffer("尊敬的"+f.getUser().getUser_name()+"用户,你在");
cont.append(gs.format(f.getStamp_created()));
cont.append("购买了"+f.getFinance_money()+"元的"+f.getFinanceProduct().getProduct_name()+"预计到期收益为:"+df.format(f.getFinance_money()*f.getFinanceProduct().getInterest_rate()*f.getFinanceProduct().getInvest_days()/360/100));
cont.append(",订单号为:"+f.getFinance_num());
DBUtils.beginTx(connection);
int isSuccess = qR.update(connection,sql,f.getFinance_num(),f.getFinance_money(),f.getUser().getUser_id(),f.getFinanceProduct().getProduct_id(),f.getCreated_by(),f.getStamp_created(),f.getUpdated_by(),f.getStamp_updated(),f.getState());
int isSuccess2 = qR.update(connection,sql2,"购买理财消息",1,f.getUser().getUser_id(),cont.toString(),f.getCreated_by(),f.getStamp_created(),f.getUpdated_by(),f.getStamp_updated(),f.getState());
if(isSuccess==1&&isSuccess2==1){
DBUtils.commit(connection);
result = true;
} else{
DBUtils.rollback(connection);
result = false;
}
} catch (Exception e) {
DBUtils.rollback(connection);
e.printStackTrace();
} finally{
DBUtils.releaseDB(null, null, connection);
}
return result;
}
@SuppressWarnings("rawtypes")
private ScalarHandler scalarHandler = new ScalarHandler() {
@Override
public Object handle(ResultSet rs) throws SQLException {
Object obj = super.handle(rs);
if (obj instanceof BigInteger)
return ((BigInteger) obj).longValue();
return obj;
}
};
//@APP--分页理财购买记录
public Pager<OrderDetial> financePager(int pageNum,int pageSize,String uid){
Pager<OrderDetial> result = null;
// 存放查询参数
Connection connection = null;
StringBuilder sql = new StringBuilder(
"SELECT A.finance_id, A.finance_num, A.finance_money, A.stamp_created,B.interest_rate,B.invest_days,B.product_name,truncate( A.finance_money*B.interest_rate*B.invest_months/12/100,2) as money_rate from lc_finance A ,lc_finance_product B where 1=1 AND A.product_id=B.product_id AND user_id=?");
StringBuilder countSql = new StringBuilder("SELECT count(finance_id) as totalRecord FROM lc_finance WHERE 1=1 AND user_id=?");
sql.append(" and A.state = ?");
countSql.append(" and state = ?");
long totalRecord = 0;
// 起始索引
long fromIndex = pageSize * (pageNum -1);
// 使用limit关键字,实现分页
sql.append(" order by A.stamp_created desc limit " + fromIndex + ", " + pageSize);
List<OrderDetial> msgList = new ArrayList<OrderDetial>();
try {
connection = DBUtils.getConnection();
DBUtils.beginTx(connection);
// 获取总记录数
totalRecord =(Long) (Number) qR.query(connection,countSql.toString(),scalarHandler,uid,"A");
// 获取查询的消息记录
msgList = qR.query(connection,sql.toString(),new BeanListHandler<OrderDetial>(OrderDetial.class),uid,"A");
//获取总页数
long totalPage = totalRecord / pageSize;
if(totalRecord % pageSize !=0){
totalPage++;
}
// 组装pager对象
result = new Pager<OrderDetial>(pageSize, pageNum, totalRecord, totalPage, msgList);
} catch (Exception e) {
DBUtils.rollback(connection);
e.printStackTrace();
} finally{
DBUtils.releaseDB(null, null, connection);
}
return result;
}
//@APP--统计理财
public String countMoney(String uid){
String result ="";
Connection connection = null;
String sql = "SELECT sum(finance_money) as result FROM lc_finance WHERE 1=1 AND is_count=1 AND user_id=? AND state=?";
try {
connection = DBUtils.getConnection();
DBUtils.beginTx(connection);
if(qR.query(connection,sql,scalarHandler,uid,"A")!=null){
result = qR.query(connection,sql,scalarHandler,uid,"A").toString();
}
DBUtils.commit(connection);
} catch (Exception e) {
DBUtils.rollback(connection);
e.printStackTrace();
} finally{
DBUtils.releaseDB(null, null, connection);
}
return result;
}
//@PT---理财查询
}
| true
|
54291c2c6f046ebd318a2d5acab55376f396e92f
|
Java
|
AitGo/CsiModel
|
/module_server/src/main/java/com/liany/csiserverapp/network/request/Request.java
|
UTF-8
| 459
| 1.679688
| 2
|
[] |
no_license
|
package com.liany.csiserverapp.network.request;
/**
* @创建者 ly
* @创建时间 2019/4/15
* @描述 ${TODO}
* @更新者 $Author$
* @更新时间 $Date$
* @更新描述 ${TODO}
*/
public interface Request {
// public static String HOST = (String) SPUtils.getParam(MyApplication.getContext(),Constants.URL,"http://192.168.31.88:8080/lianyservice/service/");
public static String HOST = "http://192.168.31.88:8080/lianyservice/service/";
}
| true
|
0bcfc2d857a737532e5e1569d1b096fbd47c8170
|
Java
|
galid1/photosend-server
|
/src/main/java/com/photosend/photosendserver01/domains/user/presentation/request_reponse/RenewApnsDeviceTokenRequest.java
|
UTF-8
| 334
| 1.539063
| 2
|
[] |
no_license
|
package com.photosend.photosendserver01.domains.user.presentation.request_reponse;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RenewApnsDeviceTokenRequest {
private String apnsDeviceToken;
}
| true
|
8b1f0a93b95d83e4fa486f506a1f19ac9f5d8fab
|
Java
|
IRetamales/SisRemu
|
/src/Clases/clsUsuario.java
|
UTF-8
| 2,058
| 2.53125
| 3
|
[] |
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 Clases;
import java.sql.*;
import java.sql.CallableStatement;
/**
*
* @author Sylar
*/
public class clsUsuario {
private String strLogin;
private String strPassword;
public String getLogin( ){
return this.strLogin;
}
public void setLogin(String login){
this.strLogin = login;
}
public String getPassword( ){
return this.strPassword;
}
public void setPassword(String password){
this.strPassword = password;
}
public boolean BuscarUsuario(){
String strSql= "Select * from tusuario where login='" + strLogin + "' and password='" + strPassword + "'";
//String strSql= "call spBuscaUsuario (?,?)";// + strLogin + "','" + strPassword + "'";
try{
clsConexion con = new clsConexion();
con.crearConexion();
/*CallableStatement prc = con.conexion.prepareCall("{call spBuscaUsuario(?,?,?,?)}");
prc.setString(1, strLogin);
prc.setString(2, strPassword);
prc.registerOutParameter(3, Types.VARCHAR);
//prc.registerOutParameter("Pas", Types.VARCHAR);
prc.execute();
String aaa=prc.getString(3);
String bbb=prc.getString(4);
if(prc.getString("idUsu")!=null){
return true;
}else{
return false;
}*/
ResultSet resultado = con.ejecutarSQLSelect(strSql);
if (resultado.next()) {
return true;
}else{
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| true
|
a2864fc8b586c1b19acd5c2deb7e2e775829b3b6
|
Java
|
zhaoxunyong/quartz-manager
|
/src/main/java/com/woyi/mhub/task/controller/SchedulerHelper.java
|
UTF-8
| 4,528
| 2.34375
| 2
|
[] |
no_license
|
package com.woyi.mhub.task.controller;
import java.io.FileInputStream;
import java.util.List;
import java.util.Properties;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.Trigger.TriggerState;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
/**
*
* 此类描述的是:任务的创建和管理
*
* @author: jie_hoang@woyitech.com
* @version: 2016年8月25日 下午8:08:51
* @ClassName: SchedulerHelper
* @项目: MyQuartz
* @包:com.woyi.mhub.quartz
*/
public class SchedulerHelper {
private static Logger logger = LoggerFactory.getLogger(SchedulerHelper.class);
private final static String JOB_GROUP_NAME = "QUARTZ_JOBGROUP_NAME";// 任务组
private final static String TRIGGER_GROUP_NAME = "QUARTZ_TRIGGERGROUP_NAME";// 触发器组
private static Scheduler scheduler;
private SchedulerFactory schedulerFactory;
private StdSchedulerFactory stdSchedulerFactory;
private static SchedulerFactoryBean schedulerFactoryBean;
public SchedulerHelper(){
if(null == this.schedulerFactory){
this.schedulerFactory = new StdSchedulerFactory();
}
}
public static void main(String[] ars) {
SchedulerFactory sf = new StdSchedulerFactory();
try {
scheduler = sf.getScheduler();
List<String> rr = scheduler.getJobGroupNames();
JobKey jobKey = new JobKey("job1",JOB_GROUP_NAME);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
TriggerKey triggerKey = TriggerKey.triggerKey("trigger1",TRIGGER_GROUP_NAME);
Trigger trigger = scheduler.getTrigger(triggerKey);
System.out.println("_______");
//getJobDetail(null);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
/**
* 加入job
*/
public static void addJob(String jobName, String triggerName,
Class<? extends Job> jobClass, int seconds){
try {
SchedulerFactory sf = new StdSchedulerFactory();
/* //显式配置
StdSchedulerFactory sf = new StdSchedulerFactory();
Properties props = new Properties();
FileInputStream in = new FileInputStream("F:/Workspaces/MyQuartz/src/quartz.properties");
props.load(in);
in.close();
props.put("org.quartz.scheduler.instanceName", "TestScheduler1");
props.put("org.quartz.scheduler.instanceId", "WOYI"+System.currentTimeMillis());
sf.initialize(props);
*/
scheduler = sf.getScheduler();
//检测job执行记录
JobKey jobKey = new JobKey(jobName,JOB_GROUP_NAME);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if(null == jobDetail){ //无记录
logger.info("add {"+ jobName +"} Scheduler");
//构建job实例
jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, JOB_GROUP_NAME).build();
//构建触发器
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName, TRIGGER_GROUP_NAME)
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(seconds)
.repeatForever())
.build();// 产生触发器
scheduler.scheduleJob(jobDetail, trigger);
}else{ //有记录
TriggerKey triggerKey = TriggerKey.triggerKey(triggerName,TRIGGER_GROUP_NAME);
SimpleTriggerImpl simpleTrigger = (SimpleTriggerImpl) scheduler.getTrigger(triggerKey);
simpleTrigger.setRepeatInterval(seconds*1000);
//重新设置job执行
scheduler.rescheduleJob(triggerKey, simpleTrigger);
logger.info(scheduler.getSchedulerInstanceId() + " .... "+ jobName + " 重置触发器 ");
}
// 启动
scheduler.start();
logger.info(""+ jobName +" start");
} catch (Exception e) {
logger.error(" add "+ jobName +" start error", e);
}
}
/**
* 清除
*/
public static void clearAllScheduler() {
try {
scheduler.clear();
} catch (SchedulerException e) {
logger.error("clearAllScheduler", e);
}
}
public static JobKey getJobKey(String jobName, String jobGroup){
return new JobKey(jobName,jobGroup);
}
}
| true
|
f895f9b9a8a8284cd05ea42c32fd56a599b28b9c
|
Java
|
ashik-18/java-lab-programs
|
/factorial.java
|
UTF-8
| 382
| 3.1875
| 3
|
[] |
no_license
|
package class_programs;
import java.util.*;
public class factorial {
public static void main(String[] args) {
System.out.println("This program is written by\nAshik MR, 4NI19IS017, B section");
int n;
int factorial = 1;
n = 10;
while(n!=0) {
factorial = factorial*n;
n--;
}
System.out.println("factorial of 10 is "+ factorial);
}
| true
|
056be68b4f92fdb85989459e130ceff436253a21
|
Java
|
msalinasicsni/estudios-ics
|
/src/main/java/ni/org/ics/estudios/service/muestreoanual/LactanciaMaternaService.java
|
UTF-8
| 3,090
| 2.296875
| 2
|
[] |
no_license
|
package ni.org.ics.estudios.service.muestreoanual;
import ni.org.ics.estudios.domain.muestreoanual.LactanciaMaterna;
import ni.org.ics.estudios.domain.muestreoanual.LactanciaMaternaId;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
/**
* Servicio para el objeto Lactancia Materna
*
* @author Brenda Lopez
*
**/
@Service("lactanciaMaternaService")
@Transactional
public class LactanciaMaternaService {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
/**
* Regresa todos los Datos de las encuestas de Lactancia Materna
*
* @return una lista de <code>datos de Lactancia Materna</code>(s)
*/
@SuppressWarnings("unchecked")
public List<LactanciaMaterna> getLactanciaMaterna() {
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
// Create a Hibernate query (HQL)
Query query = session.createQuery("FROM LactanciaMaterna");
// Retrieve all
return query.list();
}
/**
* Regresa los datos de las encuestas de lactancia materna
*
*
* @return una <code>Encuesta de lactancia materna</code>
*/
public LactanciaMaterna getLactanciaMaterna (LactanciaMaternaId lmId) {
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
Timestamp timeStamp = new Timestamp(lmId.getFechaEncLM().getTime());
Query query = session.createQuery("FROM LactanciaMaterna lacmat where lacmat.lmId.codigo = " + lmId.getCodigo() + " AND lacmat.lmId.fechaEncLM = :fechaE");
query.setTimestamp("fechaE", timeStamp);
LactanciaMaterna lactanciamaterna = (LactanciaMaterna) query.uniqueResult();
return lactanciamaterna;
}
/**
* Verifica los datos de las encuestas de lactancia materna
*
* @return true or false
*/
public Boolean checkLactanciaMaterna(LactanciaMaternaId lmId) {
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
Timestamp timeStamp = new Timestamp(lmId.getFechaEncLM().getTime());
Query query = session.createQuery("FROM LactanciaMaterna lacmat where lacmat.lmId.codigo = " + lmId.getCodigo() + " AND lacmat.lmId.fechaEncLM = :fechaE");
query.setTimestamp("fechaE", timeStamp);
LactanciaMaterna lactanciamaterna = (LactanciaMaterna) query.uniqueResult();
if(lactanciamaterna!=null){
return true;
}
else{
return false;
}
}
/**
* Agrega los datos de las encuestas de lactancia materna
*
*
*/
public void addLactanciaMaterna(LactanciaMaterna lactanciaMaterna) {
Session session = sessionFactory.getCurrentSession();
session.save(lactanciaMaterna);
}
/**
* Actualiza una encuesta de lactancia materna
*
*
*/
public void updateLactanciaMaterna(LactanciaMaterna lactanciaMaterna) {
Session session = sessionFactory.getCurrentSession();
session.update(lactanciaMaterna);
}
}
| true
|
31add358ea4f294d31dd4a2990e124eda1588fd4
|
Java
|
jasleen1291/B2BMobileApplication
|
/Web Application/build/generated/src/org/apache/jsp/shop_jsp.java
|
UTF-8
| 13,405
| 1.507813
| 2
|
[] |
no_license
|
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.json.JSONObject;
import java.sql.ResultSetMetaData;
import java.sql.ResultSet;
import org.json.JSONArray;
import Db.DbConnector;
import java.sql.Connection;
public final class shop_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
Connection con = DbConnector.initConnection();
public JSONArray fetchchildren(String id) {
try {
JSONArray temp = new JSONArray();
ResultSet resultSet = con.createStatement().executeQuery("select * from `category` where ParentCategory='" + id + "'");
if (!resultSet.next()) {
//temp.put(id, "null");
} else {
do {
JSONObject tr = new JSONObject();
tr.put("id", resultSet.getString(1));
tr.put("name", resultSet.getString(2));
tr.put("children", fetchchildren(resultSet.getString(1)));
temp.put(tr);
} while (resultSet.next());
}
return temp;
} catch (Exception e) {
return new JSONArray().put(e.toString());
}
}
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List<String> _jspx_dependants;
private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector;
public java.util.List<String> getDependants() {
return _jspx_dependants;
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("application/json;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
_jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write("\n");
out.write('\n');
if (request.getParameter("opt") != null) {
JSONArray a = new JSONArray();
if (request.getParameter("opt").equalsIgnoreCase("myshops")) {
ResultSet rs = con.createStatement().executeQuery("Select * from shop where ShopOwner='" + request.getParameter("id") + "'");
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()) {
JSONObject ob = new JSONObject();
for (int i = 1; i <= count; i++) {
ob.put(rsmd.getColumnLabel(i), rs.getString(rsmd.getColumnLabel(i)));
}
//System.out.println(rsmd.getColumnLabel(1));
JSONArray items = new JSONArray();
ResultSet rs2 = con.createStatement().executeQuery("SELECT * FROM item_shop,item where shopid='" + rs.getString(rsmd.getColumnLabel(1)) + "' and iditem=item_shop.itemid and item.status='activated' order by iditem DESC");
ResultSetMetaData rsmd2 = rs2.getMetaData();
int coun2t = rsmd2.getColumnCount();
while (rs2.next()) {
JSONObject ob2 = new JSONObject();
for (int i = 1; i <= coun2t; i++) {
if (rsmd2.getColumnLabel(i).equalsIgnoreCase("item_shopid")) {
JSONArray btd = new JSONArray();
ResultSet rs6 = con.createStatement().executeQuery("SELECT * FROM b2b.batchdiscount where `idbatchdiscount`='" + rs2.getString(rsmd2.getColumnLabel(i)) + "'");
while (rs6.next()) {
JSONObject wq = new JSONObject();
wq.put("qty", rs6.getString(2));
wq.put("discount", rs6.getString(3));
wq.put("id", rs6.getString(4));
btd.put(wq);
}
ob2.put("batch", btd);
}
ob2.put(rsmd2.getColumnLabel(i), rs2.getString(rsmd2.getColumnLabel(i)));
}
items.put(ob2);
}
JSONArray items2 = new JSONArray();
ResultSet rs3 = con.createStatement().executeQuery("SELECT * FROM item,item_shop where item_shop.sellertype='Supplier' and iditem=item_shop.itemid and itemid not in(select itemid from item_shop where shopid ='" + rs.getString(rsmd.getColumnLabel(1)) + "')");
//System.out.println("SELECT * FROM item,item_shop where item_shop.sellertype='Supplier' and iditem=item_shop.itemid and iditem not in(select itemid from item_shop where shopid ='" + rs.getString(rsmd.getColumnLabel(1)) + "')");
//sSystem.out.println("Select * from item where Owner='" + request.getParameter("id") + "' and iditem not in( SELECT itemid FROM item_shop where shopid='" + rs.getString(rsmd.getColumnLabel(1)) + "')");
ResultSetMetaData rsmd3 = rs3.getMetaData();
int count3 = rsmd3.getColumnCount();
while (rs3.next()) {
System.out.println(rs3.getString(1));
JSONObject ob3 = new JSONObject();
for (int i = 1; i <= count3; i++) {
if (rsmd3.getColumnLabel(i).equalsIgnoreCase("item_shopid")) {
JSONArray btd = new JSONArray();
ResultSet rs6 = con.createStatement().executeQuery("SELECT * FROM b2b.batchdiscount where `idbatchdiscount`='" + rs3.getString(rsmd3.getColumnLabel(i)) + "'");
while (rs6.next()) {
JSONObject wq = new JSONObject();
wq.put("qty", rs6.getString(2));
wq.put("discount", rs6.getString(3));
wq.put("id", rs6.getString(4));
btd.put(wq);
}
ob3.put("batch", btd);
}
ob3.put(rsmd3.getColumnLabel(i), rs3.getString(rsmd3.getColumnLabel(i)));
}
//System.out.println(ob3);
items2.put(ob3);
}
ob.put("children", items);
ob.put("available", items2);
JSONArray ad = new JSONArray();
ResultSet rs4 = con.createStatement().executeQuery("select * from `category` where ParentCategory='0' and idcategory in(SELECT idCategory FROM b2b.category_user where masterid='" + request.getParameter("id") + "')");
//System.out.println("select * from `category` where ParentCategory='0' and idcategory in(SELECT idCategory FROM b2b.category_user where masterid='"+request.getParameter("id")+"')");
while (rs4.next()) {
JSONObject tr = new JSONObject();
tr.put("id", rs4.getString(1));
tr.put("name", rs4.getString(2));
tr.put("children", fetchchildren(rs4.getString(1)));
//System.out.println(rs.getString(1)+rs.getString(2)+fetchchildren(rs.getString(1)));
ad.put(tr);
// System.out.println(tr);
}
ob.put("categories", ad);
a.put(ob);
}
out.println(a);
} else if (request.getParameter("opt").equalsIgnoreCase("myitems")) {
ResultSet rs = con.createStatement().executeQuery("Select * from item where Owner='" + request.getParameter("id") + "'");
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()) {
JSONObject ob = new JSONObject();
for (int i = 1; i <= count; i++) {
ob.put(rsmd.getColumnLabel(i), rs.getString(rsmd.getColumnLabel(i)));
}
a.put(ob);
}
out.println(a);
} else if (request.getParameter("opt").equalsIgnoreCase("additem")) {
int ab = con.createStatement().executeUpdate("INSERT INTO `b2b`.`item_shop` (`itemid`,`shopid`,`sellertype`,`unitcost`,`sp`,`qtyonhand`,`qtyonorder`,`discount`,`item_supplier`,`min_order`) "
+ "VALUES ('" + request.getParameter("itemid") + "','" + request.getParameter("shopid") + "','" + request.getParameter("sellertype") + "','" + request.getParameter("unitcost") + "','" + request.getParameter("sp") + "','" + request.getParameter("qtyonhand") + "','" + request.getParameter("qtyonorder") + "','" + request.getParameter("discount") + "','" + request.getParameter("item_supplier") + "','" + request.getParameter("min_order") + "');");
if (ab == 1) {
out.println(new JSONObject().put("Status", "Values inserted"));
} else {
}
} else if (request.getParameter("opt").equalsIgnoreCase("addshop")) {
int ab = con.createStatement().executeUpdate("INSERT INTO `shop` (`ShopName`,`ShopType`,`ShopOwner`,`description`,`status`,`expirydate`,`paymentemail`,categoriesallowed) VALUES('" + request.getParameter("name") + "','" + request.getParameter("type") + "','" + request.getParameter("id") + "','" + request.getParameter("desc") + "','added',date_add(CURDATE(), INTERVAL " + request.getParameter("days") + " DAY),'" + request.getParameter("email") + "','" + request.getParameter("no") + "');");
if (ab == 1) {
out.println(new JSONObject().put("Status", "Values inserted"));
} else {
out.println(new JSONObject().put("Status", "Values not inserted"));
}
} else if (request.getParameter("opt").equalsIgnoreCase("update")) {
int ab = con.createStatement().executeUpdate("UPDATE `b2b`.`shop` SET `ShopName` = '" + request.getParameter("name") + "',`description` = '" + request.getParameter("desc") + "',`paymentemail` = '" + request.getParameter("paymentemail") + "',`categoriesallowed` = '" + request.getParameter("noofcategories") + "' wHERE `idshop` = '" + request.getParameter("id") + "';");
if (ab == 1) {
out.println(new JSONObject().put("Status", "Values inserted"));
} else {
}
} else if (request.getParameter("opt").equalsIgnoreCase("deleteitem")) {
int ab = con.createStatement().executeUpdate("UPDATE `b2b`.`item` SET status = 'deactivated' WHERE `iditem` = '" + request.getParameter("id") + "';");
if (ab == 1) {
out.println(new JSONObject().put("Status", "Values inserted"));
} else {
}
} else if (request.getParameter("opt").equalsIgnoreCase("selectall")) {
JSONObject as = new JSONObject();
ResultSet rs5 = con.createStatement().executeQuery("select idshop,shopname from shop");
while (rs5.next()) {
as.put(rs5.getString(1), rs5.getString(2));
}
out.println(as);
} else if(request.getParameter("opt").equalsIgnoreCase("retail"))
{
JSONArray ar=new JSONArray();
ResultSet rs=con.createStatement().executeQuery("SELECT * FROM item,item_shop where item_shop.sellertype='Retailer' and iditem=item_shop.itemid");
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next())
{
JSONObject ob=new JSONObject();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
ob.put(rsmd.getColumnName(i), rs.getString(i));
}
ar.put(ob);
}
out.println(ar);
}
}
else if(request.getParameter("shopid")!=null)
{
ResultSet rs=con.createStatement().executeQuery("SELECT paymentemail FROM b2b.shop where idshop="+request.getParameter("shopid"));
while(rs.next())
{
out.println(new JSONArray().put(rs.getString(1)));
}
}
out.write('\n');
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
out.clearBuffer();
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
| true
|
91533e8667b8af12cd7bd5c43aeed1dee67948ca
|
Java
|
kuaifan/eeui-template
|
/plugins/eeui/framework/android/src/main/java/app/eeui/framework/extend/integration/glide/load/model/stream/UrlLoader.java
|
UTF-8
| 1,957
| 2.40625
| 2
|
[
"MIT"
] |
permissive
|
package app.eeui.framework.extend.integration.glide.load.model.stream;
import androidx.annotation.NonNull;
import app.eeui.framework.extend.integration.glide.load.Options;
import app.eeui.framework.extend.integration.glide.load.model.GlideUrl;
import app.eeui.framework.extend.integration.glide.load.model.ModelLoader;
import app.eeui.framework.extend.integration.glide.load.model.ModelLoaderFactory;
import app.eeui.framework.extend.integration.glide.load.model.MultiModelLoaderFactory;
import java.io.InputStream;
import java.net.URL;
/**
* A wrapper class that translates {@link java.net.URL} objects into {@link
* app.eeui.framework.extend.integration.glide.load.model.GlideUrl} objects and then uses the wrapped {@link
* app.eeui.framework.extend.integration.glide.load.model.ModelLoader} for {@link app.eeui.framework.extend.integration.glide.load.model.GlideUrl}s to
* load the data.
*/
public class UrlLoader implements ModelLoader<URL, InputStream> {
private final ModelLoader<GlideUrl, InputStream> glideUrlLoader;
// Public API.
@SuppressWarnings("WeakerAccess")
public UrlLoader(ModelLoader<GlideUrl, InputStream> glideUrlLoader) {
this.glideUrlLoader = glideUrlLoader;
}
@Override
public LoadData<InputStream> buildLoadData(@NonNull URL model, int width, int height,
@NonNull Options options) {
return glideUrlLoader.buildLoadData(new GlideUrl(model), width, height, options);
}
@Override
public boolean handles(@NonNull URL model) {
return true;
}
/**
* Factory for loading {@link InputStream}s from {@link URL}s.
*/
public static class StreamFactory implements ModelLoaderFactory<URL, InputStream> {
@NonNull
@Override
public ModelLoader<URL, InputStream> build(MultiModelLoaderFactory multiFactory) {
return new UrlLoader(multiFactory.build(GlideUrl.class, InputStream.class));
}
@Override
public void teardown() {
// Do nothing.
}
}
}
| true
|
5a9797951eee4ad4bd9b34b24885744ddfcdf430
|
Java
|
cenxui/Interview
|
/Interview/src/Tree.java
|
UTF-8
| 3,651
| 3.203125
| 3
|
[] |
no_license
|
import java.awt.Checkbox;
import java.util.ArrayList;
import java.util.List;
public class Tree {
private Tree left;
private Tree right;
private int val;
public static void main(String[] args) {
Tree tree = new Tree();
tree.val = 1;
tree.left = new Tree();
tree.left.val = 2;
tree.right = new Tree();
tree.right.val = 1;
tree.left.left = new Tree();
tree.left.left.val = 2;
tree.right.right = new Tree();
tree.right.right.val = 1;
System.out.println(tree.getPath(3));
// Tree another = new Tree();
// another.val = 10;
// another.left = new Tree();
// another.left.val = 11;
// another.right = new Tree();
// another.right.val = 12;
// another.left.left = new Tree();
// another.left.left.val = 7;
// another.right.right = new Tree();
// another.right.right.val = 8;
// // System.out.println(tree.equals(another));
// System.out.println(tree);
// tree.revert();
// System.out.println(tree);
// System.out.println(tree.isSymetric());
}
public Tree() {
this(null, null);
}
public Tree(Tree left, Tree right) {
this.left = left;
this.right = right;
}
public boolean isSymetric() {
return isSymetric(this.left, this.right);
}
private boolean isSymetric(Tree left, Tree right) {
if (left == null && right == null)
return true;
if (left == null || right == null)
return false;
if (left.val != right.val)
return false;
return isSymetric(left.left, right.right) && isSymetric(left.right, right.left);
}
public void revert() {
revertTree(this);
}
private void revertTree(Tree tree) {
if (tree == null)
return;
Tree temp = tree.left;
tree.left = tree.right;
tree.right = temp;
revertTree(tree.left);
revertTree(tree.right);
}
/**
* given sum that find all path lead to the sum
* @param sum the number of tree value sum
* @return result the path lead to the sum
*/
public List<String> getPath(int sum) {
List<String> result = new ArrayList<>();
checkPath(result, new StringBuilder(), this, sum);
return result;
}
private void checkPath(List<String> result, StringBuilder path, Tree treeNode, int sum) {
if (treeNode == null) {
return;
}
sum = sum - treeNode.val;
if (sum < 0) {
return;
}
path.append("->").append(treeNode.val);
if (sum == 0) {
result.add(path.toString());
return;
}
checkPath(result, new StringBuilder(path), treeNode.left, sum);
checkPath(result, path, treeNode.right, sum);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(" value : ").append(this.val);
if (this.left != null) {
stringBuilder.append(this.left);
}
if (this.right != null) {
stringBuilder.append(this.right);
}
return stringBuilder.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Tree) {
if (this.val != ((Tree) obj).val) {
return false;
}
if (this.left == null && this.right == null) {
return ((Tree) obj).left == null && ((Tree) obj).right == null;
}
if (this.left != null && this.right == null) {
return ((Tree) obj).right == null && this.left.equals(((Tree) obj).left);
}
if (this.left == null && this.right != null) {
return ((Tree) obj).left == null && this.right.equals(((Tree) obj).right);
}
return this.left.equals(((Tree) obj).left) && this.right.equals(((Tree) obj).right);
}
return false;
}
}
| true
|
351ac0f78dd453e69b8259384ca1a6c1943f2ce8
|
Java
|
happyjianguo/pay-1
|
/Common/PE/if-pricingstrategy/if-pricingstrategy-impl/src/main/java/com/pay/pricingstrategy/service/CalFeeInnerParam.java
|
UTF-8
| 811
| 1.632813
| 2
|
[] |
no_license
|
/**
*
*/
package com.pay.pricingstrategy.service;
import com.pay.pricingstrategy.dto.PricingStrategyDetailDTO;
/**
* @author
*
*/
public class CalFeeInnerParam {
private long transactionAmount;
private PricingStrategyDetailDTO pricingstategydetaildto;
public long getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(long transactionAmount) {
this.transactionAmount = transactionAmount;
}
public PricingStrategyDetailDTO getPricingstategydetaildto() {
return pricingstategydetaildto;
}
public void setPricingstategydetaildto(
PricingStrategyDetailDTO pricingstategydetaildto) {
this.pricingstategydetaildto = pricingstategydetaildto;
}
}
| true
|
4691b1362abe45046c070133e55356d5cc51d281
|
Java
|
ordnaelmedeiros/jpa-fluid-select
|
/lib/src/test/java/com/ordnaelmedeiros/jpafluidselect/querybuilder/results/ReturnTest.java
|
UTF-8
| 6,485
| 2.5
| 2
|
[] |
no_license
|
package com.ordnaelmedeiros.jpafluidselect.querybuilder.results;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import java.util.List;
import org.junit.Test;
import com.github.ordnaelmedeiros.jpafluidselect.models.Address;
import com.github.ordnaelmedeiros.jpafluidselect.models.People;
import com.github.ordnaelmedeiros.jpafluidselect.models.People_;
import com.ordnaelmedeiros.jpafluidselect.querybuilder.QueryBuilderTestBase;
public class ReturnTest extends QueryBuilderTestBase {
@Test
public void singleReturnOrigin() {
try {
People result = queryBuilder
.select(People.class)
.where()
.field("id").eq(1l)
.getSingleResult();
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo(1l));
assertThat(result.getName(), equalTo("Leandro"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void listReturnOrigin() {
try {
List<People> result = queryBuilder
.select(People.class)
.where()
.field("id").in(1l, 2l)
.order()
.asc("id")
.getResultList();
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(2));
assertThat(result.get(0).getId(), equalTo(1l));
assertThat(result.get(0).getName(), equalTo("Leandro"));
assertThat(result.get(1).getId(), equalTo(2l));
assertThat(result.get(1).getName(), equalTo("Ivana"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void singleReturnFieldEntity() {
try {
Address result = queryBuilder
.select(People.class)
.fields()
.add("address")
.where()
.field("id").eq(1l)
.getSingleResult(Address.class);
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo(1l));
assertThat(result.getStreet(), equalTo("One"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void listReturnFieldEntity() {
try {
List<Address> result = queryBuilder
.select(People.class)
.fields()
.add("address")
.where()
.field("id").in(1l, 2l)
.order()
.asc("id")
.getResultList(Address.class);
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(2));
assertThat(result.get(0).getId(), equalTo(1l));
assertThat(result.get(0).getStreet(), equalTo("One"));
assertThat(result.get(1).getId(), equalTo(2l));
assertThat(result.get(1).getStreet(), equalTo("Two"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void singleReturnFieldPrimitive() {
try {
String result = queryBuilder
.select(People.class)
.fields()
.add("name")
.where()
.field("id").eq(1l)
.getSingleResult(String.class);
assertThat(result, notNullValue());
assertThat(result, equalTo("Leandro"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void listReturnFieldPrimitive() {
try {
List<String> result = queryBuilder
.select(People.class)
.fields()
.add("name")
.where()
.field("id").in(1l, 2l)
.order()
.asc("id")
.getResultList(String.class);
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(2));
assertThat(result.get(0), equalTo("Leandro"));
assertThat(result.get(1), equalTo("Ivana"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void singleReturnFieldByConstructor() {
try {
People result = queryBuilder
.select(People.class)
.fields()
.add("id")
.add("name")
.where()
.field("id").eq(1l)
.getSingleResultByConstructor(People.class);
assertThat(result, notNullValue());
assertThat(result.getId(), equalTo(1l));
assertThat(result.getName(), equalTo("Leandro"));
assertThat(result.getCreated(), nullValue());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void listReturnFieldByConstructor() {
try {
List<People> result = queryBuilder
.select(People.class)
.fields()
//.add("id")
.add("name")
.where()
.field("id").in(1l, 2l)
.order()
.asc("id")
.getResultListByConstructor(People.class);
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(2));
//assertThat(result.get(0).getId(), equalTo(1l));
assertThat(result.get(0).getName(), equalTo("Leandro"));
assertThat(result.get(0).getCreated(), nullValue());
//assertThat(result.get(1).getId(), equalTo(2l));
assertThat(result.get(1).getName(), equalTo("Ivana"));
assertThat(result.get(1).getCreated(), nullValue());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void singleReturnFieldByTransform() {
try {
PeopleDTO result = queryBuilder
.select(People.class)
.fields()
.field(People_.id).alias("peopleId")
.field("name").alias("peopleName")
.where()
.field("id").eq(1l)
.getSingleResultByReflect(PeopleDTO.class);
assertThat(result, notNullValue());
assertThat(result.getPeopleId(), equalTo(1l));
assertThat(result.getPeopleName(), equalTo("Leandro"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void listReturnFieldByTransform() {
try {
List<PeopleDTO> result = queryBuilder
.select(People.class)
.fields()
.field("id").alias("peopleId")
.field("name").alias("peopleName")
.where()
.field("id").in(1l, 2l)
.order()
.asc("id")
.getResultListByReflect(PeopleDTO.class);
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(2));
assertThat(result.get(0).getPeopleId(), equalTo(1l));
assertThat(result.get(0).getPeopleName(), equalTo("Leandro"));
assertThat(result.get(1).getPeopleId(), equalTo(2l));
assertThat(result.get(1).getPeopleName(), equalTo("Ivana"));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}
| true
|
9d5897568fd0a1e77dbf2a8a2c40865c841359ea
|
Java
|
RouNNdeL/csgo-dashboard-app
|
/app/src/main/java/com/roundel/csgodashboard/entities/utility/FilterGrenade.java
|
UTF-8
| 659
| 2.234375
| 2
|
[] |
no_license
|
package com.roundel.csgodashboard.entities.utility;
/**
* Created by Krzysiek on 2017-02-24.
*/
public class FilterGrenade extends FilterBase
{
private static final String TAG = FilterGrenade.class.getSimpleName();
//<editor-fold desc="private variables">
private Integer type;
private Boolean isJumpThrow;
//</editor-fold>
public Integer getType()
{
return type;
}
public void setType(Integer type)
{
this.type = type;
}
public Boolean getJumpThrow()
{
return isJumpThrow;
}
public void setJumpThrow(Boolean jumpThrow)
{
isJumpThrow = jumpThrow;
}
}
| true
|
9533606bc78e1fd4558a534d1434f8d11ffab417
|
Java
|
KrystianKoziel/androidList
|
/app/src/main/java/com/studenckie/apartamenty/adapterlist/HousesList.java
|
UTF-8
| 2,929
| 2.640625
| 3
|
[] |
no_license
|
package com.studenckie.apartamenty.adapterlist;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Iterator;
import java.util.List;
import static android.app.Activity.RESULT_OK;
public class HousesList extends Fragment implements RecyclerAdapter.OnItemClickListener {
private RecyclerView myRecyclerView;
private List<House> houses;
private RecyclerAdapter recyclerAdapter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
Bundle savedInstanceState) {
View housesListFragment = inflater.inflate(R.layout.houses_list, container, false);
myRecyclerView = housesListFragment.findViewById(R.id.houses);
return housesListFragment;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerAdapter = new RecyclerAdapter(getContext(), this);
myRecyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.setHouses(houses);
}
public void setHouses(List<House> houses) {
this.houses = houses;
}
@Override
public void onItemClick(House item) {
if (getActivity().getFragmentManager()
.findFragmentById(R.id.details_fragment) != null) {
getActivity().getFragmentManager().popBackStack();
}
HouseFragment houseFragment = new HouseFragment();
houseFragment.setTargetFragment(HousesList.this, getTargetRequestCode());
Bundle args = new Bundle();
args.putParcelable("house", item);
houseFragment.setArguments(args);
getActivity().getFragmentManager().beginTransaction()
.replace(R.id.details_fragment, houseFragment)
.addToBackStack(null).commit();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
House house = data.getParcelableExtra("house_to_remove");
Iterator<House> iterator = houses.iterator();
while (iterator.hasNext()) {
House house1 = iterator.next();
if (house1.getName().equals(house.getName())) {
iterator.remove();
break;
}
}
recyclerAdapter.notifyDataSetChanged();
((MainActivity) getActivity()).removeHouse(house);
}
}
}
| true
|
0f5b9db22fd19b7f2d1dfbec53e51ffe0b2b1a56
|
Java
|
ocorella/tcu501app
|
/app/src/main/java/comsiteucrtcu501/google/httpssites/tcu501/ElementarySchoolActivity.java
|
UTF-8
| 4,534
| 2.09375
| 2
|
[] |
no_license
|
package comsiteucrtcu501.google.httpssites.tcu501;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import comsiteucrtcu501.google.httpssites.tcu501.Vocabulary.ClickAndListenSecond;
import comsiteucrtcu501.google.httpssites.tcu501.dragDrop.DragDropSecondActivity;
public class ElementarySchoolActivity extends AppCompatActivity {
Button one,two,three,four,five,six;
MediaPlayer mp3;
Activity activity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_elementary_school);
one = (Button) findViewById(R.id.button_1ro);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.firstgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,FirstGradeActivity.class);
startActivity(startNewActivity);
}
});
two = (Button) findViewById(R.id.button_2do);
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.secondgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,SecondGradeActivity.class);
startActivity(startNewActivity);
}
});
three = (Button) findViewById(R.id.button_3ro);
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.thirdgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,ThirdGradeActivity.class);
startActivity(startNewActivity);
}
});
four = (Button) findViewById(R.id.button_4to);
four.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.fourthgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,CuartoGradoActivity.class);
startActivity(startNewActivity);
}
});
five = (Button) findViewById(R.id.button_5to);
five.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.fifthgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,QuintoGradoActivity.class);
startActivity(startNewActivity);
}
});
six = (Button) findViewById(R.id.button_6to);
six.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mp3 = MediaPlayer.create(getApplicationContext(), R.raw.sixthgrade);
mp3.start();
Intent startNewActivity = new Intent(activity,SextoGradoActivity.class);
startActivity(startNewActivity);
}
});
}
public void irA1ro(View view){
Intent startNewActivity = new Intent(this,FirstGradeActivity.class);
startActivity(startNewActivity);
}
public void irA2do(View view){
Intent startNewActivity = new Intent(activity,SecondGradeActivity.class);
startActivity(startNewActivity);
}
public void irA3ro(View view){
Intent startNewActivity = new Intent(activity,ThirdGradeActivity.class);
startActivity(startNewActivity);
}
public void irA4to(View view){
Intent startNewActivity = new Intent(activity,CuartoGradoActivity.class);
startActivity(startNewActivity);
}
public void irA5to(View view){
Intent startNewActivity = new Intent(activity,QuintoGradoActivity.class);
startActivity(startNewActivity);
}
public void irA6to(View view){
Intent startNewActivity = new Intent(activity,SextoGradoActivity.class);
startActivity(startNewActivity);
}
}
| true
|
775cedb44c5211020b414fb56205126f9c03d33f
|
Java
|
ProRocketeers/bsc-be-petaalm
|
/src/main/java/com/prorocketeers/bsc/payment/tracker/service/PaymentParser.java
|
UTF-8
| 331
| 2.1875
| 2
|
[] |
no_license
|
package com.prorocketeers.bsc.payment.tracker.service;
import java.text.ParseException;
import com.prorocketeers.bsc.payment.tracker.domain.Payment;
/**
* API specification for an implementation of "payment line parser".
*/
public interface PaymentParser {
Payment fromString(String paymentLine) throws ParseException;
}
| true
|
49b0cc6d1684a67dd4c1747d0a6ba2d0e7a87ae6
|
Java
|
JamesHuangUC/LeetCode-Java
|
/4.median-of-two-sorted-arrays.java
|
UTF-8
| 1,713
| 3.6875
| 4
|
[] |
no_license
|
/*
* @lc app=leetcode id=4 lang=java
*
* [4] Median of Two Sorted Arrays
*
* https://leetcode.com/problems/median-of-two-sorted-arrays/description/
*
* algorithms
* Hard (26.15%)
* Likes: 4167
* Dislikes: 554
* Total Accepted: 422.5K
* Total Submissions: 1.6M
* Testcase Example: '[1,3]\n[2]'
*
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
*
* Find the median of the two sorted arrays. The overall run time complexity
* should be O(log (m+n)).
*
* You may assume nums1 and nums2 cannot be both empty.
*
* Example 1:
*
*
* nums1 = [1, 3]
* nums2 = [2]
*
* The median is 2.0
*
*
* Example 2:
*
*
* nums1 = [1, 2]
* nums2 = [3, 4]
*
* The median is (2 + 3)/2 = 2.5
*
*
*/
class Solution {
int findKth(int[] nums1, int i, int[] nums2, int j, int k) {
if (i >= nums1.length)
return nums2[j + k - 1];
if (j >= nums2.length)
return nums1[i + k - 1];
if (k == 1)
return Math.min(nums1[i], nums2[j]);
int midVal1 = (i + k / 2 - 1 < nums1.length) ? nums1[i + k / 2 - 1] : Integer.MAX_VALUE;
int midVal2 = (j + k / 2 - 1 < nums2.length) ? nums2[j + k / 2 - 1] : Integer.MAX_VALUE;
if (midVal1 < midVal2) {
return findKth(nums1, i + k / 2, nums2, j, k - k / 2);
} else {
return findKth(nums1, i, nums2, j + k / 2, k - k / 2);
}
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length, left = (m + n + 1) / 2, right = (m + n + 2) / 2;
return (findKth(nums1, 0, nums2, 0, left) + findKth(nums1, 0, nums2, 0, right)) / 2.0;
}
}
| true
|
2968f749a8d4c151bb25af50db197e758548740d
|
Java
|
CyberSource/cybersource-rest-samples-java
|
/src/main/java/samples/authentication/AuthSampleCode/GetGenerateHeaders.java
|
UTF-8
| 5,419
| 2.1875
| 2
|
[] |
no_license
|
package samples.authentication.AuthSampleCode;
import java.lang.invoke.MethodHandles;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.cybersource.authsdk.core.Authorization;
import com.cybersource.authsdk.core.MerchantConfig;
import com.cybersource.authsdk.util.GlobalLabelParameters;
import com.cybersource.authsdk.util.Utility;
import samples.authentication.harness.MerchantProperties;
/**
* This class generates the Headers that are present in the token was sent the server for transaction,
* GET operations.
* *
*/
public class GetGenerateHeaders {
private Properties merchantProp;
private MerchantConfig merchantConfig;
private String authenticationType = null;
private Authorization auth;
private Logger logger;
private String tempSig;
public static void WriteLogAudit(int status) {
String filename = MethodHandles.lookup().lookupClass().getSimpleName();
System.out.println("[Sample Code Testing] [" + filename + "] " + status);
}
/**
* DATE
* [Non-Editable]
*/
private String date = DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneId.of("GMT")));
/**
* REQUEST - TYPE
* [Non-Editable]
*
*/
private String requestType = "GET";
/**
*
* UNQUIE GetID
* [Editable]
*/
private String getID = "5265502011846829204101";
/**
*
* @param getID
* : Unique getID
* @throws Exception
* :
*/
public GetGenerateHeaders(String requestTarget) throws Exception {
setGenerateHeaders();
this.getID = Utility.retrieveGetIDFromRequestTarget(requestTarget);
generateGetHeaders();
}
/**
*
* @param merchantConfig
* : this object contains all the cybs.properites details.
* @throws Exception
*/
public GetGenerateHeaders(MerchantConfig merchantConfig) throws Exception {
this.merchantConfig = merchantConfig;
// merchantConfig.setGetID(getID);
merchantConfig.setRequestType(requestType);
this.logger = LogManager.getLogger(getClass());
auth = new Authorization();
generateGetHeaders();
this.logger.info(GlobalLabelParameters.END_TRANSACTION + "\n");
}
public GetGenerateHeaders() throws Exception {
setGenerateHeaders();
System.out.println("Authentication Type : " + merchantConfig.getAuthenticationType().trim());
this.logger.info(GlobalLabelParameters.BEGIN_TRANSACTION + "\n******************* Generate GET Headers *******************");
merchantConfig.validateMerchantDetails();
generateGetHeaders();
this.logger.info(GlobalLabelParameters.END_TRANSACTION + "\n");
}
private void setGenerateHeaders() throws Exception {
merchantProp = MerchantProperties.getMerchantProperties();
merchantConfig = new MerchantConfig(merchantProp);
authenticationType = merchantConfig.getAuthenticationType().trim();
merchantConfig.setRequestType(requestType);
this.logger = LogManager.getLogger(getClass());
auth = new Authorization();
}
/**
* This method generates the detailed header detail of the transaction and
* displays and log them.
*
* @throws Exception
* : Throws runtime exception.
*/
private void generateGetHeaders() throws Exception {
authenticationType = merchantConfig.getAuthenticationType().trim();
this.logger.info(GlobalLabelParameters.AUTENTICATION_TYPE + authenticationType);
this.logger.info(GlobalLabelParameters.REQUEST_TYPE + " : " + requestType);
this.logger.info(GlobalLabelParameters.DATE + " : " + date);
this.logger.info(GlobalLabelParameters.V_C_MERCHANTID + " : " + merchantConfig.getMerchantID().trim());
this.logger.info(GlobalLabelParameters.CONTENT_TYPE + " : " + GlobalLabelParameters.APPLICATION_JSON);
this.logger.info(GlobalLabelParameters.HOST + " : " + merchantConfig.getRequestHost());
this.logger.info(GlobalLabelParameters.GET + "_ID : " + this.getID);
this.logger.info(GlobalLabelParameters.CONTENT_TYPE + " : " + GlobalLabelParameters.APPLICATION_JSON);
System.out.println("Request Type : " + requestType);
System.out.println("ID : " + this.getID);
System.out.println("Date : " + date);
System.out.println("MerchantID : " + merchantConfig.getMerchantID().trim());
System.out.println("HOST : " + merchantConfig.getRequestHost());
System.out.println(GlobalLabelParameters.CONTENT_TYPE + " : " + GlobalLabelParameters.APPLICATION_JSON);
if (authenticationType.equalsIgnoreCase(GlobalLabelParameters.HTTP)) {
System.out.println(GlobalLabelParameters.USERAGENT + " : " + GlobalLabelParameters.USER_AGENT_VALUE);
this.logger.info(GlobalLabelParameters.USERAGENT + " : " + GlobalLabelParameters.USER_AGENT_VALUE);
tempSig = auth.getToken(merchantConfig);
System.out.println("Signature : " + tempSig.toString());
WriteLogAudit(200);
} else {
String jwtRequestBody = getID;
auth.setJWTRequestBody(jwtRequestBody);
tempSig = auth.getToken(merchantConfig);
System.out.println("Authorization, Bearer " + tempSig.toString());
WriteLogAudit(200);
}
}
/**
*
* @param args
* : Contains getId entry.
* @throws Exception
*/
public static void main(String[] args) throws Exception {
new GetGenerateHeaders();
}
}
| true
|
93a16666ceca7fa7ca80c7b7435e1ee53bffdedf
|
Java
|
vandana25/Implementation-of-Design-Patterns
|
/src/Iterator_Pattern/LAStudents.java
|
UTF-8
| 631
| 3.078125
| 3
|
[] |
no_license
|
package Iterator_Pattern;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
public class LAStudents {
StudentData studentData;
ArrayList<StudentData> Students = new ArrayList<>();
public void addStudent(String l, String f, String m, String c, int cha, int che, int qp) {
Students.add(new StudentData(l, f, m, c, cha, che, qp));
Collections.sort(Students,StudentData.CompareName);
}
public ArrayList<StudentData> getStudents() {
return Students;
}
public Iterator<StudentData> iterator() {
return Students.iterator();
}
}
| true
|
a7efcc573507096fd6f4eff44b7df3f5e8f00f98
|
Java
|
marcus-deans/Logo-LSystem-IDE
|
/src/oolala/model/commands/conditionals/IfSameConditionalCommand.java
|
UTF-8
| 1,514
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
package oolala.model.commands.conditionals;
import java.util.ArrayList;
import javafx.scene.Group;
import oolala.model.ModelCreature;
import oolala.model.commands.Commands;
import oolala.model.instructions.CreatureInstruction;
/**
* @author marcusdeans
* <p>
* Purpose: Create a conditional command to execute if same species in front of ModelCreature
* Assumptions: Functioning ModelCreature and position; other values error-checked Dependencies:
* IfEntityConditionalComand, ConditionalCommand, ModelCommand, ModelCreature Example Usage: used
* for 'ifsame' command User Details: None, usage exactly as dictated by command entry pattern
* (error-checked)
*/
public class IfSameConditionalCommand extends IfEntityConditionalCommand {
boolean CHECKING_SAME_TYPE = true;
/**
* Create new IfSameConditionalCommand
*
* @param modelCreature ModelCreature object on which command will be imparted
* @param nextCommand conditional command that will be executed if conditions are met
*/
public IfSameConditionalCommand(ModelCreature modelCreature, int nextCommand,
ArrayList<CreatureInstruction> creatureInstructions, Group root) {
super(modelCreature, nextCommand, creatureInstructions, root);
myCommandName = Commands.IFSAME;
checkSame();
}
//check if there is a same entity (same species) in front of the ModelCreature
private void checkSame() {
if (determineEntityPresentAndNature(CHECKING_SAME_TYPE)) {
executeSpecifiedInstruction();
}
}
}
| true
|
81c18738e440a7477fb22755cf6bc1ca85350149
|
Java
|
torstorruste/CardRest
|
/src/test/java/org/superhelt/card/DatabaseGenerator.java
|
UTF-8
| 968
| 2.578125
| 3
|
[] |
no_license
|
package org.superhelt.card;
import org.superhelt.card.db.CsvParser;
import org.superhelt.card.db.SQLiteDao;
import org.superhelt.card.om.Player;
import org.superhelt.card.om.Round;
import org.superhelt.card.om.Score;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
public class DatabaseGenerator {
public static void main(String[] args) throws Exception {
Path basePath = Paths.get("src\\test\\resources");
CsvParser csvParser = new CsvParser(basePath);
List<Player> players = csvParser.getPlayers();
Map<Integer, List<Score>> scores = csvParser.getScores(players);
List<Round> rounds = csvParser.getRounds(scores);
SQLiteDao writer = new SQLiteDao("card.db");
players.forEach(writer::createPlayer);
rounds.forEach(r-> {
writer.createRound(r);
r.getScores().forEach(s->writer.createScore(r, s));
});
}
}
| true
|
b0379fa405428ff9917400c00022ba0eeb1dc01c
|
Java
|
opure/Hello-Git
|
/src/jichu/shuzu/array01.java
|
GB18030
| 244
| 2.796875
| 3
|
[] |
no_license
|
package jichu.shuzu;
public class array01{
public static void main(String args[]){
int score[] = {91,92,93,94,95,96} ; // ʹþ̬ʼ
for(int a :score){ // ѭ
System.out.println(a) ;
}
}
};
| true
|
83e093afec358ce15110fd7cbcdf8025e2b8b796
|
Java
|
Flipkart/typescriptpoet
|
/src/main/java/com/flipkart/typescriptpoet/Modifier.java
|
UTF-8
| 923
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2018 Flipkart
*
* 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.flipkart.typescriptpoet;
public enum Modifier {
PUBLIC,
PRIVATE,
STATIC,
EXPORT,
OVERRIDE,
ABSTRACT,
FINAL,
DEFAULT;
/**
* Returns this modifier's name in lowercase.
*/
public String toString() {
return name().toLowerCase(java.util.Locale.US);
}
}
| true
|
828b229d95722f4ff0c558919f929312e54426d6
|
Java
|
andy521/NetEase-Cloud-Music
|
/src/Test.java
|
UTF-8
| 770
| 2.375
| 2
|
[] |
no_license
|
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Test {
public static void main(String[] args) {
Document doc;
try {
URL url=new URL("https://music.163.com/playlist?id=925007233");
Proxy proxy=new Proxy(Proxy.Type.HTTP,new InetSocketAddress("178.217.32.142", 65205));
URLConnection c=url.openConnection(proxy);
doc =Jsoup.parse(c.getInputStream(),"UTF-8","https://music.163.com/playlist?id=925007233");
System.out.println(doc.select("ul").select("a[href*=song]"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
e6b26a007f1cf8c4678fa84200fd11d14a1ee0eb
|
Java
|
Insane-neal/ImageMap
|
/src/com/hck/imagemap/GuideActivity.java
|
UTF-8
| 1,902
| 2.15625
| 2
|
[] |
no_license
|
package com.hck.imagemap;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.hck.imagemap.adapter.MYViewPagerAdapter;
public class GuideActivity extends Activity
{
public static int width;
public static int height;
private ArrayList<View> views = new ArrayList<View>();
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_guide);
initViewPager();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
width = display.getWidth();
height = display.getHeight();
}
private void initViewPager()
{
ViewPager viewPager = (ViewPager) findViewById(R.id.guidePagerId);
View view1 = LayoutInflater.from(this).inflate(R.layout.guide01_item,
null);
View view2 = LayoutInflater.from(this).inflate(R.layout.guide02_item,
null);
View view3 = LayoutInflater.from(this).inflate(R.layout.guide03_item,
null);
views.add(view1);
views.add(view2);
views.add(view3);
MYViewPagerAdapter adapter = new MYViewPagerAdapter();
adapter.setViews(views);
viewPager.setAdapter(adapter);
}
public void onClick(View view)
{
Intent intent = new Intent(GuideActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
| true
|
cce40ffc4bfe12c0c7b023ba6b5c3b975dd826a1
|
Java
|
newrelic/newrelic-java-agent
|
/newrelic-agent/src/test/java/com/newrelic/agent/service/module/ShaChecksumsTest.java
|
UTF-8
| 892
| 1.789063
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.service.module;
import java.io.IOException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import org.junit.Assert;
import org.junit.Test;
public class ShaChecksumsTest {
@Test
public void test() throws NoSuchAlgorithmException, IOException {
URL url = JarCollectorServiceProcessorTest.getURL(JarCollectorServiceProcessorTest.JAR_PATH);
Assert.assertEquals("b82b735bc9ddee35c7fe6780d68f4a0256c4bd7a", ShaChecksums.computeSha(url));
}
@Test
public void testJarWithinJar() throws NoSuchAlgorithmException, IOException {
Assert.assertEquals("436bdbac7290779a1a89909827d8f24f632e3852", ShaChecksums.computeSha(JarCollectorServiceProcessorTest.getEmbeddedJarURL()));
}
}
| true
|
514026052c0c88b3b9f6d9d0927470a4c720b78a
|
Java
|
ebizon/mofluid-community-android
|
/moFluid/src/main/java/com/mofluid/utility_new/Callback.java
|
UTF-8
| 112
| 1.765625
| 2
|
[] |
no_license
|
package com.mofluid.utility_new;
public interface Callback {
void callback(Object o, int response_code);
}
| true
|
6dd4d0483b64ad65be0b248e8da299568dc7f309
|
Java
|
dmisabela/curso_java
|
/src/modificadores_de_acesso/Product.java
|
WINDOWS-1250
| 1,208
| 3.46875
| 3
|
[] |
no_license
|
package modificadores_de_acesso;
public class Product {
String name; //para ser acessvel a outra classe do mesmo pacote
private double price;
private int quantity;
public Product() {
}
public Product(String a, double b, int c) {
this.name = a;
this.price = b;
this.quantity = c;
}
public Product(String a, double b) {
this.name = a;
this.price = b;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getQuantity() {
return quantity;
}
public double totalValueInStock () {
return price * quantity;
}
public void addProducts (int quantity) {
this.quantity += quantity;
}
public void removeProducts (int quantity) {
this.quantity -= quantity;
}
public String toString() {
String productResult = (name
+ ", $ "
+ String.format("%.2f", price)
+ ", "
+ quantity
+ " units, Total: $ "
+ String.format("%.2f", totalValueInStock())
);
return productResult;
}
}
| true
|
2a29462e99ffa8ec162675af2c9b632222ef48a8
|
Java
|
hanjisoo/DAO1
|
/src/com/javaex/main/BookMain.java
|
UTF-8
| 288
| 2.046875
| 2
|
[] |
no_license
|
package com.javaex.main;
import com.javaex.dao.BookDao;
import com.javaex.vo.BookVo;
public class BookMain {
public static void main(String[] args) {
BookDao dao=new BookDao();
BookVo vo=new BookVo("나혼자산다","MBC","2017/07/21",8);
dao.insert(vo);
}
}
| true
|
fa1d325166f5c43ee2744ffb6099d6e138874d89
|
Java
|
arkapal100/Cipher_Web_apps
|
/FirstProject/src/main/java/com/example/demo/MovieController.java
|
UTF-8
| 1,872
| 2.625
| 3
|
[] |
no_license
|
package com.example.demo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MovieController {
// Dependency Injection
@Autowired
private MovieService movieservice;
@CrossOrigin
@RequestMapping("/movies")
public List<Movie> getAllMovies() {
return movieservice.getAllMovies();
}
// Write a fun to fetch a specific movie
@CrossOrigin
@RequestMapping("/movies/{id}") // id will be retrieved from url
public Movie getMovie(@PathVariable String id) {
return movieservice.getMovie(id);
}
@CrossOrigin
@RequestMapping(method = RequestMethod.POST, value = "/movies") // This method must be post as we are creating new
// movie
public void addMovie(@RequestBody Movie mov) {
movieservice.addMovie(mov);
}
//Define a fun to delete a movie
//URL: http://localhost:8081/movies/{ID} this will be url
@CrossOrigin
@RequestMapping(method = RequestMethod.DELETE, value = "/movies/{id}")
public void deleteMovie(@PathVariable String id) {
movieservice.deleteMovie(id);
}
//Fun for updating
//URL + Request body
// URL to get the id
// Requestbody : modified value <--- Request Method : PUT --->
@CrossOrigin
@RequestMapping(method = RequestMethod.PUT,value = "/movies/{id}")
public void updateMovie(@RequestBody Movie updatedMov,@PathVariable String id) {
movieservice.updateMovie(updatedMov,id);
}
}
| true
|
f720b2dd784a3de6394df9e034345dd21a650783
|
Java
|
vasileboris/espressoprogrammer-blog-code
|
/references/src/main/java/com/espressoprogrammer/references/MemoryUsageDAO.java
|
UTF-8
| 1,671
| 2.5625
| 3
|
[] |
no_license
|
package com.espressoprogrammer.references;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.util.List;
@Repository
public class MemoryUsageDAO {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private JdbcTemplate jdbcTemplate;
@PostConstruct
public void initialize() {
logger.info("Creating memory_usage table");
jdbcTemplate.execute("DROP TABLE memory_usage IF EXISTS");
jdbcTemplate.execute("CREATE TABLE memory_usage (created TIME, total_memory BIGINT, free_memory BIGINT)");
}
public void deleteAll() {
logger.info("Delete all from memory_usage table");
jdbcTemplate.execute("DELETE FROM memory_usage");
}
public void insert(MemoryUsage memoryUsage) {
jdbcTemplate.update("INSERT INTO memory_usage(created, total_memory, free_memory) " +
"VALUES (?,?,?)", memoryUsage.getCreated(),
memoryUsage.getTotalMemory(),
memoryUsage.getFreeMemory());
}
public List<MemoryUsage> retrieveAll() {
logger.info("Retrieve all from memory_usage table");
return jdbcTemplate.query(
"SELECT created, total_memory, free_memory FROM memory_usage ORDER BY created",
(rs, rowNum) -> new MemoryUsage(rs.getTime("created"),
rs.getLong("total_memory"),
rs.getLong("free_memory")));
}
}
| true
|
26b6a25614458a168308d6a9e51779e23997ab68
|
Java
|
liwensihan/KangMin_ERP
|
/src/main/java/com/yidu/service/ErpExpend/ErpExpendServiceImpl.java
|
UTF-8
| 512
| 1.570313
| 2
|
[] |
no_license
|
/**
*
*/
package com.yidu.service.ErpExpend;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yidu.dao.ErpExpendMapper;
import com.yidu.model.ErpExpend;
import com.yidu.util.Tools;
/**
* @author zhangwei
* 2017年10月19日
*/
@Service
public class ErpExpendServiceImpl implements ErpExpendService{
@Resource
private ErpExpendMapper erpExpendMapper;
}
| true
|
3752f5a7681c1a43bc4cc6d83d43694a53a5bf9d
|
Java
|
Rainboz/StudyJava
|
/src/main/java/com/zhb/javaSE/package201904/package_object/obj_all_13_abstract/package_04/DC.java
|
UTF-8
| 399
| 2.71875
| 3
|
[] |
no_license
|
package com.zhb.javaSE.package201904.package_object.obj_all_13_abstract.package_04;
/**
* @program: StudyJava
* @description:
* @author: rainboz
* @create: 2019-04-25 11:55
**/
public class DC implements USB {
@Override
public void connect() {
System.out.println("USB IS DC");
}
public void method1(){
System.out.println("method1: DC独有的方法");
}
}
| true
|
b54aced0f14b422d8781996ba8fc9dc6cab8a574
|
Java
|
97UserMubai/GraduationDesign
|
/我的毕业web/src/main/java/systemOa/bean/BusinessUpdateApplication.java
|
UTF-8
| 4,249
| 2.125
| 2
|
[] |
no_license
|
package systemOa.bean;
import java.util.Date;
public class BusinessUpdateApplication {
private String messageId;
private String style;
private String employeeId;
private String employeeName;
private String department;
private Date applyTime;
private String applyEvent;
private String applyReason;
private String businessId;
private String businessName;
private String userId;
private String userName;
private int status;
private String provePerson;
private String proveReason;
private Date proveTime;
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public String getApplyEvent() {
return applyEvent;
}
public void setApplyEvent(String applyEvent) {
this.applyEvent = applyEvent;
}
public String getApplyReason() {
return applyReason;
}
public void setApplyReason(String applyReason) {
this.applyReason = applyReason;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getProvePerson() {
return provePerson;
}
public void setProvePerson(String provePerson) {
this.provePerson = provePerson;
}
public String getProveReason() {
return proveReason;
}
public void setProveReason(String proveReason) {
this.proveReason = proveReason;
}
public Date getProveTime() {
return proveTime;
}
public void setProveTime(Date proveTime) {
this.proveTime = proveTime;
}
public BusinessUpdateApplication(String messageId, String style, String employeeId,
String employeeName, String department, Date applyTime,
String applyEvent, String applyReason, String businessId,
String businessName, String userId, String userName,
int status, String provePerson, String proveReason,
Date proveTime) {
this.messageId = messageId;
this.style = style;
this.employeeId = employeeId;
this.employeeName = employeeName;
this.department = department;
this.applyTime = applyTime;
this.applyEvent = applyEvent;
this.applyReason = applyReason;
this.businessId = businessId;
this.businessName = businessName;
this.userId = userId;
this.userName = userName;
this.status = status;
this.provePerson = provePerson;
this.proveReason = proveReason;
this.proveTime = proveTime;
}
}
| true
|
ff65d78faa51732d4bed37978bcae0335777d100
|
Java
|
Bradone911/LandListView
|
/app/src/main/java/com/bignerdranch/android/landlistview/Main2Activity.java
|
UTF-8
| 715
| 2
| 2
|
[] |
no_license
|
package com.bignerdranch.android.landlistview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(getIntent().getStringExtra("Art_Piece"));
imageView.setImageResource(getIntent().getIntExtra("Art",R.drawable.spiraljetty));
}
}
| true
|
5518f38b0ae13457b073ae7356aa92e7248d46e0
|
Java
|
Liuly-liuly/java-thread-jvm
|
/src/main/java/com/concurrency/chapter13/Animal.java
|
UTF-8
| 546
| 3.015625
| 3
|
[] |
no_license
|
package com.concurrency.chapter13;
/**
* @version 1.0
* @Description: 1367636569@qq.com
* @Auther: Liuly
* @Date: 2020/2/3
* @since JDK 1.8
*/
public class Animal {
public static final String str = "change job";
private Animal(){}
public Animal(String s){}
public void print(){
System.out.println(str);
}
public void sl(){
System.out.println("sleeping");
}
public void run (){
System.out.println("running");
}
public void eat(){
System.out.println("eating");
}
}
| true
|
3d1bf72092d9d4e3dd553bff9a5d53bb383a89e5
|
Java
|
Aptxsh/SpringMyTest
|
/src/test3/review/StudentDao.java
|
UTF-8
| 1,345
| 2.890625
| 3
|
[] |
no_license
|
package test3.review;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class StudentDao implements IStudentDao {
@Autowired
private DataSource dataSource;
public StudentDao(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public List<Student> findAll() {
List<Student> list = new ArrayList<>();
Connection conn = null;
try {
conn = dataSource.getConnection();
String sql = "select S_NUMBER, S_NAME, S_GENDER, S_AGE, S_MAJOR from STUDENTS";
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
int number = rs.getInt(1);
String name = rs.getString(2);
Gender gender = Gender.valueOf(rs.getString(3));
int age = rs.getInt(4);
String major = rs.getString(5);
list.add(new Student(number, name, gender, age, major));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
}
| true
|
47f69e510b971a564aad30713909df6623c8f155
|
Java
|
6638112/mps-1
|
/src/main/java/cn/damei/entity/modules/OrderManagerChange.java
|
UTF-8
| 2,418
| 1.820313
| 2
|
[
"Apache-2.0"
] |
permissive
|
package cn.damei.entity.modules;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import cn.damei.common.persistence.DataEntity;
public class OrderManagerChange extends DataEntity<OrderManagerChange> {
private static final long serialVersionUID = 1L;
private Integer storeId;
private String orderNumber;
private String customerName;
private String customerPhone;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date changeDate;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date endChangeDate;
private String oldManagerName;
private String oldManagerPhone;
private String newManagerName;
private String newManagerPhone;
private String createName;
public Integer getStoreId() {
return storeId;
}
public void setStoreId(Integer storeId) {
this.storeId = storeId;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerPhone() {
return customerPhone;
}
public void setCustomerPhone(String customerPhone) {
this.customerPhone = customerPhone;
}
public Date getChangeDate() {
return changeDate;
}
public void setChangeDate(Date changeDate) {
this.changeDate = changeDate;
}
public Date getEndChangeDate() {
return endChangeDate;
}
public void setEndChangeDate(Date endChangeDate) {
this.endChangeDate = endChangeDate;
}
public String getOldManagerName() {
return oldManagerName;
}
public void setOldManagerName(String oldManagerName) {
this.oldManagerName = oldManagerName;
}
public String getOldManagerPhone() {
return oldManagerPhone;
}
public void setOldManagerPhone(String oldManagerPhone) {
this.oldManagerPhone = oldManagerPhone;
}
public String getNewManagerName() {
return newManagerName;
}
public void setNewManagerName(String newManagerName) {
this.newManagerName = newManagerName;
}
public String getNewManagerPhone() {
return newManagerPhone;
}
public void setNewManagerPhone(String newManagerPhone) {
this.newManagerPhone = newManagerPhone;
}
public String getCreateName() {
return createName;
}
public void setCreateName(String createName) {
this.createName = createName;
}
}
| true
|
8808c44ca077dfa448ff5e7bdbd3c2981f3c7f05
|
Java
|
TeamTitanz/Warana
|
/src/main/java/com/cse/warana/utility/Graph/extraction/BurnerClass.java
|
UTF-8
| 875
| 2.203125
| 2
|
[] |
no_license
|
package com.cse.warana.utility.Graph.extraction;
import com.cse.warana.utility.Graph.network.NetworkConnectionManager;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.Hashtable;
/**
* Created by Anushka on 2015-01-03.
*/
public class BurnerClass {
public NetworkConnectionManager networkConnectionManager;
protected Hashtable<String, Boolean> wordlist;
public String termsFilePath ;
public BurnerClass(String root) {
networkConnectionManager = new NetworkConnectionManager();
wordlist = new Hashtable<String, Boolean>();
termsFilePath = root + "/Docs/Terms/";
}
public Document getPage(String urlString) throws IOException {
networkConnectionManager.DomainName(urlString);
Document mainPage = networkConnectionManager.URLgraber(urlString);
return mainPage;
}
}
| true
|
10aa40a823494561edd9646155e130b4d596e1ac
|
Java
|
victorolave/AbstractFactory_Java
|
/src/Vehicle/VehicleFactory.java
|
UTF-8
| 619
| 2.9375
| 3
|
[] |
no_license
|
package Vehicle;
import Car.Car;
import SUV.Suv;
public abstract class VehicleFactory {
public static final String LUXURY_VEHICLE = "Luxury";
public static final String NON_LUXURY_VEHICLE = "NonLuxury";
public abstract Car getCar();
public abstract Suv getSuv();
public static VehicleFactory getVehicleFactory(String type)
{
if(type.equals(VehicleFactory.LUXURY_VEHICLE))
return new LuxuryVehicleFactory();
if(type.equals(VehicleFactory.NON_LUXURY_VEHICLE))
return new NonLuxuryVehicleFactory();
return new LuxuryVehicleFactory();
}
}
| true
|
2704d221e093970a86ee2b4ee3260c044ead90d3
|
Java
|
HexaHexage/ExerciceSTE
|
/sudoku/Sudoku/src/ste/sudoku/etape6Bis/exceptions/DoublonSudokuException.java
|
UTF-8
| 455
| 2.40625
| 2
|
[] |
no_license
|
package ste.sudoku.etape6Bis.exceptions;
public class DoublonSudokuException extends SudokuException {
private static final long serialVersionUID = 1L;
public DoublonSudokuException() {
}
public DoublonSudokuException(String message) {
super(message);
}
public DoublonSudokuException(Throwable cause) {
super(cause);
}
public DoublonSudokuException(String message, Throwable cause) {
super(message, cause);
}
}
| true
|
9d1aa7f6c236d2f8bb1ba0d13f0f6473eb484947
|
Java
|
sallymah/YHDP
|
/src/main/tw/com/hyweb/svc/yhdp/batch/summary/computeRmCard/AppointJob.java
|
UTF-8
| 15,033
| 1.765625
| 2
|
[] |
no_license
|
package tw.com.hyweb.svc.yhdp.batch.summary.computeRmCard;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
import tw.com.hyweb.core.cp.batch.preoperation.PreOperationUtil;
import tw.com.hyweb.core.cp.batch.util.beans.TransBean;
import tw.com.hyweb.core.cp.batch.util.beans.TransDtlBean;
import tw.com.hyweb.core.cp.common.misc.Constants;
import tw.com.hyweb.core.cp.common.misc.DateRange;
import tw.com.hyweb.service.db.info.TbAppointReloadDtlInfo;
import tw.com.hyweb.service.db.info.TbBonusIssDefInfo;
import tw.com.hyweb.service.db.info.TbCardBalInfo;
import tw.com.hyweb.service.db.info.TbCardInfo;
import tw.com.hyweb.service.db.info.TbTermBatchInfo;
import tw.com.hyweb.service.db.info.TbTransDtlInfo;
import tw.com.hyweb.service.db.info.TbTransInfo;
import tw.com.hyweb.service.db.mgr.TbAppointReloadDtlMgr;
import tw.com.hyweb.svc.yhdp.online.LMSContext;
import tw.com.hyweb.util.Calc;
import tw.com.hyweb.util.string.StringUtil;
public class AppointJob {
private static final Logger logger = Logger.getLogger(AppointJob.class);
private final String batchDate;
private final TbCardInfo cardInfo;
private final List<TbBonusIssDefInfo> tbBonusIssDefList;
private final TbTermBatchInfo terminalBatch;
private final String lmsInvoiceNumber;
private final Map<String, String> apt;
private final HashMap<String, Double> appBonusQtys;
private final List<TbCardBalInfo> cardBalResults;
private List<TbAppointReloadDtlInfo> appDtlList;
private List<String> sqlList = new ArrayList<>();
public AppointJob(String batchDate, TbCardInfo cardInfo, List<TbCardBalInfo> cardBalResults,
List<TbBonusIssDefInfo> tbBonusIssDefList, TbTermBatchInfo terminalBatch, String lmsInvoiceNumber,
Map<String, String> apt, HashMap<String, Double> appBonusQtys) {
// TODO Auto-generated constructor stub
this.batchDate = batchDate;
this.cardInfo = cardInfo;
this.cardBalResults = cardBalResults;
this.tbBonusIssDefList = tbBonusIssDefList;
this.terminalBatch = terminalBatch;
this.lmsInvoiceNumber = lmsInvoiceNumber;
this.apt = apt;
this.appBonusQtys = appBonusQtys;
}
public void init(Connection connection) throws SQLException {
// TODO Auto-generated method stub
appDtlList = makeAppointReloadDetail(connection);
}
private List<TbAppointReloadDtlInfo> makeAppointReloadDetail(Connection connection) throws SQLException
{
StringBuffer sqlCmd = new StringBuffer("");
sqlCmd.append("bonus_base = ");
sqlCmd.append(StringUtil.toSqlValueWithSQuote(apt.get("BONUS_BASE")));
sqlCmd.append("AND balance_type = ");
sqlCmd.append(StringUtil.toSqlValueWithSQuote(apt.get("BALANCE_TYPE")));
sqlCmd.append("AND balance_id = ");
sqlCmd.append(StringUtil.toSqlValueWithSQuote(apt.get("BALANCE_ID")));
sqlCmd.append("AND ar_serno = ");
sqlCmd.append(StringUtil.toSqlValueWithSQuote(apt.get("AR_SERNO")));
Vector<TbAppointReloadDtlInfo> results = new Vector();
TbAppointReloadDtlMgr mgr = new TbAppointReloadDtlMgr(connection);
mgr.queryMultiple(sqlCmd.toString(), results);
return results;
}
/*private List<TbCardBalInfo> makeCardBal(Connection connection) throws SQLException
{
StringBuffer cardBalSqlCmd = new StringBuffer("");
cardBalSqlCmd.append("CARD_NO = ");
cardBalSqlCmd.append(StringUtil.toSqlValueWithSQuote(apt.get("CARD_NO")));
cardBalSqlCmd.append("AND EXPIRY_DATE = ");
cardBalSqlCmd.append(apt.get("EXPIRY_DATE"));
cardBalSqlCmd.append(" AND BONUS_SDATE <= ");
cardBalSqlCmd.append(StringUtil.toSqlValueWithSQuote(batchDate));
cardBalSqlCmd.append(" AND BONUS_EDATE >= ");
cardBalSqlCmd.append(StringUtil.toSqlValueWithSQuote(batchDate));
Vector<TbCardBalInfo> results = new Vector();
TbCardBalMgr mgr = new TbCardBalMgr(connection);
mgr.queryMultiple(cardBalSqlCmd.toString(), results);
return results;
}*/
public void action(Connection connection) throws Exception {
// TODO Auto-generated method stub
/*StringBuffer sql = new StringBuffer();
Vector<String> params = new Vector<String>();
sql.append("UPDATE TB_CARD SET ");
sql.append("LAST_TXN_DATE = ").append(StringUtil.toSqlValueWithSQuote(batchDate));
sql.append("WHERE CARD_NO = ").append(StringUtil.toSqlValueWithSQuote(cardInfo.getCardNo()));
sql.append("AND EXPIRY_DATE = ").append(StringUtil.toSqlValueWithSQuote(cardInfo.getExpiryDate()));
sqlList.add(sql.toString());*/
TbTransInfo transaction = addTransaction(connection);
addDetails(connection, transaction);
updateAppoint();
}
private void updateAppoint() {
// TODO Auto-generated method stub
StringBuffer sql = new StringBuffer();
sql.append(" UPDATE TB_APPOINT_RELOAD");
sql.append(" SET STATUS = ").append(StringUtil.toSqlValueWithSQuote("1"));
sql.append(" ,BATCH_RCODE = ").append(StringUtil.toSqlValueWithSQuote(Constants.RCODE_0000_OK));
sql.append(" ,DW_TXN_DATE = ").append(StringUtil.toSqlValueWithSQuote(terminalBatch.getTermSettleDate()));
sql.append(" ,DW_TXN_TIME = ").append(StringUtil.toSqlValueWithSQuote(terminalBatch.getTermSettleTime()));
sql.append(" ,DW_LMS_INVOICE_NO = ").append(StringUtil.toSqlValueWithSQuote(lmsInvoiceNumber));
sql.append(" WHERE BONUS_BASE = ").append(StringUtil.toSqlValueWithSQuote(apt.get("BONUS_BASE")));
sql.append(" AND BALANCE_TYPE = ").append(StringUtil.toSqlValueWithSQuote(apt.get("BALANCE_TYPE")));
sql.append(" AND BALANCE_ID = ").append(StringUtil.toSqlValueWithSQuote(apt.get("BALANCE_ID")));
sql.append(" AND AR_SERNO = ").append(StringUtil.toSqlValueWithSQuote(apt.get("AR_SERNO")));
sqlList.add(sql.toString());
}
private TbTransInfo addTransaction(Connection connection) throws Exception
{
TbTransInfo transaction = makeTransaction(connection);
transaction.setTxnSrc(terminalBatch.getTxnSrc());
transaction.setBatchNo(terminalBatch.getBatchNo());
transaction.setTermSettleDate(terminalBatch.getTermSettleDate());
transaction.setTermSettleTime(terminalBatch.getTermSettleTime());
transaction.setLmsInvoiceNo(lmsInvoiceNumber);
if (StringUtil.isEmpty(transaction.getTxnDate()))
transaction.setTxnDate(terminalBatch.getTermSettleDate());
if (StringUtil.isEmpty(transaction.getTxnTime()))
transaction.setTxnTime(terminalBatch.getTermSettleTime());
transaction.setTermDate(transaction.getTxnDate());
transaction.setTermTime(transaction.getTxnTime());
if(StringUtil.isEmpty(transaction.getIssMemId()) & !StringUtil.isEmpty(transaction.getCardNo()) & !StringUtil.isEmpty(transaction.getExpiryDate()))
{
transaction.setIssMemId(cardInfo.getMemId());
}
transaction.setCutDate(terminalBatch.getCutDate());
transaction.setCutTime(terminalBatch.getCutTime());
TransBean bean = new TransBean();
bean.setTransInfo(transaction);
sqlList.add(bean.getInsertSql());
return transaction;
}
protected TbTransInfo makeTransaction(Connection connection)
throws Exception {
TbTransInfo transInfo = new TbTransInfo();
transInfo.setCardNo(apt.get("CARD_NO"));
transInfo.setExpiryDate(apt.get("EXPIRY_DATE"));
transInfo.setPCode(Constants.PCODE_7307);
//需求單號 #394 虛擬指定加值的收單代號為: 00001001
String acqMemId = (!apt.get("ACQ_MEM_ID").toString().equals("00000000"))
? apt.get("ACQ_MEM_ID").toString():"00001001";
transInfo.setAcqMemId(acqMemId);
transInfo.setMerchId(apt.get("MERCH_ID"));
transInfo.setTermDate(terminalBatch.getTermSettleDate());
transInfo.setTermTime(terminalBatch.getTermSettleTime());
double[] sumBefore = new double[LMSContext.getMaxPoint()];
double[] sumBeforeCr = new double[LMSContext.getMaxPoint()];
double[] sumBeforeDb = new double[LMSContext.getMaxPoint()];
double[] sumAfter = new double[LMSContext.getMaxPoint()];
for ( int i = 0; i < LMSContext.getMaxPoint(); i ++ ){
sumBefore[i] = 0;
sumBeforeCr[i] = 0;
sumBeforeDb[i] = 0;
sumAfter[i] = 0;
}
for ( TbBonusIssDefInfo tbBonusIssDefInfo : tbBonusIssDefList ){
if ( cardInfo.getMemId().equals(tbBonusIssDefInfo.getMemId())){
for (TbCardBalInfo infoDtl : cardBalResults){
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint1BonusId()))
sumBefore[0] = sumBefore[0] + infoDtl.getCrBonusQty().doubleValue()- infoDtl.getDbBonusQty().doubleValue() + infoDtl.getBalBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint2BonusId()))
sumBefore[1] = sumBefore[1] + infoDtl.getCrBonusQty().doubleValue()- infoDtl.getDbBonusQty().doubleValue() + infoDtl.getBalBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint3BonusId()))
sumBefore[2] = sumBefore[2] + infoDtl.getCrBonusQty().doubleValue()- infoDtl.getDbBonusQty().doubleValue() + infoDtl.getBalBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint4BonusId()))
sumBefore[3] = sumBefore[3] + infoDtl.getCrBonusQty().doubleValue()- infoDtl.getDbBonusQty().doubleValue() + infoDtl.getBalBonusQty().doubleValue();
}
for (TbAppointReloadDtlInfo infoDtl : appDtlList){
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint1BonusId()))
sumBeforeCr[0] = sumBeforeCr[0] + infoDtl.getBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint2BonusId()))
sumBeforeCr[1] = sumBeforeCr[1] + infoDtl.getBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint3BonusId()))
sumBeforeCr[2] = sumBeforeCr[2] + infoDtl.getBonusQty().doubleValue();
if (infoDtl.getBonusId().equalsIgnoreCase(tbBonusIssDefInfo.getPoint4BonusId()))
sumBeforeCr[3] = sumBeforeCr[3] + infoDtl.getBonusQty().doubleValue();
}
for ( int i = 0; i < LMSContext.getMaxPoint(); i ++ ){
sumAfter[i] = sumBefore[i] + sumBeforeCr[i];
}
}
}
transInfo.setChipPoint1Before(sumBefore[0]);
transInfo.setChipPoint2Before(sumBefore[1]);
transInfo.setChipPoint3Before(sumBefore[2]);
transInfo.setChipPoint4Before(sumBefore[3]);
transInfo.setChipPoint1Cr(sumBeforeCr[0]);
transInfo.setChipPoint2Cr(sumBeforeCr[1]);
transInfo.setChipPoint3Cr(sumBeforeCr[2]);
transInfo.setChipPoint4Cr(sumBeforeCr[3]);
transInfo.setChipPoint1Db(sumBeforeDb[0]);
transInfo.setChipPoint2Db(sumBeforeDb[1]);
transInfo.setChipPoint3Db(sumBeforeDb[2]);
transInfo.setChipPoint4Db(sumBeforeDb[3]);
transInfo.setChipPoint1After(sumAfter[0]);
transInfo.setChipPoint2After(sumAfter[1]);
transInfo.setChipPoint3After(sumAfter[2]);
transInfo.setChipPoint4After(sumAfter[3]);
return transInfo;
}
private void addDetails(Connection connection, TbTransInfo transaction) throws Exception
{
for (TbTransDtlInfo detail : makeTransactionDetails(connection))
{
if (appBonusQtys.get(detail.getBonusId()) == null){
appBonusQtys.put(detail.getBonusId(), detail.getBonusCrQty().doubleValue());
}
else{
appBonusQtys.put(detail.getBonusId(),
Calc.add(appBonusQtys.get(detail.getBonusId()), detail.getBonusCrQty().doubleValue()));
}
sqlList.add(PreOperationUtil.getBalCrDbSql(connection, transaction, detail));
sqlList.add(addDetail(connection, transaction, detail));
}
}
protected Collection<TbTransDtlInfo> makeTransactionDetails(Connection connection) throws Exception {
List<TbTransDtlInfo> transDtlInfo = new ArrayList();
for (TbAppointReloadDtlInfo infoDtl : appDtlList){
transDtlInfo.add(makeTransactionDetail(connection, infoDtl));
}
return transDtlInfo;
}
protected TbTransDtlInfo makeTransactionDetail(Connection connection, TbAppointReloadDtlInfo appointReloadDtlInfo)
throws Exception
{
logger.info("call campaign : bonus sdate edate");
DateRange range = PreOperationUtil.getBonusSdateEdate(connection, terminalBatch.getTermSettleDate(), apt.get("BALANCE_TYPE"),
apt.get("CARD_NO"), apt.get("EXPIRY_DATE"), appointReloadDtlInfo.getBonusId(),
appointReloadDtlInfo.getBonusSdate(), appointReloadDtlInfo.getBonusEdate());
logger.info("range:" + range);
TbTransDtlInfo transDtlInfo = new TbTransDtlInfo();
transDtlInfo.setTxnCode(Constants.TXNCODE_8817);
transDtlInfo.setCutDate(terminalBatch.getCutDate());
transDtlInfo.setRegionId(apt.get("REGION_ID"));
transDtlInfo.setBonusBase(apt.get("BONUS_BASE"));
transDtlInfo.setBalanceType(apt.get("BALANCE_TYPE"));
transDtlInfo.setBalanceId(apt.get("BALANCE_ID"));
transDtlInfo.setBonusId(appointReloadDtlInfo.getBonusId());
transDtlInfo.setBonusSdate(range.getStartDate());
transDtlInfo.setBonusEdate(range.getEndDate());
transDtlInfo.setBonusQty(appointReloadDtlInfo.getBonusQty());
transDtlInfo.setBalProcDate("00000000");
transDtlInfo.setBonusBeforeQty(0);
for (TbCardBalInfo infoDtl : cardBalResults){
if ( infoDtl.getBonusId().equalsIgnoreCase(transDtlInfo.getBonusId())
&& infoDtl.getBonusSdate().equalsIgnoreCase(transDtlInfo.getBonusSdate())
&& infoDtl.getBonusEdate().equalsIgnoreCase(transDtlInfo.getBonusEdate()) ){
transDtlInfo.setBonusBeforeQty(infoDtl.getCrBonusQty().doubleValue()- infoDtl.getDbBonusQty().doubleValue() + infoDtl.getBalBonusQty().doubleValue());
}
}
transDtlInfo.setBonusCrQty(appointReloadDtlInfo.getBonusQty());
transDtlInfo.setBonusAfterQty(transDtlInfo.getBonusBeforeQty().doubleValue() + transDtlInfo.getBonusCrQty().doubleValue());
return transDtlInfo;
}
private String addDetail(Connection connection, TbTransInfo transaction, TbTransDtlInfo detail) throws SQLException
{
/*找Region id*/
if(StringUtil.isEmpty(detail.getRegionId()) & !StringUtil.isEmpty(transaction.getCardNo()) & !StringUtil.isEmpty(transaction.getExpiryDate()))
{
detail.setRegionId(cardInfo.getRegionId());
}
TransDtlBean bean = new TransDtlBean();
bean.setTransInfo(transaction);
bean.setTransDtlInfo(detail);
return bean.getInsertSql();
}
public List<String> getSqlList() {
return sqlList;
}
public void setSqlList(List<String> sqlList) {
this.sqlList = sqlList;
}
}
| true
|
d2e4898481e07c11584ce7d2449b0d3cfaf89433
|
Java
|
jmcabandara/camel
|
/dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/main/java/org/apache/camel/dsl/yaml/deserializers/NamedBeanDeserializer.java
|
UTF-8
| 3,192
| 1.921875
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dsl.yaml.deserializers;
import org.apache.camel.dsl.yaml.common.YamlDeserializerBase;
import org.apache.camel.dsl.yaml.common.YamlDeserializerResolver;
import org.apache.camel.dsl.yaml.common.exception.UnsupportedFieldException;
import org.apache.camel.spi.annotations.YamlProperty;
import org.apache.camel.spi.annotations.YamlType;
import org.apache.camel.util.ObjectHelper;
import org.snakeyaml.engine.v2.nodes.MappingNode;
import org.snakeyaml.engine.v2.nodes.Node;
import org.snakeyaml.engine.v2.nodes.NodeTuple;
@YamlType(
types = NamedBeanDefinition.class,
order = YamlDeserializerResolver.ORDER_DEFAULT,
properties = {
@YamlProperty(name = "name", type = "string", required = true),
@YamlProperty(name = "type", type = "string", required = true),
@YamlProperty(name = "properties", type = "object")
})
public class NamedBeanDeserializer extends YamlDeserializerBase<NamedBeanDefinition> {
public NamedBeanDeserializer() {
super(NamedBeanDefinition.class);
}
@Override
protected NamedBeanDefinition newInstance() {
return new NamedBeanDefinition();
}
@Override
public NamedBeanDefinition construct(Node node) {
final MappingNode bn = asMappingNode(node);
final NamedBeanDefinition answer = new NamedBeanDefinition();
for (NodeTuple tuple : bn.getValue()) {
final String key = asText(tuple.getKeyNode());
final Node val = tuple.getValueNode();
switch (key) {
case "name":
answer.setName(asText(val));
break;
case "type":
String type = asText(val);
if (!type.startsWith("#class:")) {
type = "#class:" + type;
}
answer.setType(type);
break;
case "properties":
answer.setProperties(asMap(val));
break;
default:
throw new UnsupportedFieldException(val, key);
}
}
ObjectHelper.notNull(answer.getName(), "The bean name must be set");
ObjectHelper.notNull(answer.getType(), "The bean type must be set");
return answer;
}
}
| true
|
705d09b1b44babdb618625715440ba6fe9c7f47e
|
Java
|
wordlessly/jftp
|
/src/main/java/com/myjavaworld/jftp/TransferModesPrefsPanel.java
|
UTF-8
| 7,230
| 2.09375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2012 jMethods, Inc.
*
* 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.myjavaworld.jftp;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import com.myjavaworld.ftp.FTPConstants;
import com.myjavaworld.gui.MComboBox;
import com.myjavaworld.gui.MLabel;
import com.myjavaworld.gui.MScrollPane;
import com.myjavaworld.gui.MTable;
import com.myjavaworld.gui.MTableCellRenderer;
import com.myjavaworld.gui.MTextField;
import com.myjavaworld.util.ResourceLoader;
/**
* A supporting panel used by the preferences dialog.
*
* @author Sai Pullabhotla, psai [at] jMethods [dot] com
* @version 2.0
*
*/
public class TransferModesPrefsPanel extends JPanel {
private static final ResourceBundle resources = ResourceLoader
.getBundle("com.myjavaworld.jftp.TransferModesPrefsPanel");
private static final String[] COLUMN_NAMES = {
resources.getString("text.fileType"),
resources.getString("text.transferMode") };
private static final String[] TYPE_NAMES = { "ASCII", "Binary" };
private TypesTableModel model = null;
private MTable table = null;
private MComboBox comboDefaultTransferMode = null;
public TransferModesPrefsPanel() {
super();
setLayout(new GridBagLayout());
initComponents();
configureTable();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
public boolean validateFields() {
return true;
}
public void populateScreen() {
populateScreen(JFTP.prefs);
}
public void populateScreen(JFTPPreferences prefs) {
comboDefaultTransferMode.setSelectedIndex(prefs
.getDefaultTransferType() - 1);
model.setData(prefs.getTransferTypes());
}
public void saveChanges() {
int rowCount = model.getRowCount();
Map map = new TreeMap();
for (int i = 0; i < rowCount; i++) {
String extension = (String) model.getValueAt(i, 0);
if (extension.trim().length() > 0) {
map.put(extension, model.getValueAt(i, 1));
}
}
JFTP.prefs.setTransferTypes(map);
JFTP.prefs.setDefaultTransferType(comboDefaultTransferMode
.getSelectedIndex() + 1);
}
private void initComponents() {
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
// model = new TypesTableModel(JFTP.prefs.getTransferTypes());
model = new TypesTableModel();
table = new MTable(model);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
c.gridheight = 2;
c.weightx = 0.5;
c.weighty = 0.5;
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(12, 12, 12, 12);
MScrollPane scroller = new MScrollPane(table);
add(scroller, c);
MLabel labDefaultTransferMode = new MLabel(
resources.getString("text.defaultTransferMode"));
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(0, 12, 12, 12);
add(labDefaultTransferMode, c);
comboDefaultTransferMode = new MComboBox(TYPE_NAMES);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
c.weightx = 0.5;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 0, 12, 12);
add(comboDefaultTransferMode, c);
populateScreen();
}
private void configureTable() {
table.setDefaultRenderer(Object.class, new MTableCellRenderer());
table.setDefaultRenderer(Integer.class, new TransferTypeCellRenderer());
MComboBox comboTypes = new MComboBox(TYPE_NAMES);
table.setDefaultEditor(Integer.class, new DefaultCellEditor(comboTypes));
DefaultCellEditor fileTypeEditor = new DefaultCellEditor(
new MTextField());
fileTypeEditor.setClickCountToStart(1);
table.setDefaultEditor(Object.class, fileTypeEditor);
}
private class TypesTableModel extends AbstractTableModel {
private Vector extensions = null;
private Vector types = null;
public TypesTableModel() {
this(new TreeMap());
}
public TypesTableModel(Map map) {
setData(map);
}
public void setData(Map map) {
if (map == null) {
map = new TreeMap();
}
extensions = new Vector(map.size());
types = new Vector(map.size());
for (Iterator i = map.keySet().iterator(); i.hasNext();) {
String key = (String) (i.next());
extensions.add(key);
types.add(map.get(key));
}
addEmptyRow();
fireTableDataChanged();
}
public int getRowCount() {
return extensions.size();
}
public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override
public String getColumnName(int col) {
return COLUMN_NAMES[col];
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return extensions.get(row);
} else {
return types.get(row);
}
}
@Override
public void setValueAt(Object value, int row, int col) {
String str = value.toString();
if (col == 0) {
extensions.set(row, str.toUpperCase());
if (row == extensions.size() - 1 && str.trim().length() != 0) {
addEmptyRow();
}
} else {
int type = str.equals(TYPE_NAMES[0]) ? FTPConstants.TYPE_ASCII
: FTPConstants.TYPE_BINARY;
types.set(row, new Integer(type));
}
fireTableDataChanged();
}
@Override
public Class getColumnClass(int col) {
if (col == 1) {
return Integer.class;
}
return Object.class;
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
private void addEmptyRow() {
extensions.add("");
types.add(new Integer(FTPConstants.TYPE_ASCII));
}
}
private static class TransferTypeCellRenderer extends MTableCellRenderer {
public TransferTypeCellRenderer() {
super();
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int col) {
int type = ((Integer) value).intValue();
setText(TYPE_NAMES[type - 1]);
setBackground(isSelected ? table.getSelectionBackground() : table
.getBackground());
setForeground(isSelected ? table.getSelectionForeground() : table
.getForeground());
setFont(table.getFont());
return this;
}
}
}
| true
|
db765381a8faaa3201abbcbad9803838bcd05144
|
Java
|
learninginb/labWeb
|
/src/java/common/com/simulation/common/util/TcpipUtil.java
|
UTF-8
| 1,448
| 2.390625
| 2
|
[] |
no_license
|
package com.simulation.common.util;
import javax.servlet.http.HttpServletRequest;
/**
* tcp/ip 工具类
* Description:
* @ClassName: TcpipUtil
* @author Jalf
* @since 2016年5月31日 上午9:20:28
* Copyright foxtail All right reserved.
*/
public class TcpipUtil {
/**
* Description:获得ip地址
* @Title: getIpAddr
* @author Jalf
* @since 2016年5月31日 上午9:20:45
* @param request
* @return
* Copyright foxtail All right reserved.
*/
public static String getIpAddr(HttpServletRequest request)
{
String ip = request.getHeader("x-forwarded-for");
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* Description:获得mac地址
* @Title: getMacIp
* @author Jalf
* @since 2016年5月31日 上午9:21:05
* @param sip
* @return
* @throws Exception
* Copyright foxtail All right reserved.
*/
public static String getMacIp(String sip) throws Exception{
String smac = "";
UdpGetClientMacAddr umac = new UdpGetClientMacAddr(sip);
smac = umac.GetRemoteMacAddr();
return smac;
}
}
| true
|
60c333a7b392dfaadcc4f9c6739bbee369f29dca
|
Java
|
JetBrains/intellij-community
|
/java/java-tests/testData/codeInsight/replaceStringFormat/beforeStringFormatWithArgsAndTokensPassedToPrintf.java
|
UTF-8
| 921
| 3.15625
| 3
|
[
"Apache-2.0"
] |
permissive
|
// "Fix all 'Redundant call to 'String.format()'' problems in file" "true"
import java.io.PrintStream;
import java.util.Locale;
import static java.lang.String.format;
class Main {
static {
System.out.<caret>printf(/* one */ "hello" /* two */);
System.out.printf(/* one */ ("hello") /* two */;
System.out.printf(((/* one */ ("hello") /* two */)));
}
Main() {
System.out.printf(/* one */ ("hello") /* two */);
System.out.printf(((/* one */ ("hello") /* two */)));
}
void f() {
System.out.printf(/* one */ ("hello") /* two */);
System.out.printf(((/* one */ ("hello") /* two */)));
}
void out(PrintStream printer) {
printer.printf(/* one */ ("hello") /* two */);
printer.printf(((/* one */ ("hello") /* two */)));
}
void caller() {
printf(/* one */ ("hello") /* two */);
printf(((/* one */ ("hello") /* two */)));
}
static void printf(String value) {}
}
| true
|
2edcc22b412c5a218e417640b9c4fce7fa4a0d74
|
Java
|
libinjin/ThreadImp
|
/src/main/java/com/youguu/spring/springIOC/xml/Test001.java
|
UTF-8
| 751
| 2.109375
| 2
|
[] |
no_license
|
package com.youguu.spring.springIOC.xml;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test001 {
public static void main(String[] args) throws DocumentException {
/* SAXReader reader = new SAXReader();
Document document = reader.read("");
document.getRootElement();*/
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring_02.xml");
UserServiceImpl userService = (UserServiceImpl) ctx.getBean("userService");
userService.add();
/* UserServiceImpl userService = new UserServiceImpl();
userService.add();*/
}
}
| true
|
64865c7cec66dd5dfe46142f1aa95b4455e72f55
|
Java
|
Djpet/Poulet4j
|
/src/main/java/fr/poulet4j/Runner.java
|
UTF-8
| 6,170
| 2.328125
| 2
|
[] |
no_license
|
package fr.poulet4j;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fr.poulet4j.core.SocketReader;
import fr.poulet4j.core.SocketWriter;
import fr.poulet4j.core.message.client.Authenticate;
import fr.poulet4j.core.message.client.TurnResult;
import fr.poulet4j.core.message.server.GameServerMessage;
import fr.poulet4j.core.message.server.GetTurnOrder;
import fr.poulet4j.core.message.server.ID;
import fr.poulet4j.model.Cell;
import fr.poulet4j.model.GameMap;
import fr.poulet4j.model.IAInfo;
import fr.poulet4j.order.TurnAction;
import fr.poulet4j.save.ISaveGame;
import fr.poulet4j.save.NoSaveGame;
import fr.poulet4j.save.SaveGame;
/**
* Lanceur de l'IA.
*/
public final class Runner {
private static final Logger LOGGER = LoggerFactory.getLogger(Runner.class);
private IA ia;
protected Socket socket;
protected SocketReader reader;
protected SocketWriter writer;
private long id;
private IAInfo iaInfo;
private ISaveGame saveGame;
public Runner(final IA ia) {
this.ia = ia;
iaInfo = ia.getIAInfo();
saveGame = new NoSaveGame();
}
/**
* Charge l'IA.
* @param ia : votre IA.
* @return le runner
*/
public static Runner ia(final IA ia) {
return new Runner(ia);
}
/**
* Sauvegarde la partie (perte environs : 10 ms sur le premier tour et 1-3 ms ensuite)
* @return le runner
*/
public Runner saveGame() {
saveGame = new SaveGame();
return this;
}
/**
* Sauvegarde la partie
* @param iSaveGame : votre implémentation de la sauvegarde la partie
* @return le runner
*/
public Runner saveGame(final ISaveGame iSaveGame) {
saveGame = iSaveGame;
return this;
}
/**
* Connect l'ia au serveur et attend la prochaine partie.
* @param host : nom ou adresse IP du serveur (port par défault à 8127
*/
public void connectAndRun(final String host) {
connectAndRun(host, 8127);
}
/**
* Connect l'ia au serveur et attend la prochaine partie.
* @param host : nom ou adresse IP du serveur
* @param port : port de connection
*/
public void connectAndRun(final String host, final int port) {
try {
socket = new Socket(host, port);
reader = new SocketReader(socket.getInputStream());
writer = new SocketWriter(socket.getOutputStream());
authenticate();
run();
} catch (UnknownHostException e) {
LOGGER.error("Serveur '" + host + "' incconu : ", e);
} catch (IOException e) {
LOGGER.error("Problème de connexion : ", e);
}
}
private void authenticate() throws IOException {
Authenticate authenticate = new Authenticate();
authenticate.name = iaInfo.name;
authenticate.avatar = iaInfo.avatar;
authenticate.profil = iaInfo.profil.getCode();
authenticate.token = iaInfo.token;
writer.write(authenticate);
GameServerMessage message = reader.read();
if (!(message instanceof ID)) {
throw new RuntimeException("Message de type 'id' attendu, mais reçu type : " + message.getType());
}
id = ((ID) message).getId();
iaInfo.id = id;
ia.afterConnect(iaInfo);
LOGGER.info("Connection OK");
saveGame.init();
}
private void run() throws IOException {
while (true) {
GameServerMessage message = reader.read();
if (message instanceof GetTurnOrder) {
long start = System.currentTimeMillis();
GameMap data = ((GetTurnOrder) message).data;
fillInfo(data);
iaInfo = data.moi;
LOGGER.debug("fillInfo {}", System.currentTimeMillis() - start);
start = System.currentTimeMillis();
List<TurnAction> actions = ia.getOrders(data);
TurnResult turnResult = new TurnResult();
turnResult.ia = iaInfo;
turnResult.actions = actions;
writer.write(turnResult);
saveGame.write(data, turnResult, (int) (System.currentTimeMillis() - start), message.json);
}
}
}
public void stop() throws IOException {
socket.close();
}
private void fillInfo(final GameMap data) {
// ia
if (data.iaList.get(0).id == id) {
data.moi = data.iaList.get(0);
data.ennemi = data.iaList.get(1);
} else {
data.moi = data.iaList.get(1);
data.ennemi = data.iaList.get(0);
}
data.poulet = data.iaList.get(2);
// map
Cell[][] cells = data.cells;
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
Cell cell = cells[i][j];
cell.x = j;
cell.y = i;
if (cell.top != 0) {
cell.topCell = cells[i - 1][j];
}
if (cell.bottom != 0) {
cell.bottomCell = cells[i + 1][j];
}
if (cell.left != 0) {
cell.leftCell = cells[i][j - 1];
}
if (cell.right != 0) {
cell.rightCell = cells[i][j + 1];
}
if (cell.occupant != null) {
if (cell.occupant.id == id) {
cell.moi = true;
data.moi.position = cell;
}
if (cell.occupant.id == data.poulet.id) {
cell.poulet = true;
data.poulet.position = cell;
}
if (cell.occupant.id == data.ennemi.id) {
cell.ennemi = true;
data.ennemi.position = cell;
}
}
}
}
}
}
| true
|
4ccb47a38383703e558c554ee55c1ea1b43e3db1
|
Java
|
swapnilghadge2390/CafeFinderMVPDemo
|
/app/src/main/java/com/suma/coffeeshopmvpassignment/views/MapsView.java
|
UTF-8
| 543
| 1.695313
| 2
|
[] |
no_license
|
package com.suma.coffeeshopmvpassignment.views;
import android.app.Activity;
import android.location.Location;
import com.suma.coffeeshopmvpassignment.models.NearByApiResponse;
import retrofit2.Response;
public interface MapsView {
void generateMap();
void updateLocationOnMap(Location location);
void getCoffeeShopListSuccess(Response<NearByApiResponse> response, Location location);
void onFailure(Throwable error);
Activity getViewActivity();
void onPermissionsGranted();
void onPermissionsDenied();
}
| true
|
45b22d6a20fa4f618217b37c8db4222c0276b6ed
|
Java
|
bellmit/cms-1
|
/JavaSource/com/yuanluesoft/dpc/keyproject/service/KeyProjectService.java
|
UTF-8
| 2,140
| 2.0625
| 2
|
[] |
no_license
|
package com.yuanluesoft.dpc.keyproject.service;
import java.util.List;
import com.yuanluesoft.dpc.keyproject.pojo.KeyProject;
import com.yuanluesoft.dpc.keyproject.pojo.KeyProjectParameter;
import com.yuanluesoft.jeaf.business.service.BusinessService;
import com.yuanluesoft.jeaf.exception.ServiceException;
import com.yuanluesoft.jeaf.sessionmanage.model.SessionInfo;
/**
* 重点项目服务
* @author linchuan
*
*/
public interface KeyProjectService extends BusinessService {
/**
* 更新项目所在地
* @param keyProject
* @param area
* @throws ServiceException
*/
public void updateProjectArea(KeyProject keyProject, String area) throws ServiceException;
/**
* 把项目列入重点项目
* @param keyProject
* @param isKeyProject
* @throws ServiceException
*/
public void setAsKeyProject(KeyProject keyProject, boolean isKeyProject) throws ServiceException;
/**
* 完成项目汇报的审批
* @param keyProject
* @param sessionInfo
* @throws ServiceException
*/
public void completeApprovalDebrief(KeyProject keyProject, SessionInfo sessionInfo) throws ServiceException;
/**
* 项目申报
* @param keyProject
* @param declareYear
* @param sessionInfo
* @throws ServiceException
*/
public void declareProject(KeyProject keyProject, int declareYear, SessionInfo sessionInfo) throws ServiceException;
/**
* 获取重点项目参数配置
* @return
* @throws ServiceException
*/
public KeyProjectParameter getKeyProjectParameter() throws ServiceException;
/**
* 获取行业列表
* @return
* @throws ServiceException
*/
public List listKeyProjectIndustries() throws ServiceException;
/**
* 获取资金来源列表
* @return
* @throws ServiceException
*/
public List listKeyProjectInvestSources() throws ServiceException;
/**
* 获取开发区分类列表
* @return
* @throws ServiceException
*/
public List listDevelopmentAreaCategories() throws ServiceException;
/**
* 汇报是否需要审核
* @return
*/
public boolean isApprovalDebrief();
/**
*
* @return
*/
public String getComponentNames();
}
| true
|
c9f884ac4e4d787f395906aff7ebf56f790ac205
|
Java
|
wjh3323/SCSE
|
/app/src/main/java/com/example/stevenmeow/template/Activity_CheckOnWorkAttrndance.java
|
UTF-8
| 3,060
| 2.25
| 2
|
[] |
no_license
|
package com.example.stevenmeow.template;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.jsoup.select.Elements;
public class Activity_CheckOnWorkAttrndance extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity__check_on_work_attrndance);
//接受数据
Intent intent = getIntent();
String result = intent.getStringExtra("result2");
Elements abc = Jsoup_checkOnWorkAttendance.JAttendance(result);
String[][] abc1 = Jsoup_checkOnWorkAttendance.workAttendance(abc);
for (int i = 0;i<abc1.length;i++){
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.cowall);
android.support.v7.widget.CardView cardView = new android.support.v7.widget.CardView(Activity_CheckOnWorkAttrndance.this);
cardView.setCardBackgroundColor(0xffebf6f7);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(0,15,0,0);
LinearLayout linearLayout1 = new LinearLayout(Activity_CheckOnWorkAttrndance.this);
linearLayout1.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams params3 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams params4 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView tv1 = new TextView(Activity_CheckOnWorkAttrndance.this);
params2.setMargins(0,20,0,10);
tv1.setText(abc1[i][0]);
tv1.setTextSize(15);
tv1.setGravity(Gravity.CENTER);
linearLayout1.addView(tv1,params2);
TextView tv2 = new TextView(Activity_CheckOnWorkAttrndance.this);
tv2.setText(abc1[i][1]);
tv2.setTextSize(18);
tv2.setGravity(Gravity.CENTER);
tv2.getPaint().setFakeBoldText(true);
params3.setMargins(20,0,20,10);
linearLayout1.addView(tv2,params3);
TextView tv3 = new TextView(Activity_CheckOnWorkAttrndance.this);
tv3.setText(abc1[i][2]);
tv3.setTextSize(18);
tv3.setGravity(Gravity.CENTER);
params4.setMargins(0,0,0,30);
linearLayout1.addView(tv3,params4);
cardView.addView(linearLayout1);
linearLayout.addView(cardView,params);
}
}
}
| true
|
05231a7295aabc9e90145ab6abe950ff348e687e
|
Java
|
juzer10/Twitter
|
/app/src/main/java/com/twitter/Authentication.java
|
UTF-8
| 6,540
| 1.953125
| 2
|
[] |
no_license
|
package com.twitter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import com.twitter.utils.Token;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
/**
* Created by juzer_000 on 11/20/2014.
*/
public class Authentication extends Activity {
static String PREFERENCE_NAME = "twitter_oauth";
public static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
public static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLoggedIn";
static String CALLBACK_URL = "oauth://twitter";
Button signInTwitter;
WebView mWebView;
private static Twitter twitter;
private static RequestToken requestToken;
private static AccessToken accessToken;
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
signInTwitter = (Button) findViewById(R.id.button_sign_in);
mWebView = (WebView) findViewById(R.id.twitter_browser);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url != null && url.startsWith(CALLBACK_URL))
new AfterLoginTask().execute(url);
else
webView.loadUrl(url);
return true;
}
});
//mSharedPreferences = getApplicationContext().getSharedPreferences(
//"MyPref", 0)
signInTwitter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new LoginTask().execute();
}
});
}
private void loginToTwitter() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Token.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Token.CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
twitter = factory.getInstance();
try {
requestToken = twitter.getOAuthRequestToken(CALLBACK_URL);
} catch (TwitterException e) {
e.printStackTrace();
}
}
public void handleTwitterCallback(String url) {
Uri uri = Uri.parse(url);
final String verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);
try {
SharedPreferences preferences = this.getSharedPreferences("Twitter", Context.MODE_PRIVATE);
Authentication.this.accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
Log.i("s", accessToken.getToken() + "------" + accessToken.getTokenSecret()+"---"+accessToken.getScreenName());
SharedPreferences.Editor e = preferences.edit();
e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
e.apply();
Log.e("Twitter OAuth Token", "> " + accessToken.getToken());
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(Token.CONSUMER_KEY);
builder.setOAuthConsumerSecret(Token.CONSUMER_SECRET);
String access_token = getPreferences(MODE_PRIVATE).getString(PREF_KEY_OAUTH_TOKEN, "");
String access_token_secret = getPreferences(MODE_PRIVATE).getString(PREF_KEY_OAUTH_SECRET, "");
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
//TESR TWEET twitter4j.Status response = twitter.updateStatus("XXXXXXXXXXXXXXXXX");
} catch (Exception e) {
e.printStackTrace();
}
}
class LoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
loginToTwitter();
return true;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
//super.onPostExecute(aBoolean);
signInTwitter.setVisibility(View.GONE);
mWebView.loadUrl(requestToken.getAuthenticationURL());
mWebView.setVisibility(View.VISIBLE);
mWebView.requestFocus(View.FOCUS_DOWN);
}
}
class AfterLoginTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
//super.onPreExecute();
mWebView.clearHistory();
}
@Override
protected Boolean doInBackground(String... params) {
handleTwitterCallback(params[0]);
return true;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
//super.onPostExecute(aBoolean);
SharedPreferences pref = getSharedPreferences("Twitter", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("FirstTime", true);
editor.apply();
mWebView.setVisibility(View.GONE);
Intent i = new Intent(Authentication.this, TweetList.class);
startActivity(i);
signInTwitter.setVisibility(View.VISIBLE);
}
}
@Override
public void onBackPressed() {
if (mWebView.getVisibility() == View.VISIBLE) {
if (mWebView.canGoBack()) {
mWebView.goBack();
return;
} else {
mWebView.setVisibility(View.GONE);
return;
}
}
super.onBackPressed();
}
}
| true
|
39ffc156484f273b48bad3fd81b6f390895fcbc4
|
Java
|
juanpquiroga/lombok-demo
|
/src/main/java/co/com/rockthorum/lombokdemo/dto/PropietarioDataEquivalentDTO.java
|
UTF-8
| 574
| 2.109375
| 2
|
[] |
no_license
|
package co.com.rockthorum.lombokdemo.dto;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* Genera getter and setters automatico, igual que el constructor de parametros requeridos, hashcode, equals y toString
* @author juanp
*
*/
@Getter
@Setter
@EqualsAndHashCode
@ToString
@RequiredArgsConstructor
public class PropietarioDataEquivalentDTO {
private int id;
private String nombre;
private String apellido;
private String nombreCompleto;
private boolean activo;
}
| true
|
976e7f899caa13116c6a7c9bee41a61056d85d82
|
Java
|
badisreguigui/AdoPet
|
/src/controllers/DetController.java
|
UTF-8
| 3,514
| 2.375
| 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 Controllers;
import Entities.DemandeSitting;
import Entities.OffreSitting;
import com.jfoenix.controls.JFXButton;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
/**
* FXML Controller class
*
* @author emna
*/
public class DetController implements Initializable {
@FXML
private Label titre;
@FXML
private Label lieu;
@FXML
private Label dd;
@FXML
private Label hd;
@FXML
private Label df;
@FXML
private Label hf;
@FXML
private TextArea desc;
@FXML
private Label visite;
@FXML
private Label prom;
@FXML
private Label nourri;
@FXML
private Label chat;
@FXML
private Label chien;
@FXML
private Label autre;
@FXML
private JFXButton service;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
public void setting(OffreSitting d){
titre.setText(d.getTitre());
desc.setText(d.getDescription());
desc.setEditable(false);
lieu.setText("A "+d.getLieu());
dd.setText("A partir De: "+String.valueOf(d.getDate_debut_dispo()));
df.setText("Jusq'au: "+String.valueOf(d.getDate_fin_dispo()));
hd.setText(" à "+String.valueOf(d.getTmp_debut()));
hf.setText(" à "+String.valueOf(d.getTmp_fin()));
if (d.isNourriture() == true){
nourri.setText("Je peux nourrir votre animal lors de sa garde");
}else{
nourri.setText("Apportez votre propre nourriture");
}
if (d.isVisite()== true){
visite.setText("Vous pouvez visiter votre animal");
}else{
visite.setText("La visite est interdit lors de la garde");
}
if (d.isPromenade()== true){
prom.setText("Je peux promener votre animal lors de sa garde");
}else{
prom.setText("Je n'offre pas de promenades");
}
if(d.isChat() == true)
chat.setText("Chat permis");
else
chat.setText("Chat non permis");
if(d.isChien() == true)
chien.setText("Chien permis");
else
chien.setText("Chien non permis");
if(d.isAutre())
autre.setText("D'autre type d'animaux sont permis");
else
autre.setText("D'autre type d'animaux ne sont permis");
}
@FXML
private void reserver(ActionEvent event) throws IOException {
Stage foroffre = new Stage();
Parent root= FXMLLoader.load(getClass().getResource("/fxml/ReservationDemande.fxml"));
Scene scene = new Scene(root);
scene.setFill(javafx.scene.paint.Color.TRANSPARENT);
foroffre.centerOnScreen();
foroffre.setScene(scene);
foroffre.setResizable(false);
foroffre.show();
}
}
| true
|
c4785261b166b3e29507e3b0710c6e4a4f017d12
|
Java
|
Nononoa-Zoro/notes
|
/JavaTest/src/main/java/com/study/leecode/两数之和.java
|
UTF-8
| 1,252
| 3.65625
| 4
|
[] |
no_license
|
package com.study.leecode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class 两数之和 {
static List<List<Integer>> res = new ArrayList<>();
//方法一 左右指针
public static List<List<Integer>> solve(int[] arr, int target) {
Arrays.sort(arr);
int i = 0, j = arr.length - 1;
while (i < j) {
int sum = arr[i] + arr[j];
if (sum < target) {
i++;
} else if (sum > target) {
j--;
} else {
res.add(Arrays.asList(arr[i],arr[j]));
//跳过重复元素
while (arr[i]==arr[i+1]){
i++;
}
while (arr[j-1]==arr[j]){
j--;
}
i++;
j--;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {1,2,2,3,5,6,7};
List<List<Integer>> lists = solve(arr, 8);
for(List<Integer> list:lists){
for(Integer i:list){
System.out.print(i+" ");
}
System.out.println();
}
}
}
| true
|