text
stringlengths 10
2.72M
|
|---|
package com.googlecode.easyec.sika.validations;
/**
* 数字类型列数据验证器类。
* <p>
* 该类用于验证列值为空或属于{@link Number}类型对象实例的时候,返回true。
* </p>
*
* @author JunJie
*/
public class NumberColumnValidator implements ColumnValidator {
public boolean accept(Object val) {
return val == null || val instanceof Number;
}
public String getAlias() {
return "NOT_NUMBER";
}
}
|
package gov.nih.mipav.model.dicomcomm;
/**
* Simple utilities to convert transfer syntaxes to a different form.
*
* <hr>
*
* This DICOM communication package was originally based on the Java Dicom Package, whose license is below:
*
* <pre>
* Java Dicom Package (com.zmed.dicom)
*
* Copyright (c) 1996-1997 Z Medical Imaging Systems, Inc.
*
* This software is provided, as is, for non-commercial educational
* purposes only. Use or incorporation of this software or derivative
* works in commercial applications requires written consent from
* Z Medical Imaging Systems, Inc.
*
* Z MEDICAL IMAGING SYSTEMS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT
* THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR CONFORMANCE TO ANY
* SPECIFICATION OR STANDARD. Z MEDICAL IMAGING SYSTEMS SHALL NOT BE
* LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING OR
* MODIFYING THIS SOFTWARE OR ITS DERIVATIVES.
*
* =============================================================================
*
* This software package is implemented similarly to the UC Davis public
* domain C++ DICOM implementation which contains the following copyright
* notice:
*
* Copyright (C) 1995, University of California, Davis
*
* THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY
* OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS
* PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
* USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY
* SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF
* THE SOFTWARE IS WITH THE USER.
*
* Copyright of the software and supporting documentation is
* owned by the University of California, and free access
* is hereby granted as a license to use this software, copy this
* software and prepare derivative works based upon this software.
* However, any distribution of this software source code or
* supporting documentation or derivative works (source code and
* supporting documentation) must include this copyright notice.
*
* The UC Davis C++ source code is publicly available from the following
* anonymous ftp site:
*
* ftp://imrad.ucdmc.ucdavis.edu/pub/dicom/UCDMC/
* </pre>
*
* @author Matthew J. McAuliffe, Ph.D.
*/
public class DICOM_TransferSyntaxUtil {
// ~ Static fields/initializers
// -------------------------------------------------------------------------------------
/** Static that defines IMPLICIT_LITTLE_ENDIAN. */
public static final int IMPLICIT_LITTLE_ENDIAN = 100;
/** Static that defines EXPLICIT_LITTLE_ENDIAN. */
public static final int EXPLICIT_LITTLE_ENDIAN = 101;
/** Static that defines EXPLICIT_BIG_ENDIAN. */
public static final int EXPLICIT_BIG_ENDIAN = 102;
/** Static that defines UNKNOWN. */
public static final int UNKNOWN = 0;
// ~ Methods
// --------------------------------------------------------------------------------------------------------
/**
* Converts a transfer syntax UID to one of the three transfer syntaxes.
*
* @param transferSyntaxUID UID to be converted
*
* @return the converted UID ID.
*/
public static int convertToAlias(final String transferSyntaxUID) {
if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferLITTLEENDIAN)) {
return (DICOM_TransferSyntaxUtil.IMPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferLITTLEENDIANEXPLICIT)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferBIGENDIANEXPLICIT)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_BIG_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGBASELINEPROCESS1)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC2AND4)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC3AND5)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC6AND8)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC7AND9)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC10AND12)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC11AND13)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC14)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC15)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC16AND18)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC17AND19)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC20AND22)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC21AND23)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC24AND26)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC25AND27)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC28)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC29)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROCFIRSTORDERREDICT)) {
return (DICOM_TransferSyntaxUtil.EXPLICIT_LITTLE_ENDIAN);
}
return (DICOM_TransferSyntaxUtil.UNKNOWN);
}
/**
* Converts a transfer syntax UID (i.e. "1.2.840.10008.1.2.4.50") to a more understandable string form ( i.e.
* TransferJPEGBASELINEPROCESS1 )
*
* @param transferSyntaxUID UID to be converted
*
* @return the convert UID string.
*/
public static String convertToReadableString(final String transferSyntaxUID) {
if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferLITTLEENDIAN)) {
return (new String("IMPLICIT_LITTLE_ENDIAN"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferLITTLEENDIANEXPLICIT)) {
return (new String("EXPLICIT_LITTLE_ENDIAN"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferBIGENDIANEXPLICIT)) {
return (new String("EXPLICIT_BIG_ENDIAN"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGBASELINEPROCESS1)) {
return (new String("JPEGBASELINEPROCESS1"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC2AND4)) {
return (new String("JPEGEXTENDEDPROC2AND4"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC3AND5)) {
return (new String("JPEGEXTENDEDPROC3AND5"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC6AND8)) {
return (new String("JPEGSPECTRALPROC6AND8"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC7AND9)) {
return (new String("JPEGSPECTRALPROC7AND9"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC10AND12)) {
return (new String("JPEGFULLPROGRESSPROC10AND12"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC11AND13)) {
return (new String("JPEGFULLPROGRESSPROC11AND13"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC14)) {
return (new String("JPEGLOSSLESSPROC14"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC15)) {
return (new String("JPEGLOSSLESSPROC15"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC16AND18)) {
return (new String("JPEGEXTENDEDPROC16AND18"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGEXTENDEDPROC17AND19)) {
return (new String("JPEGEXTENDEDPROC17AND19"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC20AND22)) {
return (new String("JPEGSPECTRALPROC20AND22"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGSPECTRALPROC21AND23)) {
return (new String("JPEGSPECTRALPROC21AND23"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC24AND26)) {
return (new String("JPEGFULLPROGRESSPROC24AND26"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGFULLPROGRESSPROC25AND27)) {
return (new String("JPEGFULLPROGRESSPROC25AND27"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC28)) {
return (new String("JPEGLOSSLESSPROC28"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROC29)) {
return (new String("JPEGLOSSLESSPROC29"));
} else if (transferSyntaxUID.equals(DICOM_Constants.UID_TransferJPEGLOSSLESSPROCFIRSTORDERREDICT)) {
return (new String("JPEGLOSSLESSPROCFIRSTORDERREDICT"));
}
return (new String("Unknown")); // unknown transfer syntax
}
}
|
package org.crce.interns.service.impl;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.crce.interns.dao.ResumeUploadDao;
import org.crce.interns.exception.IncorrectFileFormatException;
import org.crce.interns.exception.MaxFileSizeExceededError;
import org.crce.interns.service.ResumeUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Service("resumeUploadService")
public class ResumeUploadServiceImpl implements ResumeUploadService {
@Autowired
private ResumeUploadDao resumeUploadDao;
private String saveDirectory = "C:/Users/Crystal/workspace1/PMS_v2_Working-master/PMS_v2-master(edited)/src/resources/Resume/";
public void handleFileUpload(HttpServletRequest request, @RequestParam CommonsMultipartFile fileUpload, String username)
throws Exception {
final String fullPath = saveDirectory + fileUpload.getOriginalFilename();
if (!fileUpload.isEmpty()) {
IncorrectFileFormatException e = new IncorrectFileFormatException();
MaxFileSizeExceededError m = new MaxFileSizeExceededError();
//File file = new File(fileUpload.getOriginalFilename());
final String extension = FilenameUtils.getExtension(fullPath);
if(!(extension.equals("pdf") || extension.equals("docx") || extension.equals("odt")))
throw e;
//final long size = FileUtils.sizeOf(file);
final long size = fileUpload.getSize();
System.out.println(size);
if(size > 512520)
throw m;
System.out.println("Saving file: " + fileUpload.getOriginalFilename());
System.out.println(extension);
if (!fileUpload.getOriginalFilename().equals(""))
fileUpload.transferTo(new File(fullPath));
}
resumeUploadDao.addNewResume(username,fullPath);
}
}
|
package cn.bdqn.stumanage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.bdqn.stumanage.mapper")//必须加上-用来扫描mapper接口
public class MgrExamServiceApplication {
public static void main(String[] args) {
SpringApplication.run(MgrExamServiceApplication.class, args);
}
}
|
package com.java8.comparator;
import com.java8.businessdataobjects.Student;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorBeforeAndWithJava8 {
public static void main(String args[]) {
Student s1 = new Student(10,"John D", 20);
Student s2 = new Student(8,"Ron C", 19);
Student s3 = new Student(11,"Tom P", 23);
Student s4 = new Student(15,"Gimmy D", 25);
Student s5 = new Student(9,"Ronny D", 21);
Student s6 = new Student(13,"Rock R", 20);
List<Student> studentList= new ArrayList<>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
studentList.add(s6);
System.out.println("************ Sorting by name using traditional java without anonymous and java 8 ************ \n");
System.out.println("Before sorting by name :");
studentList.forEach(student -> System.out.print(student.getName()+ " "));
System.out.println("\n \n After sorting by name :");
Collections.sort(studentList, new StudentNameComparator());
studentList.forEach(student -> System.out.print(student.getName()+ " "));
System.out.println("\n************ Sorting age with anonymouys inner class ************ \n");
System.out.println("Before sorting by age :");
studentList.forEach(student -> System.out.print(student.getAge()+ " "));
System.out.println("\nAfter sorting by age :");
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student student1, Student student2) {
return student1.getAge().compareTo(student2.getAge());
}
});
studentList.forEach(student -> System.out.print(student.getAge()+ " "));
System.out.println("\n************ Sorting roll number with java 8 comparator ************ \n");
System.out.println("Before sorting roll no with java 8 lambda \n");
studentList.forEach(student -> System.out.print(student.getRollno()+ " "));
// with java 8 lambda
Comparator<Student> compareByRollNumber = (Student stu1, Student stu2) -> stu1.getRollno().compareTo(stu2.getRollno());
Collections.sort(studentList, compareByRollNumber);
// Collections.sort(studentList, (Student stu1, Student stu2) -> stu1.getRollno().compareTo(stu2.getRollno())); can be done with this as well.
// with java 8 comparing method using method reference
//studentList.sort(Comparator.comparing(Student::getRollno));
System.out.println("\nAfter sorting roll no with java 8 lambda");
studentList.forEach(student -> System.out.print(student.getRollno()+ " "));
}
}
|
package com.example.miniproject;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class CustomerProfileView extends AppCompatActivity {
private static final String TAG = "CustomerProfileView";
TextView tvCustUsername, tvCustEmail, tvCustPhone, tvCustIC;
String id;
Button btnEditCustProfile, logout;
protected void onCreate(Bundle savedInstanceState) {
// Write a message to the database
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
setTitle("Customer Profile");
logout = findViewById(R.id.logout);
//Initialize and assign bottom navigation
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//Set Profile selected bottom Navigation
bottomNavigationView.setSelectedItemId(R.id.navprofile);
//Perform ItemSelectedListener bottom Navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.navprofile:
startActivity(new Intent(getApplicationContext()
,CustomerProfileView.class));
overridePendingTransition(0, 0);
return true;
case R.id.navreceiverlist:
startActivity(new Intent(getApplicationContext()
,ReceiverList.class));
overridePendingTransition(0, 0);
return true;
case R.id.navdonationlist:
startActivity(new Intent(getApplicationContext()
,DonationHistoryList.class));
overridePendingTransition(0, 0);
return true;
}
return false;
}
});
//end bottom navigation
tvCustUsername = findViewById(R.id.tvCustUsername);
tvCustEmail = findViewById(R.id.tvCustEmail);
tvCustPhone = findViewById(R.id.tvCustPhone);
tvCustIC = findViewById(R.id.tvCustIC);
btnEditCustProfile = findViewById(R.id.btnEditCustProfile);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
if (currentFirebaseUser != null) {
id = currentFirebaseUser.getUid();
boolean emailVerified = currentFirebaseUser.isEmailVerified();
// Toast.makeText(this, "User ID:" + id + "\nEmail Verified: " + emailVerified, Toast.LENGTH_SHORT).show();
if(emailVerified != true)
{
Toast.makeText(this, "Email not verified, Please check your inbox", Toast.LENGTH_SHORT).show();
Intent intent2login = new Intent(CustomerProfileView.this, MainActivity.class);
startActivity(intent2login);
}
} else {
// No user is signed in
Toast.makeText(this, "User Not Signed In:", Toast.LENGTH_SHORT).show();
Intent intent2login = new Intent(CustomerProfileView.this, MainActivity.class);
startActivity(intent2login);
}
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("Users").child(id);
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue().toString();
String ic = dataSnapshot.child("ic").getValue().toString();
String phone = dataSnapshot.child("phone").getValue().toString();
String fullName = dataSnapshot.child("fullName").getValue().toString();
tvCustUsername.setText(fullName);
tvCustEmail.setText(email);
tvCustPhone.setText(phone);
tvCustIC.setText(ic);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
Toast.makeText(CustomerProfileView.this, "Database Error Fail to read value", Toast.LENGTH_SHORT).show();
}
});
btnEditCustProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2edit = new Intent(CustomerProfileView.this, CustomerProfileEdit.class);
intent2edit.putExtra("id", (String.valueOf(id)));
startActivity(intent2edit);
}
});
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(CustomerProfileView.this, MainActivity.class));
}
});
}
}
|
package com.r.base.languageBase;
import java.util.Arrays;
import com.r.util.CountingGenerator;
import com.r.util.Generated;
public class TestGenerated {
public static void main(String[] args){
Integer[] a = {9,8,7,6};
System.out.println(Arrays.toString(a));
a = Generated.array(a, new CountingGenerator.Integer());
System.out.println(Arrays.toString(a));
Integer[] b = Generated.array(Integer.class,new CountingGenerator.Integer(), 15);
System.out.println(Arrays.toString(b));
}
}
|
package br.com.LoginSpringBootThymeleaf.dto.Permissoes;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class PermissaoDTO {
private Integer id;
private String permissao;
private String descricao;
private Boolean checked;
public PermissaoDTO(Integer integer, String permissao, String descricao) {
this.id = integer;
this.permissao = permissao;
this.descricao = descricao;
}
}
|
package update;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class HisDataProssorHandler {
public static void closeHisDataProssor(){
Process process = null;
String cmdStr = "taskkill /f /im java(hzcy).exe";
try {
process = Runtime.getRuntime().exec(cmdStr);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void openHisDataProssor(){
String startCmd = null;
String root = null;
try {
File file = new File(Const.startConfig);
root = file.getParentFile().getAbsolutePath();
DataInputStream dIn = new DataInputStream(new FileInputStream(file));
startCmd = dIn.readLine();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Process process = null;
String cmdStr[] = startCmd.split(";");
try {
for(String cmd:cmdStr){
System.out.println("启动程序"+cmd);
//进入root目录
int last = cmd.lastIndexOf("/");
String runStr = "start /min "+root+cmd.substring(0,last);
File workFile = new File(root+"/"+cmd.substring(0,last));
String[] cmds = new String[5];
cmds[0] = "cmd.exe";
cmds[1] = "/c";
cmds[2] = "start";
cmds[3] = "/min";
cmds[4] = cmd.substring(last+1);
process = Runtime.getRuntime().exec(cmds,null,workFile);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
closeHisDataProssor();
}
}
|
package com.ebook.admin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EBookAdminApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(EBookAdminApplication.class);
public static void main(String[] args) {
LOGGER.debug("Main Method Start");
SpringApplication.run(EBookAdminApplication.class, args);
LOGGER.debug("Main Method End");
}
}
|
package com.coder.model;
// Generated Jan 23, 2020 8:11:18 PM by Hibernate Tools 5.0.6.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* OptionJoinItemId generated by hbm2java
*/
@Embeddable
public class OptionJoinItemId implements java.io.Serializable {
private int itemJoinStoreId;
private int itemOptionId;
public OptionJoinItemId() {
}
public OptionJoinItemId(int itemJoinStoreId, int itemOptionId) {
this.itemJoinStoreId = itemJoinStoreId;
this.itemOptionId = itemOptionId;
}
@Column(name = "item_join_store_id", nullable = false)
public int getItemJoinStoreId() {
return this.itemJoinStoreId;
}
public void setItemJoinStoreId(int itemJoinStoreId) {
this.itemJoinStoreId = itemJoinStoreId;
}
@Column(name = "item_option_id", nullable = false)
public int getItemOptionId() {
return this.itemOptionId;
}
public void setItemOptionId(int itemOptionId) {
this.itemOptionId = itemOptionId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof OptionJoinItemId))
return false;
OptionJoinItemId castOther = (OptionJoinItemId) other;
return (this.getItemJoinStoreId() == castOther.getItemJoinStoreId())
&& (this.getItemOptionId() == castOther.getItemOptionId());
}
public int hashCode() {
int result = 17;
result = 37 * result + this.getItemJoinStoreId();
result = 37 * result + this.getItemOptionId();
return result;
}
}
|
package com.shichuang.mobileworkingticket.activity;
import android.app.DatePickerDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.shichuang.mobileworkingticket.R;
import com.shichuang.mobileworkingticket.adapter.WorkingTicketListAdapter;
import com.shichuang.mobileworkingticket.common.Constants;
import com.shichuang.mobileworkingticket.common.NewsCallback;
import com.shichuang.mobileworkingticket.common.TokenCache;
import com.shichuang.mobileworkingticket.entify.AMBaseDto;
import com.shichuang.mobileworkingticket.entify.HistoryWorkInfo;
import com.shichuang.mobileworkingticket.entify.WorkingTicketList;
import com.shichuang.mobileworkingticket.widget.RxTitleBar;
import com.shichuang.open.base.BaseActivity;
import com.shichuang.open.tool.RxActivityTool;
import com.shichuang.open.widget.RxEmptyLayout;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 历史工票
* Created by Administrator on 2018/2/28.
*/
public class HistoryWorkOrderActivity extends BaseActivity {
//private View headerView;
private TextView mTvTotalWorkOrderCount;
private TextView mTvCompleteCount;
private TextView mTvTotalWorkingHours;
private TextView mTvTimeInterval;
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
private WorkingTicketListAdapter mAdapter;
private RxEmptyLayout mEmptyLayout;
private int pageSize = 10;
private int pageIndex = 1;
private String startTime = "", endTime = "";
private Calendar currentCal;
@Override
public int getLayoutId() {
return R.layout.activity_history_work_order;
}
@Override
public void initView(Bundle savedInstanceState, View view) {
mTvTimeInterval = view.findViewById(R.id.tv_time_interval);
mTvTotalWorkOrderCount = view.findViewById(R.id.tv_total_work_order_count);
mTvCompleteCount = view.findViewById(R.id.tv_complete_count);
mTvTotalWorkingHours = view.findViewById(R.id.tv_total_working_hours);
mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
mRecyclerView = view.findViewById(R.id.recycler_view);
//headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_history_work_order_header, (ViewGroup) mRecyclerView.getParent(), false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
mAdapter = new WorkingTicketListAdapter();
//mAdapter.addHeaderView(headerView);
mAdapter.setPreLoadNumber(2);
mRecyclerView.setAdapter(mAdapter);
mEmptyLayout = view.findViewById(R.id.empty_layout);
mEmptyLayout.setOnEmptyLayoutClickListener(new RxEmptyLayout.OnEmptyLayoutClickListener() {
@Override
public void onEmptyLayoutClick(int status) {
if (status != RxEmptyLayout.NETWORK_LOADING) {
refresh();
}
}
});
initTimeInterval();
}
/**
* 初始化时间区间
*/
private void initTimeInterval() {
// 当前时间
currentCal = Calendar.getInstance();
endTime = formatDate(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
// 前一个月时间
Calendar oneMonthBefore = Calendar.getInstance();
oneMonthBefore.setTime(new Date());
oneMonthBefore.add(Calendar.MONTH, -1);
startTime = formatDate(oneMonthBefore.get(Calendar.YEAR), oneMonthBefore.get(Calendar.MONTH), oneMonthBefore.get(Calendar.DAY_OF_MONTH));
mTvTimeInterval.setText(startTime + "~" + endTime);
}
@Override
public void initEvent() {
((RxTitleBar) findViewById(R.id.title_bar)).setTitleBarClickListener(new RxTitleBar.TitleBarClickListener() {
@Override
public void onRightClick() {
RxActivityTool.skipActivity(mContext, WorkingTicketSearchActivity.class);
}
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(false);
}
});
mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
Bundle bundle = new Bundle();
bundle.putInt("ticketId", mAdapter.getData().get(position).getId());
RxActivityTool.skipActivity(mContext, WorkingTicketDetailsActivity.class, bundle);
}
});
mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
@Override
public void onLoadMoreRequested() {
loadMore();
}
}, mRecyclerView);
findViewById(R.id.ll_select_time).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectStartTime();
}
});
}
@Override
public void initData() {
getHistoricalWorkInfoData();
refresh();
}
private void getHistoricalWorkInfoData() {
OkGo.<AMBaseDto<HistoryWorkInfo>>get(Constants.historicalWorkInfoUrl)
.tag(mContext)
.params("token", TokenCache.getToken(mContext))
.params("ticket_state", 2) // 工票状态 0=待分配成员,1=生产作业,2=已完成
.params("start_time", startTime)
.params("end_time", endTime)
.execute(new NewsCallback<AMBaseDto<HistoryWorkInfo>>() {
@Override
public void onStart(Request<AMBaseDto<HistoryWorkInfo>, ? extends Request> request) {
super.onStart(request);
}
@Override
public void onSuccess(final Response<AMBaseDto<HistoryWorkInfo>> response) {
if (response.body().code == 0 && response.body().data != null && response.body().data.getRow() != null) {
HistoryWorkInfo.HistoryWorkInfoModel historyWorkInfo = response.body().data.getRow();
mTvTotalWorkOrderCount.setText(historyWorkInfo.getSumCount());
mTvCompleteCount.setText(historyWorkInfo.getSumCompleteCount());
mTvTotalWorkingHours.setText(historyWorkInfo.getSumWorkingHours());
}
}
@Override
public void onError(Response<AMBaseDto<HistoryWorkInfo>> response) {
super.onError(response);
}
@Override
public void onFinish() {
super.onFinish();
}
});
}
private void refresh() {
pageIndex = 1;
mSwipeRefreshLayout.setRefreshing(true);
getWorkingTicketListData();
}
private void loadMore() {
getWorkingTicketListData();
}
private void getWorkingTicketListData() {
OkGo.<AMBaseDto<WorkingTicketList>>get(Constants.ticketListUrl)
.tag(mContext)
.params("token", TokenCache.getToken(mContext))
.params("pageSize", pageSize)
.params("pageIndex", pageIndex)
.params("start_time", startTime)
.params("end_time", endTime)
.params("type", 5)
.execute(new NewsCallback<AMBaseDto<WorkingTicketList>>() {
@Override
public void onStart(Request<AMBaseDto<WorkingTicketList>, ? extends Request> request) {
super.onStart(request);
}
@Override
public void onSuccess(final Response<AMBaseDto<WorkingTicketList>> response) {
if (response.body().code == 0) {
WorkingTicketList table = response.body().data;
setData(table.getRows());
// 判断是否有更多数据
if (table.getRecordCount() > 0) {
mEmptyLayout.hide();
if (mAdapter.getData().size() < table.getRecordCount()) {
pageIndex++;
mAdapter.loadMoreComplete();
mAdapter.setEnableLoadMore(true);
} else {
if (table.getRecordCount() < pageSize) {
mAdapter.loadMoreEnd(true);
//showToast("没有更多数据");
} else {
mAdapter.loadMoreEnd(false);
//mAdapter.setEnableLoadMore(false);
}
}
} else {
mEmptyLayout.show(RxEmptyLayout.EMPTY_DATA);
}
} else {
showToast(response.body().msg);
}
}
@Override
public void onError(Response<AMBaseDto<WorkingTicketList>> response) {
super.onError(response);
mEmptyLayout.show(RxEmptyLayout.NETWORK_ERROR);
}
@Override
public void onFinish() {
super.onFinish();
mSwipeRefreshLayout.setRefreshing(false);
}
});
}
private void setData(List<WorkingTicketList.WorkingTicketListModel> data) {
if (mSwipeRefreshLayout.isRefreshing()) {
mAdapter.setNewData(data);
} else {
mAdapter.addData(data);
}
}
private void selectStartTime() {
DatePickerDialog mDialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startTime = formatDate(year, month, dayOfMonth);
mTvTimeInterval.setText(startTime + "~" + endTime);
selectEndTime();
}
}, currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
mDialog.setTitle("选择开始时间");
if (Build.VERSION.SDK_INT >= 11) {
mDialog.getDatePicker().setMaxDate(currentCal.getTimeInMillis());
}
mDialog.show();
}
private void selectEndTime() {
DatePickerDialog mDialog = new DatePickerDialog(mContext, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
endTime = formatDate(year, month, dayOfMonth);
mTvTimeInterval.setText(startTime + "~" + endTime);
getHistoricalWorkInfoData();
refresh();
}
}, currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
//mDialog.setTitle("选择结束时间");
if (Build.VERSION.SDK_INT >= 11) {
mDialog.getDatePicker().setMaxDate(currentCal.getTimeInMillis());
}
mDialog.show();
}
private String formatDate(int year, int month, int day) {
String yearStr = year + "";
String monthStr = "";
if ((month + 1) < 10) {
monthStr = "0" + (month + 1);
} else {
monthStr = (month + 1) + "";
}
String dayStr = "";
if (day < 10) {
dayStr = "0" + day;
} else {
dayStr = day + "";
}
return yearStr + "-" + monthStr + "-" + dayStr;
}
}
|
package com.cs.casino.payment;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Omid Alaepour
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class Greeting {
@XmlElement
@Nonnull
private String content;
public Greeting() {
}
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
|
class FC {
public String name;
protected void setName (String name) {
this.name = name;
}
protected String getName () {
return name;
}
public String color;
protected void setColor (String color) {
this.color = color;
}
protected String getColor () {
return color;
}
public String captain;
protected void setCaptain (String captain) {
this.captain = captain;
}
protected String getCaptain () {
return captain;
}
public String director;
protected void setDirector (String director) {
this.director = director;
}
protected String getDirector () {
return director;
}
public String budget;
protected void setBudget (String budget) {
this.budget = budget;
}
protected String getBudget () {
return budget;
}
public String coach;
protected void setCoach (String coach) {
this.coach = coach;
}
protected String getCoach () {
return coach;
}
public String owner;
protected void setOwner (String owner) {
this.owner = owner;
}
protected String getOwner () {
return owner;
}
public int year;
protected void setYear (int year) {
this.year = year;
}
protected int getYear () {
return year;
}
}
class FC1 extends FC {
public static void main (String[] args) {
FC1 chelsea = new FC1();
chelsea.setName ("Chelsea FC");
chelsea.setColor ("blue");
chelsea.setCaptain ("John Terry");
chelsea.setDirector ("Bruce Buck");
chelsea.setBudget ("100 000 000 $");
chelsea.setCoach ("Jose Mourinho");
chelsea.setOwner ("Roman Abramovich");
chelsea.setYear (1905);
System.out.println ("My Club:\nName: " + chelsea.getName() + "\nColor: " + chelsea.getColor() + "\nCaptain: " + chelsea.getCaptain() + "\nDirector: " + chelsea.getDirector() + "\nBudget: " + chelsea.getBudget() + "\nCoach: " + chelsea.getCoach() + "\nOwner: " + chelsea.getOwner() + "\nYear: " + chelsea.getYear());
}
}
class FC2 extends FC {
public static void main (String args[]){
FC1 RM = new FC1();
RM.setName("Real Madrid FC");
RM.setColor("Creamy");
RM.setCaptain("Iker Casillas");
RM.setDirector("Florentino Perez");
RM.setBudget("150 000 000 $");
RM.setCoach("Carlo Ancelotti");
RM.setOwner("Socios");
RM.setYear(1902);
System.out.println ("My Club:\nName: " + RM.getName() + "\nColor: " + RM.getColor() + "\nCaptain: " + RM.getCaptain() + "\nDirector: " + RM.getDirector() + "\nBudget: " + RM.getBudget() + "\nCoach: " + RM.getCoach() + "\nOwner: " + RM.getOwner() + "\nYear: " + RM.getYear());
}
}
|
package io.github.utk003.chat_search.hangouts;
public class HangoutsTakeout {
}
|
package it.mindware.manageit;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import com.google.gson.Gson;
/**
* Schermata di login.
*
* @author Alessandro Fort, Filippo Gastaldello
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Converte il contenut delle EditText in JSON e lo manda all'API
* @param view onClick signature requirement
*/
public void composeJson(View view){
Gson gson = new Gson();
Login login = new Login();
String user = ((EditText) findViewById(R.id.et_user)).getText().toString();
String pass = ((EditText) findViewById(R.id.et_pass)).getText().toString();
login.setUsername(user);
login.setPassword(pass);
String json = gson.toJson(login);
HttpHandler httpHandler = new HttpHandler();
HttpHandler.setActivity(this);
httpHandler.connect("login.php",json);
}
}
|
package com.ljl.service;
import com.ljl.vo.UserInfo;
import java.util.List;
public interface UserService {
//登录
public UserInfo login(UserInfo userInfo);
//查询所有
public List<UserInfo> selUser(UserInfo userInfo);
//添加
public int addUser(UserInfo userInfo);
//修改
public int updUser(UserInfo userInfo);
//删除
public int delUser(int id);
}
|
package com.example.cropad;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Locale;
public class MarketAdapter extends RecyclerView.Adapter<MarketAdapter.ViewHolder> {
private Context context;
private ArrayList<marketdata> dataList;
public MarketAdapter(Context context, ArrayList<marketdata> dataList){
this.context=context;
this.dataList= dataList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.market_item,parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ImageView markImg=holder.markImg;
TextView markName=holder.markName;
TextView cropPrice=holder.cropPrice;
final double lat = dataList.get(position).getLat();
final double lon = dataList.get(position).getLon();
// Log.d("Lat",lat);
// Log.d("lon",lon);
// cropPrice.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// Toast.makeText(context, "hello ", Toast.LENGTH_LONG).show();
//
// }
// });
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=loc:%f,%f", lat,lon);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent=new Intent(context,MainActivity.class);
context.startActivity(intent);
}
});
markName.setText(dataList.get(position).getMarketName());
cropPrice.setText(dataList.get(position).getPrice());
}
@Override
public int getItemCount() {
return dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView markImg;
TextView markName,cropPrice;
LinearLayout linearLayout;
public ViewHolder(@NonNull View itemView) {
super(itemView);
markImg=itemView.findViewById(R.id.marketImage);
markName=itemView.findViewById(R.id.marketName);
cropPrice=itemView.findViewById(R.id.marketPrice);
linearLayout = itemView.findViewById(R.id.market_item);
}
}
}
|
package Fichier_circuit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FichierCircuit
{
private String nom;
private String url;
private String contenu;
public FichierCircuit(String nom, String url_fichier_circuit, String contenu)
{
this.setNom(nom);
this.setUrl(url_fichier_circuit);
this.setContenu(contenu);
}
public String chargerContenu()
{
String contenu = new String("");
try
{
File fichier_circuit = new File(this.getUrl());
FileReader lecteur = new FileReader(fichier_circuit);
BufferedReader buffer = new BufferedReader(lecteur);
try
{
String ligne = buffer.readLine();
contenu += ligne + "\n";
while(ligne != null)
{
ligne = buffer.readLine();
contenu += ligne + "\n";
}
buffer.close();
lecteur.close();
System.out.println("[SUCCES] Le contenu du fichier a bien été chargé ! \n");
}
catch(IOException e)
{
System.out.print("[ERREUR] Le fichier n'a pas pu être ouvert... (" + e + ")");
}
}
catch(FileNotFoundException e)
{
System.out.println("[ERREUR] Le fichier n'a pas été trouvé ! (" + e + ")");
}
return contenu;
}
public void lire()
{
this.setContenu(this.chargerContenu());
}
public void sauvegarder(String url_fichier_circuit, String nom_fichier_circuit)
{
try
{
File fichier_circuit = new File(this.getUrl());
FileWriter ecriveur = new FileWriter(url_fichier_circuit + "/" + nom_fichier_circuit + ".txt");
BufferedWriter buffer = new BufferedWriter(ecriveur);
try
{
ecriveur.write(this.getContenu());
buffer.close();
ecriveur.close();
System.out.println("[SUCCES] Votre fichier a été sauvegardé !");
}
catch (IOException e)
{
System.out.print("[ERREUR] Le fichier n'a pas pu être ouvert... (" + e + ")");
}
}
catch(IOException e)
{
System.out.println("[ERREUR] Le fichier n'a pas été trouvé ! (" + e + ")");
}
}
public void editer()
{
//TODO
}
/*
* FONCTIONS A IMPLEMENTER PLUS TARD
public void ajouterComposant(Composant c)
{
//TODO
}
public void supprimerComposant(Composant c)
{
//TODO
}
public void ajouterAmperemetre(Amperemetre a)
{
//TODO
}
public void supprimerAmperemetre(Amperemetre a)
{
//TODO
}
public void ajouterVoltmetre(Voltmetre v)
{
//TODO
}
public void supprimerVoltmetre(Voltmetre v)
{
//TODO
}
*/
//-------------------------------------------------- accesseurs et mutateurs --------------------------------------------------//
public String getNom()
{
return nom;
}
public void setNom(String nom)
{
this.nom = nom;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getContenu()
{
return contenu;
}
public void setContenu(String contenu)
{
this.contenu = contenu;
}
}
|
package com.codigo.smartstore.xbase.database.structure.header;
public interface IXbFileHeader {
}
|
package br.com.fiap.dao;
import java.util.List;
import javax.persistence.Query;
import br.com.fiap.entity.Disciplina;
public class DisciplinaDao extends GenericDao<Disciplina> {
public List<Disciplina> buscarPorProfessor(Integer idProfessor) {
em = JpaUtil.getEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("select d from Disciplina d where professor.id = :idProfessor");
query.setParameter("idProfessor", idProfessor);
return query.getResultList();
}
}
|
package DAO;
import model.ModelVendasProdutos;
import connections.ConexaoMySql;
import java.sql.SQLException;
import java.util.ArrayList;
public class DAOVendasProdutos extends ConexaoMySql {
/**
* grava VendasProdutos
* @param pModelVendasProdutos
* return int
* @return
*/
public int salvarVendasProdutosDAO(ModelVendasProdutos pModelVendasProdutos){
try {
this.conectar();
return this.insertSQL(
"INSERT INTO tbl_vendas_produtos ("
+ "fk_produto,"
+ "fk_venda,"
+ "valor,"
+ "qtd"
+ ") VALUES ("
+ "'" + pModelVendasProdutos.getProduto() + "',"
+ "'" + pModelVendasProdutos.getVenda() + "',"
+ "'" + pModelVendasProdutos.getVenProValor() + "',"
+ "'" + pModelVendasProdutos.getVenProQtd() + "'"
+ ");"
);
} catch(Exception e){
return 0;
} finally{
this.fecharConexao();
}
}
/**
* recupera VendasProdutos
* @param pVendaProdutoId
* return ModelVendasProdutos
* @return
*/
public ModelVendasProdutos getVendasProdutosDAO(int pVendaProdutoId){
ModelVendasProdutos modelVendasProdutos = new ModelVendasProdutos();
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "pk_id_venda_produto,"
+ "fk_produto,"
+ "fk_venda,"
+ "valor,"
+ "qtd"
+ " FROM"
+ " tbl_vendas_produtos"
+ " WHERE"
+ " pk_id_venda_produto = '" + pVendaProdutoId + "'"
+ ";"
);
while(this.getResultSet().next()){
modelVendasProdutos.setVendaProdutoId(this.getResultSet().getInt(1));
modelVendasProdutos.setProduto(this.getResultSet().getInt(2));
modelVendasProdutos.setVenda(this.getResultSet().getInt (3));
modelVendasProdutos.setVenProValor(this.getResultSet().getDouble(4));
modelVendasProdutos.setVenProQtd(this.getResultSet().getInt(5));
}
} catch(SQLException e){
} finally{
this.fecharConexao();
}
return modelVendasProdutos;
}
/**
* recupera uma lista de VendasProdutos
* return ArrayList
* @return
*/
public ArrayList<ModelVendasProdutos> getListaVendasProdutosDAO(){
ArrayList<ModelVendasProdutos> listamodelVendasProdutos = new ArrayList();
ModelVendasProdutos modelVendasProdutos;
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "pk_id_venda_produto,"
+ "fk_produto,"
+ "fk_venda,"
+ "valor,"
+ "qtd"
+ " FROM"
+ " tbl_vendas_produtos"
+ ";"
);
while(this.getResultSet().next()){
modelVendasProdutos = new ModelVendasProdutos();
modelVendasProdutos.setVendaProdutoId(this.getResultSet().getInt(1));
modelVendasProdutos.setProduto(this.getResultSet().getInt(2));
modelVendasProdutos.setVenda(this.getResultSet().getInt (3));
modelVendasProdutos.setVenProValor(this.getResultSet().getDouble(4));
modelVendasProdutos.setVenProQtd(this.getResultSet().getInt(5));
listamodelVendasProdutos.add(modelVendasProdutos);
}
} catch(SQLException e){
} finally{
this.fecharConexao();
}
return listamodelVendasProdutos;
}
/**
* atualiza VendasProdutos
* @param pModelVendasProdutos
* return boolean
* @return
*/
public boolean atualizarVendasProdutosDAO(ModelVendasProdutos pModelVendasProdutos){
try {
this.conectar();
return this.executarUpdateDeleteSQL(
"UPDATE tbl_vendas_produtos SET "
+ "pk_id_venda_produto = '" + pModelVendasProdutos.getVendaProdutoId() + "',"
+ "fk_produto = '" + pModelVendasProdutos.getProduto() + "',"
+ "fk_venda = '" + pModelVendasProdutos.getVenda() + "',"
+ "valor = '" + pModelVendasProdutos.getVenProValor() + "',"
+ "qtd = '" + pModelVendasProdutos.getVenProQtd() + "'"
+ " WHERE "
+ "pk_id_venda_produto = '" + pModelVendasProdutos.getVendaProdutoId() + "'"
+ ";"
);
} catch(Exception e){
return false;
} finally{
this.fecharConexao();
}
}
/**
* exclui VendasProdutos
* @param pVendaProdutoId
* return boolean
* @return
*/
public boolean excluirVendasProdutosDAO(int pVendaProdutoId){
try {
this.conectar();
return this.executarUpdateDeleteSQL(
"DELETE FROM tbl_vendas_produtos "
+ " WHERE "
+ "fk_venda = '" + pVendaProdutoId + "'"
+ ";"
);
} catch(Exception e){
return false;
} finally{
this.fecharConexao();
}
}
/**
* Salva uma lista de produtos
* @param pListaModelVendasProdutos
* @return
*/
public boolean salvarVendasProdutosDAO(ArrayList<ModelVendasProdutos> pListaModelVendasProdutos) {
try {
this.conectar();
int tamanho = pListaModelVendasProdutos.size();
// Percorre a lista com os produtos e adiciona no banco um por um
for (int i = 0; i < tamanho; i++) {
this.insertSQL(
"INSERT INTO tbl_vendas_produtos ("
+ "fk_venda,"
+ "fk_produto,"
+ "valor,"
+ "qtd"
+ ") VALUES ("
+ "'" + pListaModelVendasProdutos.get(i).getVenda() + "',"
+ "'" + pListaModelVendasProdutos.get(i).getProduto() + "',"
+ "'" + pListaModelVendasProdutos.get(i).getVenProValor() + "',"
+ "'" + pListaModelVendasProdutos.get(i).getVenProQtd() + "'"
+ ");"
);
}
return true;
} catch(Exception e){
return false;
} finally{
this.fecharConexao();
}
}
public boolean getVendaPorProdutoDAO(int pCodigoProduto) {
try {
this.conectar();
this.executarSQL(
"SELECT "
+ "fk_produto"
+ " FROM"
+ " tbl_vendas_produtos"
+ " WHERE"
+ " fk_produto = '" + pCodigoProduto + "'"
+ ";"
);
return getResultSet().next();
} catch(SQLException e){
return false;
} finally{
this.fecharConexao();
}
}
}
|
package fr.ucbl.disp.vfos.controller.sensor.distance.laser;
import fr.ucbl.disp.vfos.controller.data.AData;
import fr.ucbl.disp.vfos.controller.sensor.distance.DistanceSensor;
public class LaserRangeFinderSensorBySerial extends DistanceSensor {
public AData perceive() throws InterruptedException {
// TODO Auto-generated method stub
return null;
}
public void run() {
// TODO Auto-generated method stub
}
}
|
package p0200;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class P0205CP extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.ORANGE);
g.fillRect(getX()+10, getY()+10, getWidth()-20, getHeight()-20);
}
}
|
package com.javarush.test.level08.lesson11.home09;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/* Работа с датой
1. Реализовать метод isDateOdd(String date) так, чтобы он возвращал true, если количество дней с начала года - нечетное число, иначе false
2. String date передается в формате MAY 1 2013
Пример:
JANUARY 1 2000 = true
JANUARY 2 2020 = false
*/
public class Solution
{
public static void main(String[] args) throws ParseException {
String input = "01 1 1987";
System.out.print(isDateOdd(input));
}
public static boolean isDateOdd(String m_date) throws ParseException {
SimpleDateFormat sd = new SimpleDateFormat("mm dd yyyy");
Date date = sd.parse(m_date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int[] array = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30,31};
// int month = date.getMonth();
int month = cal.get(Calendar.MONTH);//date.getMonth();
int days = cal.get(Calendar.DAY_OF_MONTH);//date.getDate();
for (int i = 0; i <= month; i++){
days += array[i];
if ((cal.get(Calendar.YEAR)%4 == 0) && (month > 1)){ //leap year
days += 1;
}
}
if (days % 2 == 1) {
return true;
}
else { return false;}
}
}
|
package au.edu.jcu.cp3406.smartereveryday.game2;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import java.util.Random;
class Goal {
private static final int GOAL_HEIGHT = 100;
private int boundingWidth, goalWidth;
private double x, y, xDir, speed;
private float left, right, bottom;
Goal(int boundingWidth, int boundingHeight, int goalWidthFactor, int speed) {
this.goalWidth = boundingWidth / goalWidthFactor;
this.boundingWidth = boundingWidth - goalWidth;
Random random = new Random();
x = random.nextInt(this.boundingWidth);
y = boundingHeight;
this.speed = speed;
xDir = 1;
}
void draw(Canvas canvas) {
canvas.save();
left = (float) x;
float top = (float) y - GOAL_HEIGHT;
right = (float) x + goalWidth;
bottom = (float) y;
Paint goalPaint = new Paint();
goalPaint.setColor(Color.GREEN);
goalPaint.setShadowLayer(10, 0, 20, Color.BLACK);
canvas.drawRect(left, top, right, bottom, goalPaint);
canvas.restore();
}
void move() {
x += xDir * speed;
if ((x < 1 && xDir < 0) || (x >= boundingWidth && xDir > 0)) {
xDir *= -1;
}
}
float getLeft() {
return left;
}
float getRight() {
return right;
}
float getBottom() {
return bottom;
}
}
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
import dalvik.system.VMRuntime;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;
// Run on host with:
// javac ThreadTest.java && java ThreadStress && rm *.class
// Through run-test:
// test/run-test {run-test-args} 004-ThreadStress [Main {ThreadStress-args}]
// (It is important to pass Main if you want to give parameters...)
//
// ThreadStress command line parameters:
// -n X .............. number of threads
// -d X .............. number of daemon threads
// -o X .............. number of overall operations
// -t X .............. number of operations per thread
// -p X .............. number of permits granted by semaphore
// --dumpmap ......... print the frequency map
// --locks-only ...... select a pre-set frequency map with lock-related operations only
// --allocs-only ..... select a pre-set frequency map with allocation-related operations only
// -oom:X ............ frequency of OOM (double)
// -sigquit:X ........ frequency of SigQuit (double)
// -alloc:X .......... frequency of Alloc (double)
// -largealloc:X ..... frequency of LargeAlloc (double)
// -nonmovingalloc:X.. frequency of NonMovingAlloc (double)
// -stacktrace:X ..... frequency of StackTrace (double)
// -exit:X ........... frequency of Exit (double)
// -sleep:X .......... frequency of Sleep (double)
// -wait:X ........... frequency of Wait (double)
// -timedwait:X ...... frequency of TimedWait (double)
// -timedpark:X ...... frequency of TimedPark (double)
// -syncandwork:X .... frequency of SyncAndWork (double)
// -queuedwait:X ..... frequency of QueuedWait (double)
public class Main implements Runnable {
public static final boolean DEBUG = false;
private static abstract class Operation {
/**
* Perform the action represented by this operation. Returns true if the thread should
* continue when executed by a runner (non-daemon) thread.
*/
public abstract boolean perform();
}
private final static class OOM extends Operation {
private final static int ALLOC_SIZE = 1024;
@Override
public boolean perform() {
try {
List<byte[]> l = new ArrayList<byte[]>();
while (true) {
l.add(new byte[ALLOC_SIZE]);
}
} catch (OutOfMemoryError e) {
}
return true;
}
}
private final static class SigQuit extends Operation {
private final static int sigquit;
private final static Method kill;
private final static int pid;
static {
int pidTemp = -1;
int sigquitTemp = -1;
Method killTemp = null;
try {
Class<?> osClass = Class.forName("android.system.Os");
Method getpid = osClass.getDeclaredMethod("getpid");
pidTemp = (Integer)getpid.invoke(null);
Class<?> osConstants = Class.forName("android.system.OsConstants");
Field sigquitField = osConstants.getDeclaredField("SIGQUIT");
sigquitTemp = (Integer)sigquitField.get(null);
killTemp = osClass.getDeclaredMethod("kill", int.class, int.class);
} catch (Exception e) {
Main.printThrowable(e);
}
pid = pidTemp;
sigquit = sigquitTemp;
kill = killTemp;
}
@Override
public boolean perform() {
try {
kill.invoke(null, pid, sigquit);
} catch (OutOfMemoryError e) {
} catch (Exception e) {
if (!e.getClass().getName().equals(Main.errnoExceptionName)) {
Main.printThrowable(e);
}
}
return true;
}
}
private final static class Alloc extends Operation {
private final static int ALLOC_SIZE = 1024; // Needs to be small enough to not be in LOS.
private final static int ALLOC_COUNT = 1024;
@Override
public boolean perform() {
try {
List<byte[]> l = new ArrayList<byte[]>();
for (int i = 0; i < ALLOC_COUNT; i++) {
l.add(new byte[ALLOC_SIZE]);
}
} catch (OutOfMemoryError e) {
}
return true;
}
}
private final static class LargeAlloc extends Operation {
private final static int PAGE_SIZE = 4096;
private final static int PAGE_SIZE_MODIFIER = 10; // Needs to be large enough for LOS.
private final static int ALLOC_COUNT = 100;
@Override
public boolean perform() {
try {
List<byte[]> l = new ArrayList<byte[]>();
for (int i = 0; i < ALLOC_COUNT; i++) {
l.add(new byte[PAGE_SIZE_MODIFIER * PAGE_SIZE]);
}
} catch (OutOfMemoryError e) {
}
return true;
}
}
private final static class NonMovingAlloc extends Operation {
private final static int ALLOC_SIZE = 1024; // Needs to be small enough to not be in LOS.
private final static int ALLOC_COUNT = 1024;
private final static VMRuntime runtime = VMRuntime.getRuntime();
@Override
public boolean perform() {
try {
List<byte[]> l = new ArrayList<byte[]>();
for (int i = 0; i < ALLOC_COUNT; i++) {
l.add((byte[]) runtime.newNonMovableArray(byte.class, ALLOC_SIZE));
}
} catch (OutOfMemoryError e) {
}
return true;
}
}
private final static class StackTrace extends Operation {
@Override
public boolean perform() {
try {
Thread.currentThread().getStackTrace();
} catch (OutOfMemoryError e) {
}
return true;
}
}
private final static class Exit extends Operation {
@Override
public boolean perform() {
return false;
}
}
private final static class Sleep extends Operation {
private final static int SLEEP_TIME = 100;
@Override
public boolean perform() {
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException ignored) {
}
return true;
}
}
private final static class TimedWait extends Operation {
private final static int SLEEP_TIME = 100;
private final Object lock;
public TimedWait(Object lock) {
this.lock = lock;
}
@Override
public boolean perform() {
synchronized (lock) {
try {
lock.wait(SLEEP_TIME, 0);
} catch (InterruptedException ignored) {
}
}
return true;
}
}
private final static class Wait extends Operation {
private final Object lock;
public Wait(Object lock) {
this.lock = lock;
}
@Override
public boolean perform() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ignored) {
}
}
return true;
}
}
private final static class TimedPark extends Operation {
private final static int SLEEP_TIME = 100;
public TimedPark() {}
@Override
public boolean perform() {
LockSupport.parkNanos(this, 100*1000000);
return true;
}
}
private final static class SyncAndWork extends Operation {
private final Object lock;
public SyncAndWork(Object lock) {
this.lock = lock;
}
@Override
public boolean perform() {
synchronized (lock) {
try {
Thread.sleep((int)(Math.random() * 50 + 50));
} catch (InterruptedException ignored) {
}
}
return true;
}
}
// An operation requiring the acquisition of a permit from a semaphore
// for its execution. This operation has been added to exercise
// java.util.concurrent.locks.AbstractQueuedSynchronizer, used in the
// implementation of java.util.concurrent.Semaphore. We use the latter,
// as the former is not supposed to be used directly (see b/63822989).
private final static class QueuedWait extends Operation {
private final static int SLEEP_TIME = 100;
private final Semaphore semaphore;
public QueuedWait(Semaphore semaphore) {
this.semaphore = semaphore;
}
@Override
public boolean perform() {
boolean permitAcquired = false;
try {
semaphore.acquire();
permitAcquired = true;
Thread.sleep(SLEEP_TIME);
} catch (OutOfMemoryError ignored) {
// The call to semaphore.acquire() above may trigger an OOME,
// despite the care taken doing some warm-up by forcing
// ahead-of-time initialization of classes used by the Semaphore
// class (see forceTransitiveClassInitialization below).
// For instance, one of the code paths executes
// AbstractQueuedSynchronizer.addWaiter, which allocates an
// AbstractQueuedSynchronizer$Node (see b/67730573).
// In that case, just ignore the OOME and continue.
} catch (InterruptedException ignored) {
} finally {
if (permitAcquired) {
semaphore.release();
}
}
return true;
}
}
private final static Map<Operation, Double> createDefaultFrequencyMap(Object lock,
Semaphore semaphore) {
Map<Operation, Double> frequencyMap = new HashMap<Operation, Double>();
frequencyMap.put(new OOM(), 0.005); // 1/200
frequencyMap.put(new SigQuit(), 0.095); // 19/200
frequencyMap.put(new Alloc(), 0.2); // 40/200
frequencyMap.put(new LargeAlloc(), 0.05); // 10/200
frequencyMap.put(new NonMovingAlloc(), 0.025); // 5/200
frequencyMap.put(new StackTrace(), 0.1); // 20/200
frequencyMap.put(new Exit(), 0.225); // 45/200
frequencyMap.put(new Sleep(), 0.075); // 15/200
frequencyMap.put(new TimedPark(), 0.05); // 10/200
frequencyMap.put(new TimedWait(lock), 0.05); // 10/200
frequencyMap.put(new Wait(lock), 0.075); // 15/200
frequencyMap.put(new QueuedWait(semaphore), 0.05); // 10/200
return frequencyMap;
}
private final static Map<Operation, Double> createAllocFrequencyMap() {
Map<Operation, Double> frequencyMap = new HashMap<Operation, Double>();
frequencyMap.put(new Sleep(), 0.2); // 40/200
frequencyMap.put(new Alloc(), 0.575); // 115/200
frequencyMap.put(new LargeAlloc(), 0.15); // 30/200
frequencyMap.put(new NonMovingAlloc(), 0.075); // 15/200
return frequencyMap;
}
private final static Map<Operation, Double> createLockFrequencyMap(Object lock) {
Map<Operation, Double> frequencyMap = new HashMap<Operation, Double>();
frequencyMap.put(new Sleep(), 0.2); // 40/200
frequencyMap.put(new TimedWait(lock), 0.1); // 20/200
frequencyMap.put(new Wait(lock), 0.2); // 40/200
frequencyMap.put(new SyncAndWork(lock), 0.4); // 80/200
frequencyMap.put(new TimedPark(), 0.1); // 20/200
return frequencyMap;
}
public static void main(String[] args) throws Exception {
System.loadLibrary(args[0]);
parseAndRun(args);
}
private static Map<Operation, Double> updateFrequencyMap(Map<Operation, Double> in,
Object lock, Semaphore semaphore, String arg) {
String split[] = arg.split(":");
if (split.length != 2) {
throw new IllegalArgumentException("Can't split argument " + arg);
}
double d;
try {
d = Double.parseDouble(split[1]);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
if (d < 0) {
throw new IllegalArgumentException(arg + ": value must be >= 0.");
}
Operation op = null;
if (split[0].equals("-oom")) {
op = new OOM();
} else if (split[0].equals("-sigquit")) {
op = new SigQuit();
} else if (split[0].equals("-alloc")) {
op = new Alloc();
} else if (split[0].equals("-largealloc")) {
op = new LargeAlloc();
} else if (split[0].equals("-nonmovingalloc")) {
op = new NonMovingAlloc();
} else if (split[0].equals("-stacktrace")) {
op = new StackTrace();
} else if (split[0].equals("-exit")) {
op = new Exit();
} else if (split[0].equals("-sleep")) {
op = new Sleep();
} else if (split[0].equals("-wait")) {
op = new Wait(lock);
} else if (split[0].equals("-timedwait")) {
op = new TimedWait(lock);
} else if (split[0].equals("-timedpark")) {
op = new TimedPark();
} else if (split[0].equals("-syncandwork")) {
op = new SyncAndWork(lock);
} else if (split[0].equals("-queuedwait")) {
op = new QueuedWait(semaphore);
} else {
throw new IllegalArgumentException("Unknown arg " + arg);
}
if (in == null) {
in = new HashMap<Operation, Double>();
}
in.put(op, d);
return in;
}
private static void normalize(Map<Operation, Double> map) {
double sum = 0;
for (Double d : map.values()) {
sum += d;
}
if (sum == 0) {
throw new RuntimeException("No elements!");
}
if (sum != 1.0) {
// Avoid ConcurrentModificationException.
Set<Operation> tmp = new HashSet<>(map.keySet());
for (Operation op : tmp) {
map.put(op, map.get(op) / sum);
}
}
}
public static void parseAndRun(String[] args) throws Exception {
int numberOfThreads = -1;
int numberOfDaemons = -1;
int totalOperations = -1;
int operationsPerThread = -1;
int permits = -1;
Object lock = new Object();
Map<Operation, Double> frequencyMap = null;
boolean dumpMap = false;
if (args != null) {
// args[0] is libarttest
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-n")) {
i++;
numberOfThreads = Integer.parseInt(args[i]);
} else if (args[i].equals("-d")) {
i++;
numberOfDaemons = Integer.parseInt(args[i]);
} else if (args[i].equals("-o")) {
i++;
totalOperations = Integer.parseInt(args[i]);
} else if (args[i].equals("-t")) {
i++;
operationsPerThread = Integer.parseInt(args[i]);
} else if (args[i].equals("-p")) {
i++;
permits = Integer.parseInt(args[i]);
} else if (args[i].equals("--locks-only")) {
frequencyMap = createLockFrequencyMap(lock);
} else if (args[i].equals("--allocs-only")) {
frequencyMap = createAllocFrequencyMap();
} else if (args[i].equals("--dumpmap")) {
dumpMap = true;
} else {
// Processing an argument of the form "-<operation>:X"
// (where X is a double value).
Semaphore semaphore = getSemaphore(permits);
frequencyMap = updateFrequencyMap(frequencyMap, lock, semaphore, args[i]);
}
}
}
if (totalOperations != -1 && operationsPerThread != -1) {
throw new IllegalArgumentException(
"Specified both totalOperations and operationsPerThread");
}
if (numberOfThreads == -1) {
numberOfThreads = 5;
}
if (numberOfDaemons == -1) {
numberOfDaemons = 3;
}
if (totalOperations == -1) {
totalOperations = 1000;
}
if (operationsPerThread == -1) {
operationsPerThread = totalOperations/numberOfThreads;
}
if (frequencyMap == null) {
Semaphore semaphore = getSemaphore(permits);
frequencyMap = createDefaultFrequencyMap(lock, semaphore);
}
normalize(frequencyMap);
if (dumpMap) {
System.out.println(frequencyMap);
}
try {
runTest(numberOfThreads, numberOfDaemons, operationsPerThread, lock, frequencyMap);
} catch (Throwable t) {
// In this case, the output should not contain all the required
// "Finishing worker" lines.
Main.printThrowable(t);
}
}
private static Semaphore getSemaphore(int permits) {
if (permits == -1) {
// Default number of permits.
permits = 3;
}
Semaphore semaphore = new Semaphore(permits, /* fair */ true);
forceTransitiveClassInitialization(semaphore, permits);
return semaphore;
}
// Force ahead-of-time initialization of classes used by Semaphore
// code. Try to exercise all code paths likely to be taken during
// the actual test later (including having a thread blocking on
// the semaphore trying to acquire a permit), so that we increase
// the chances to initialize all classes indirectly used by
// QueuedWait (e.g. AbstractQueuedSynchronizer$Node).
private static void forceTransitiveClassInitialization(Semaphore semaphore, final int permits) {
// Ensure `semaphore` has the expected number of permits
// before we start.
assert semaphore.availablePermits() == permits;
// Let the main (current) thread acquire all permits from
// `semaphore`. Then create an auxiliary thread acquiring a
// permit from `semaphore`, blocking because none is
// available. Have the main thread release one permit, thus
// unblocking the second thread.
// Auxiliary thread.
Thread auxThread = new Thread("Aux") {
public void run() {
try {
// Try to acquire one permit, and block until
// that permit is released by the main thread.
semaphore.acquire();
// When unblocked, release the acquired permit
// immediately.
semaphore.release();
} catch (InterruptedException ignored) {
throw new RuntimeException("Test set up failed in auxiliary thread");
}
}
};
// Main thread.
try {
// Acquire all permits.
semaphore.acquire(permits);
// Start the auxiliary thread and have it try to acquire a
// permit.
auxThread.start();
// Synchronization: Wait until the auxiliary thread is
// blocked trying to acquire a permit from `semaphore`.
while (!semaphore.hasQueuedThreads()) {
Thread.sleep(100);
}
// Release one permit, thus unblocking `auxThread` and let
// it acquire a permit.
semaphore.release();
// Synchronization: Wait for the auxiliary thread to die.
auxThread.join();
// Release remaining permits.
semaphore.release(permits - 1);
// Verify that all permits have been released.
assert semaphore.availablePermits() == permits;
} catch (InterruptedException ignored) {
throw new RuntimeException("Test set up failed in main thread");
}
}
public static void runTest(final int numberOfThreads, final int numberOfDaemons,
final int operationsPerThread, final Object lock,
Map<Operation, Double> frequencyMap) throws Exception {
final Thread mainThread = Thread.currentThread();
final Barrier startBarrier = new Barrier(numberOfThreads + numberOfDaemons + 1);
// Each normal thread is going to do operationsPerThread
// operations. Each daemon thread will loop over all
// the operations and will not stop.
// The distribution of operations is determined by
// the frequencyMap values. We fill out an Operation[]
// for each thread with the operations it is to perform. The
// Operation[] is shuffled so that there is more random
// interactions between the threads.
// Fill in the Operation[] array for each thread by laying
// down references to operation according to their desired
// frequency.
// The first numberOfThreads elements are normal threads, the last
// numberOfDaemons elements are daemon threads.
final Main[] threadStresses = new Main[numberOfThreads + numberOfDaemons];
for (int t = 0; t < threadStresses.length; t++) {
Operation[] operations = new Operation[operationsPerThread];
int o = 0;
LOOP:
while (true) {
for (Operation op : frequencyMap.keySet()) {
int freq = (int)(frequencyMap.get(op) * operationsPerThread);
for (int f = 0; f < freq; f++) {
if (o == operations.length) {
break LOOP;
}
operations[o] = op;
o++;
}
}
}
// Randomize the operation order
Collections.shuffle(Arrays.asList(operations));
threadStresses[t] = (t < numberOfThreads)
? new Main(lock, t, operations)
: new Daemon(lock, t, operations, mainThread, startBarrier);
}
// Enable to dump operation counts per thread to make sure its
// sane compared to frequencyMap.
if (DEBUG) {
for (int t = 0; t < threadStresses.length; t++) {
Operation[] operations = threadStresses[t].operations;
Map<Operation, Integer> distribution = new HashMap<Operation, Integer>();
for (Operation operation : operations) {
Integer ops = distribution.get(operation);
if (ops == null) {
ops = 1;
} else {
ops++;
}
distribution.put(operation, ops);
}
System.out.println("Distribution for " + t);
for (Operation op : frequencyMap.keySet()) {
System.out.println(op + " = " + distribution.get(op));
}
}
}
// Create the runners for each thread. The runner Thread
// ensures that thread that exit due to operation Exit will be
// restarted until they reach their desired
// operationsPerThread.
Thread[] runners = new Thread[numberOfThreads];
for (int r = 0; r < runners.length; r++) {
final Main ts = threadStresses[r];
runners[r] = new Thread("Runner thread " + r) {
final Main threadStress = ts;
public void run() {
try {
int id = threadStress.id;
// No memory hungry task are running yet, so println() should succeed.
System.out.println("Starting worker for " + id);
// Wait until all runners and daemons reach the starting point.
startBarrier.await();
// Run the stress tasks.
while (threadStress.nextOperation < operationsPerThread) {
try {
Thread thread = new Thread(ts, "Worker thread " + id);
thread.start();
thread.join();
if (DEBUG) {
System.out.println(
"Thread exited for " + id + " with " +
(operationsPerThread - threadStress.nextOperation) +
" operations remaining.");
}
} catch (OutOfMemoryError e) {
// Ignore OOME since we need to print "Finishing worker"
// for the test to pass. This OOM can come from creating
// the Thread or from the DEBUG output.
// Note that the Thread creation may fail repeatedly,
// preventing the runner from making any progress,
// especially if the number of daemons is too high.
}
}
// Print "Finishing worker" through JNI to avoid OOME.
Main.printString(Main.finishingWorkerMessage);
} catch (Throwable t) {
Main.printThrowable(t);
// Interrupt the main thread, so that it can orderly shut down
// instead of waiting indefinitely for some Barrier.
mainThread.interrupt();
}
}
};
}
// The notifier thread is a daemon just loops forever to wake
// up threads in operations Wait and Park.
if (lock != null) {
Thread notifier = new Thread("Notifier") {
public void run() {
while (true) {
synchronized (lock) {
lock.notifyAll();
}
for (Thread runner : runners) {
if (runner != null) {
LockSupport.unpark(runner);
}
}
}
}
};
notifier.setDaemon(true);
notifier.start();
}
// Create and start the daemon threads.
for (int r = 0; r < numberOfDaemons; r++) {
Main daemon = threadStresses[numberOfThreads + r];
Thread t = new Thread(daemon, "Daemon thread " + daemon.id);
t.setDaemon(true);
t.start();
}
for (int r = 0; r < runners.length; r++) {
runners[r].start();
}
// Wait for all threads to reach the starting point.
startBarrier.await();
// Wait for runners to finish.
for (int r = 0; r < runners.length; r++) {
runners[r].join();
}
}
protected final Operation[] operations;
private final Object lock;
protected final int id;
private int nextOperation;
private Main(Object lock, int id, Operation[] operations) {
this.lock = lock;
this.id = id;
this.operations = operations;
}
public void run() {
try {
if (DEBUG) {
System.out.println("Starting ThreadStress " + id);
}
while (nextOperation < operations.length) {
Operation operation = operations[nextOperation];
if (DEBUG) {
System.out.println("ThreadStress " + id
+ " operation " + nextOperation
+ " is " + operation);
}
nextOperation++;
if (!operation.perform()) {
return;
}
}
} finally {
if (DEBUG) {
System.out.println("Finishing ThreadStress for " + id);
}
}
}
private static class Daemon extends Main {
private Daemon(Object lock,
int id,
Operation[] operations,
Thread mainThread,
Barrier startBarrier) {
super(lock, id, operations);
this.mainThread = mainThread;
this.startBarrier = startBarrier;
}
public void run() {
try {
if (DEBUG) {
System.out.println("Starting ThreadStress Daemon " + id);
}
startBarrier.await();
try {
int i = 0;
while (true) {
Operation operation = operations[i];
if (DEBUG) {
System.out.println("ThreadStress Daemon " + id
+ " operation " + i
+ " is " + operation);
}
// Ignore the result of the performed operation, making
// Exit.perform() essentially a no-op for daemon threads.
operation.perform();
i = (i + 1) % operations.length;
}
} catch (OutOfMemoryError e) {
// Catch OutOfMemoryErrors since these can cause the test to fail it they print
// the stack trace after "Finishing worker". Note that operations should catch
// their own OOME, this guards only agains OOME in the DEBUG output.
}
if (DEBUG) {
System.out.println("Finishing ThreadStress Daemon for " + id);
}
} catch (Throwable t) {
Main.printThrowable(t);
// Interrupt the main thread, so that it can orderly shut down
// instead of waiting indefinitely for some Barrier.
mainThread.interrupt();
}
}
final Thread mainThread;
final Barrier startBarrier;
}
// Note: java.util.concurrent.CyclicBarrier.await() allocates memory and may throw OOM.
// That is highly undesirable in this test, so we use our own simple barrier class.
// The only memory allocation that can happen here is the lock inflation which uses
// a native allocation. As such, it should succeed even if the Java heap is full.
// If the native allocation surprisingly fails, the program shall abort().
private static class Barrier {
public Barrier(int initialCount) {
count = initialCount;
}
public synchronized void await() throws InterruptedException {
--count;
if (count != 0) {
do {
wait();
} while (count != 0); // Check for spurious wakeup.
} else {
notifyAll();
}
}
private int count;
}
// Printing a String/Throwable through JNI requires only native memory and space
// in the local reference table, so it should succeed even if the Java heap is full.
private static native void printString(String s);
private static native void printThrowable(Throwable t);
static final String finishingWorkerMessage;
static final String errnoExceptionName;
static {
// We pre-allocate the strings in class initializer to avoid const-string
// instructions in code using these strings later as they may throw OOME.
finishingWorkerMessage = "Finishing worker\n";
errnoExceptionName = "ErrnoException";
}
}
|
package Control;
import Entidad.Productos;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
public class ControlGestionarPresupuesto {
public void modificarProductos(Vector listaVector){
if(!(listaVector == null)){
List<Productos> lista = new ArrayList();
for(int i=0; i<listaVector.size();i++){
Productos producto = new Productos();
producto.setNombreProducto((String)((Vector) listaVector.get(i)).get(0));
producto.setDineroDisponible((Float)((Vector)listaVector.get(i)).get(1));
if(!producto.getNombreProducto().equals(null))
lista.add(producto);
}
}
}
public String verificarProducto (Productos producto) {
if (!verificarLongitudPrecio(producto.getNombreProducto())){
return ("Longitud de nombre incorrecta");}
if (!verificarLongitudPrecio(producto.getDineroDisponible()))
return ("Precio incorrecto");
return("Correcto");
}
// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
// #[regen=yes,id=DCE.C3D0DA41-6C85-B034-CD6F-281FB8395B50]
// </editor-fold>
public boolean verificarLongitudPrecio (String producto) {
return(producto.length() > 3 && producto.length()<=12);
}
// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
// #[regen=yes,id=DCE.2428B11A-C5F0-9E85-4B8B-3A2CB01CA09B]
// </editor-fold>
public boolean verificarLongitudPrecio (float precio) {
return(precio >= 0 && precio<10000000);
}
public String estandarizarNombre(String nombre){
String nuevo="";
nuevo = nuevo + Character.toUpperCase(nombre.charAt(0));
for (int i=1; i < nombre.length(); i++){
if(nombre.charAt(i)>= 'A' && nombre.charAt(i) <= 'Z' ){
nuevo = nuevo + Character.toLowerCase(nombre.charAt(i));
}else{
nuevo = nuevo + nombre.charAt(i);
}
}
return nuevo;
}
}
|
package com.cwelth.industrialessentials.blocks;
import com.cwelth.industrialessentials.tileentities.CoalGeneratorTE;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.INamedContainerProvider;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import javax.annotation.Nullable;
public class CoalGenerator extends ModelledBlock {
public CoalGenerator() {
}
@Override
public boolean hasTileEntity(BlockState state) {
return true;
}
@Nullable
@Override
public TileEntity createTileEntity(BlockState state, IBlockReader world) {
return new CoalGeneratorTE();
}
@Override
public ActionResultType onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult p_225533_6_) {
if (!worldIn.isRemote) {
CoalGeneratorTE te = (CoalGeneratorTE)worldIn.getTileEntity(pos);
if (te instanceof INamedContainerProvider) {
NetworkHooks.openGui((ServerPlayerEntity) player, te, te.getPos());
} else {
throw new IllegalStateException("Our named container provider is missing!");
}
return ActionResultType.SUCCESS;
}
return super.onBlockActivated(state, worldIn, pos, player, handIn, p_225533_6_);
}
}
|
package jp.ac.hal.Util;
public class InputCheck {
/**
* 引数にNullまたは空文字があった場合trueを返す
* @param org
* @return
*/
public boolean checkNullChar(String... args) {
boolean err = false;
for (String str : args) {
err |= (str == null || str.length() == 0);
}
return err;
}
/**
* 引数strが引数lengthより大きい文字数だった場合trueを返す
* @param str
* @param length
* @return
*/
public boolean checkCharaLength(String str, int length) {
return str.length() > length;
}
/**
* 引数strに数字以外が含まれている場合trueを返す
* @param str
* @return
*/
public boolean checkNumbers(String... args) {
boolean err = false;
try {
for (String str : args) {
Integer.parseInt(str);
}
} catch (NumberFormatException e) {
err = true;
}
return err;
}
/**
* 数字-のみ
* @param args
* @return
*/
public boolean addressAndPhoneValidator(String... args) {
boolean err = false;
String pattern = "[0-9a-zA-Z-]+";
for (String str : args) {
if (!str.matches(pattern)) {
err |= true;
}
}
return err;
}
/**
* メールアドレスかどうか
* @param args
* @return
*/
public boolean checkMailAddress(String... args){
boolean err = false;
for (String str : args) {
if (!str.matches("[\\w\\.\\-]+@(?:[\\w\\-]+\\.)+[\\w\\-]+")){
err = true;
}
}
return err;
}
}
|
package com.lemo.cmx.springlong;
/**
* Created by 罗选通 on 2017/11/7.
*/
public interface MessageProvider {
String queryForMessage(String name);
}
|
//Example to show method overloding in java
import java.util.*;
class Addition
{
private double num1,num2,num3,num4,add;
void input(int a,int b)
{
num1=a;num2=b;num3=num4=0.0;
}
void input(int a,int b,int c)
{
num1=a;num2=b;num3=c;num4=0.0;
}
void input(int a,int b,int c,int d)
{
num1=a;num2=b;num3=c;num4=d;
}
double sum()
{
add=num1+num2+num3+num4;
return(add);
}
void disp()
{
System.out.println("Sum of number="+add);
}
}//close of class
class Addition1{
public static void main(String args[])
{
Addition no=new Addition();
no.input(10,20);
System.out.println("Sum of two number:-"+no.sum());
no.input(10,20,30);
System.out.println("Sum of Three number:-"+no.sum());
no.input(10,20,30,40);
no.sum();
no.disp();
}//close of main
}//close of main class
|
package com.djtracksholder.djtracksholder.utils;
/**
* Created by Вадим on 22.08.2014.
*/
import android.content.Context;
import android.graphics.Typeface;
/**
* Created by Вадим on 01.07.2014.
*/
public class TypefaceFactory {
private static final String FONTS_PATH = "fonts/";
private static final String RALEWAY_BOLD = FONTS_PATH + "Raleway-Bold.otf";
private static final String RALEWAY_EXTRA_BOLD = FONTS_PATH + "Raleway-ExtraBold.otf";
private static final String RALEWAY_EXTRA_LIGHT = FONTS_PATH + "Raleway-ExtraLight.otf";
private static final String RALEWAY_HEAVY = FONTS_PATH + "Raleway-Heavy.otf";
private static final String RALEWAY_LIGHT = FONTS_PATH + "Raleway-Light.otf";
private static final String RALEWAY_MEDIUM = FONTS_PATH + "Raleway-Medium.otf";
private static final String RALEWAY_REGULAR = FONTS_PATH + "Raleway-Regular.otf";
private static final String RALEWAY_SEMI_BOLD = FONTS_PATH + "Raleway-SemiBold.otf";
private static final String RALEWAY_THIN = FONTS_PATH + "Raleway-Thin.otf";
private static final String BRANNBOLL_FET = FONTS_PATH + "BranbollFet.ttf";
private static final String BRANNBOLL_SMALL = FONTS_PATH + "BranbollSmall.ttf";
private static final String LOVELO_BOLD = FONTS_PATH + "LoveloLineBold.otf";
private static final String LOVELO_LIGHT = FONTS_PATH + "LoveloLineLight.otf";
private static final String LOVELO_BLACK = FONTS_PATH + "LoveloBlack.otf";
private Context context;
private static TypefaceFactory factory;
public static void init(Context context) {
if (factory == null) {
factory = new TypefaceFactory(context);
}
}
private TypefaceFactory(Context context) {
this.context = context;
}
private Context getContext() { return this.context; }
private static Typeface getTypeFace(Context context, String srcFontPath) {
return Typeface.createFromAsset(context.getAssets(), srcFontPath);
}
public static Typeface getRalewayBold() {
return getTypeFace(factory.getContext(), RALEWAY_BOLD);
}
public static Typeface getRalewayExtraBold() {
return getTypeFace(factory.getContext(), RALEWAY_EXTRA_BOLD);
}
public static Typeface getRalewayExtraLight() {
return getTypeFace(factory.getContext(), RALEWAY_EXTRA_LIGHT);
}
public static Typeface getRalewayHeavy() {
return getTypeFace(factory.getContext(), RALEWAY_HEAVY);
}
public static Typeface getRalewayLight() {
return getTypeFace(factory.getContext(), RALEWAY_LIGHT);
}
public static Typeface getRalewayMedium() {
return getTypeFace(factory.getContext(), RALEWAY_MEDIUM);
}
public static Typeface getRalewayRegular() {
return getTypeFace(factory.getContext(), RALEWAY_REGULAR);
}
public static Typeface getRalewaySemiBold() {
return getTypeFace(factory.getContext(), RALEWAY_SEMI_BOLD);
}
public static Typeface getBranbollFet() {
return getTypeFace(factory.getContext(), BRANNBOLL_FET);
}
public static Typeface getBranbollSmall() {
return getTypeFace(factory.getContext(), BRANNBOLL_SMALL);
}
public static Typeface getLoveloBlack() {
return getTypeFace(factory.getContext(), LOVELO_BLACK);
}
public static Typeface getLoveloBold() {
return getTypeFace(factory.getContext(), LOVELO_BOLD);
}
public static Typeface getLoveloLight() {
return getTypeFace(factory.getContext(), LOVELO_LIGHT);
}
public static Typeface getRalewayThin() {
return getTypeFace(factory.getContext(), RALEWAY_THIN);
}
}
|
package com.zd.christopher.proxy;
import javax.annotation.Resource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import com.zd.christopher.bean.Entity;
import com.zd.christopher.dao.EntityDAO;
import com.zd.christopher.dao.Many2ManyDAO;
@Aspect
@Component
public class Many2ManyDAOProxy<TEntity extends Entity>
{
@Resource
private Many2ManyDAO<TEntity> many2ManyDAO;
@SuppressWarnings("unused")
@Pointcut("execution(public boolean com.zd.christopher.dao..*.update*(..)) && !execution(public boolean com.zd.christopher.dao.Many2ManyDAO.*(..))")
private void update()
{
}
@Around("update() && args(entity)")
public boolean updateImpl(ProceedingJoinPoint pjp, TEntity entity) throws Throwable
{
String methodName = pjp.getSignature().getName();
String updatedField = methodName.substring(6, 7).toLowerCase() + methodName.substring(7);
many2ManyDAO.setUpdatedField(updatedField);
many2ManyDAO.setEntityClass(((EntityDAO<TEntity>) pjp.getTarget()).getEntityClass());
return many2ManyDAO.update(entity);
}
}
|
/*
* Copyright 2002-2012 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.lang;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
/**
* Represents a latitude and longitude pair, giving a position on earth in spherical coordinates.
* Values of latitude and longitude are given in degrees.
* This type is immutable.
*/
public final class GeoLocation
{
private final double _latitude;
private final double _longitude;
/**
* Instantiates a new instance of {@link GeoLocation}.
*
* @param latitude the latitude, in degrees
* @param longitude the longitude, in degrees
*/
public GeoLocation(double latitude, double longitude)
{
_latitude = latitude;
_longitude = longitude;
}
/**
* @return the latitudinal angle of this location, in degrees.
*/
public double getLatitude()
{
return _latitude;
}
/**
* @return the longitudinal angle of this location, in degrees.
*/
public double getLongitude()
{
return _longitude;
}
/**
* @return true, if both latitude and longitude are equal to zero
*/
public boolean isZero()
{
return _latitude == 0 && _longitude == 0;
}
/**
* Converts a decimal degree angle into its corresponding DMS (degrees-minutes-seconds) representation as a string,
* of format: {@code -1° 23' 4.56"}
*/
@NotNull
public static String decimalToDegreesMinutesSecondsString(double decimal)
{
double[] dms = decimalToDegreesMinutesSeconds(decimal);
return dms[0] + "° " + dms[1] + "' " + dms[2] + '"';
}
/**
* Converts a decimal degree angle into its corresponding DMS (degrees-minutes-seconds) component values, as
* a double array.
*/
@NotNull
public static double[] decimalToDegreesMinutesSeconds(double decimal)
{
int d = (int)decimal;
double m = Math.abs((decimal % 1) * 60);
double s = (m % 1) * 60;
return new double[] { d, (int)m, s};
}
/**
* Converts DMS (degrees-minutes-seconds) rational values, as given in {@link com.drew.metadata.exif.GpsDirectory},
* into a single value in degrees, as a double.
*/
@Nullable
public static Double degreesMinutesSecondsToDecimal(@NotNull final Rational degs, @NotNull final Rational mins, @NotNull final Rational secs, final boolean isNegative)
{
double decimal = Math.abs(degs.doubleValue())
+ mins.doubleValue() / 60.0d
+ secs.doubleValue() / 3600.0d;
if (Double.isNaN(decimal))
return null;
if (isNegative)
decimal *= -1;
return decimal;
}
@Override
public boolean equals(final Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GeoLocation that = (GeoLocation) o;
if (Double.compare(that._latitude, _latitude) != 0) return false;
if (Double.compare(that._longitude, _longitude) != 0) return false;
return true;
}
@Override
public int hashCode()
{
int result;
long temp;
temp = _latitude != +0.0d ? Double.doubleToLongBits(_latitude) : 0L;
result = (int) (temp ^ (temp >>> 32));
temp = _longitude != +0.0d ? Double.doubleToLongBits(_longitude) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
/**
* @return a string representation of this location, of format: {@code 1.23, 4.56}
*/
@Override
@NotNull
public String toString()
{
return _latitude + ", " + _longitude;
}
/**
* @return a string representation of this location, of format: {@code -1° 23' 4.56", 54° 32' 1.92"}
*/
@NotNull
public String toDMSString()
{
return decimalToDegreesMinutesSecondsString(_latitude) + ", " + decimalToDegreesMinutesSecondsString(_longitude);
}
}
|
package org.shiro.demo.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* 夺宝计划参与情况
* @author Christy
*
*/
@Entity
@Table(name="db_dbattend")
public class DBAttend {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="attendid")
private Long attendid;//id
@Column(name="createtime")
private Long createTime;//创建时间
@Column(name="isplay")
private Integer isplay;//是否付款
@ManyToOne(fetch = FetchType.LAZY,cascade = {CascadeType.MERGE })
@JoinColumn(name = "customerid")
private Customer customer;//顾客
@ManyToOne(fetch = FetchType.LAZY,cascade = {CascadeType.MERGE })
@JoinColumn(name = "dbplanid")
private DBPlan dbPlan;//参与夺宝计划
public DBAttend() {
super();
}
public DBAttend(Long attendid, Long createTime, Integer isplay,
Customer customer, DBPlan dbPlan) {
super();
this.attendid = attendid;
this.createTime = createTime;
this.isplay = isplay;
this.customer = customer;
this.dbPlan = dbPlan;
}
public DBAttend(Long createTime, Integer isplay, Customer customer,
DBPlan dbPlan) {
super();
this.createTime = createTime;
this.isplay = isplay;
this.customer = customer;
this.dbPlan = dbPlan;
}
public Long getAttendid() {
return attendid;
}
public void setAttendid(Long attendid) {
this.attendid = attendid;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Integer getIsplay() {
return isplay;
}
public void setIsplay(Integer isplay) {
this.isplay = isplay;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public DBPlan getDbPlan() {
return dbPlan;
}
public void setDbPlan(DBPlan dbPlan) {
this.dbPlan = dbPlan;
}
}
|
package practica;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;
@SuppressWarnings("unchecked")
public class Graph {
private int v;
private LinkedList<Integer>[] adj;
public Graph(int v) {
this.v = v;
adj = new LinkedList[v];
for (int i = 0; i < v; i++) {
adj[i] = new LinkedList<>();
}
}
public void agregarArista(int v, int w) {
adj[v].add(w);
}
public void topologicalSort() {
Stack<Integer> pila = new Stack<>();
boolean visitado[] = new boolean[v];
for (int i = 0; i < v; i++) {
if(visitado[i] == false) {
ordenarTopologicoUtil(i, visitado, pila);
}
}
while(pila.isEmpty() == false) {
System.out.println(pila.pop() + " ");
}
}
public void ordenarTopologicoUtil(int v, boolean visitado[],Stack<Integer> pila) {
visitado[v] = true;
Integer i;
Iterator<Integer> it = adj[v].iterator();
while(it.hasNext()) {
i = it.next();
if(!visitado[i]) {
ordenarTopologicoUtil(i, visitado, pila);
}
}
pila.push(v);
}
public static void main(String[] args) {
Graph g = new Graph(6);
g.agregarArista(5, 2);
g.agregarArista(5, 0);
g.agregarArista(4, 0);
g.agregarArista(4, 1);
g.agregarArista(2, 3);
g.agregarArista(3, 1);
System.out.println("El orden topologico es: \n");
g.topologicalSort();
}
}
|
package com.git.cloud.resmgt.common.service.impl;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.git.cloud.common.enums.EnumResouseHeader;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.foundation.common.WebApplicationManager;
import com.git.cloud.foundation.util.PwdUtil;
import com.git.cloud.handler.automation.LinkRouteType;
import com.git.cloud.resmgt.common.CloudClusterConstants;
import com.git.cloud.resmgt.common.dao.impl.CmPasswordDAO;
import com.git.cloud.resmgt.common.dao.impl.CmVmDAO;
import com.git.cloud.resmgt.common.dao.impl.RmDatacenterDAO;
import com.git.cloud.resmgt.common.dao.impl.RmVmManageServerDAO;
import com.git.cloud.resmgt.common.model.po.CmPasswordPo;
import com.git.cloud.resmgt.common.model.po.CmVmPo;
import com.git.cloud.resmgt.common.model.po.RmVmManageServerPo;
import com.git.cloud.resmgt.common.service.ICheckResource;
import com.git.support.common.MesgFlds;
import com.git.support.common.VMFlds;
import com.git.support.common.VmReturnFlds;
import com.git.support.general.field.GeneralKeyField;
import com.git.support.invoker.common.impl.ResAdptInvokerFactory;
import com.git.support.invoker.common.inf.IResAdptInvoker;
import com.git.support.sdo.impl.BodyDO;
import com.git.support.sdo.impl.DataObject;
import com.git.support.sdo.impl.HeaderDO;
import com.git.support.sdo.inf.IDataObject;
@Service
public class CheckResourceImpl implements ICheckResource {
private static final Logger log = LoggerFactory.getLogger(CheckResourceImpl.class);
private ResAdptInvokerFactory invkerFactory;
@Override
public boolean checkVmInVc(String vmId) throws RollbackableBizException {
CmVmDAO cmVmDao = (CmVmDAO) WebApplicationManager.getBean("cmVmDAO");
CmVmPo vmPo = cmVmDao.findCmVmById(vmId);
RmVmManageServerDAO rmVmMSDao = (RmVmManageServerDAO) WebApplicationManager.getBean("rmVmManageServerDAO");
RmVmManageServerPo vmManagerServerPo = rmVmMSDao.findRmVmManageServerByVmId(vmId);
String uuid = vmPo.getIaasUuid();
IDataObject reqData = DataObject.CreateDataObject();
HeaderDO header = HeaderDO.CreateHeaderDO();
header.setResourceClass(EnumResouseHeader.VM_RES_CLASS.getValue());
header.setResourceType(EnumResouseHeader.VM_RES_TYPE.getValue());
// header.setOperation(VMOpration.QUERY_VM_INFO);
header.setOperationBean("queryVmInfoServiceImpl");
// 增加数据中心路由标识
RmDatacenterDAO rmDcDao = (RmDatacenterDAO)WebApplicationManager.getBean("rmDatacenterDAO");
String queueIdentify = rmDcDao.getDataCenterById(vmManagerServerPo.getDatacenterId()).getQueueIden();
header.set(LinkRouteType.DATACENTER_QUEUE_IDEN.getValue(),
queueIdentify);
reqData.setDataObject(MesgFlds.HEADER, header);
BodyDO body = BodyDO.CreateBodyDO();
String hostIp=vmManagerServerPo.getManageIp();
String userName = vmManagerServerPo.getUserName();
String password = "";
try {
CmPasswordDAO cmPasswordDAO = (CmPasswordDAO)WebApplicationManager.getBean("cmPasswordDAO");
CmPasswordPo pwpo = cmPasswordDAO.findCmPasswordByResourceUser(vmManagerServerPo.getId(), userName);
password = pwpo.getPassword();
if(StringUtils.isBlank(password))
throw new Exception("获取ManagerServer[" + vmManagerServerPo.getId() + "] password is null");
password = PwdUtil.decryption(password);
} catch (Exception e) {
log.error("异常exception",e);
}
body.set(VMFlds.ESXI_URL, CloudClusterConstants.VCENTER_URL_HTTPS+hostIp+CloudClusterConstants.VCENTER_URL_SDK);
body.set(VMFlds.ESXI_USERNAME, userName);
body.set(VMFlds.ESXI_PASSWORD, password);
if(invkerFactory==null){
invkerFactory = (ResAdptInvokerFactory) WebApplicationManager.getBean("resInvokerFactory");
}
IResAdptInvoker invoker = invkerFactory.findInvoker("AMQ");
body.set(VMFlds.VAPP_NAME, vmPo.getDeviceName());
reqData.setDataObject(MesgFlds.BODY, body);
IDataObject rsp;
try {
rsp = invoker.invoke(reqData, 300000);
BodyDO rspBody = (BodyDO)rsp.get(MesgFlds.BODY);
DataObject vmObj = (DataObject)rspBody.get(VmReturnFlds.VM_NAME);
String vcUUID = vmObj.getString(GeneralKeyField.VM.UUID);
// System.out.println(vmObj.get(GeneralKeyField.VM.UUID));
// System.out.println(vmObj.getString(GeneralKeyField.VM.UUID));
log.info("vCenter中的uuid:"+vcUUID+", 云平台中的uuid:"+uuid);
if(vcUUID!=null && vcUUID.equals(uuid)){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
|
package com.atguigu.jdbc.utils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/*
* ThreadLocal: 在每个线程的本地保存数据.
* 为每个线程创建一个ThreadLocalMap,每个线程操作的是自己的ThreadLocalMap中的数据。
* 提供set(T)向Map中存放变量
* 提供get()获取之前保存的变量
* 提供remove()移除之前保存的变量
*
* 原生方式获取Coonection
* 每个线程最多只能创建一个Connection
*
*/
public class JDBCUtils {
private static ThreadLocal<Connection> threadLocal;
private static String username;
private static String password;
private static String jdbcUrl;
private static String driverClass;
private static Properties props;
static {
props=new Properties();
try {
props.load(JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
username = props.getProperty("username");
password=props.getProperty("password");
jdbcUrl=props.getProperty("url");
driverClass=props.getProperty("driverClassName");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
threadLocal=new ThreadLocal<>();
}
//获取Connection
public static Connection getConn() throws SQLException {
// 获取之前,先从ThreadLocal中尝试获取Conn
Connection connection = threadLocal.get();
if (connection==null) {
connection= DriverManager.getConnection(jdbcUrl, username, password);
}
threadLocal.set(connection);
return connection;
}
// 释放资源
public static void close(ResultSet rs,Statement s,Connection c) throws Exception {
if (rs !=null) {
rs.close();
}
if (s != null) {
s.close();
}
if (c !=null) {
c.close();
threadLocal.remove();
}
}
}
|
package com.github.fierioziy.particlenativeapi.core.mocks.nms.v1_7;
import com.github.fierioziy.particlenativeapi.core.mocks.nms.common.Packet;
public class PlayerConnection_1_7 {
public PlayerConnection_1_7() {}
// required
public void sendPacket(Packet packet) {}
}
|
package tardis.implementation;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import jbse.mem.Clause;
import static tardis.implementation.Util.shorten;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import tardis.Main;
/**
* Class that takes as input the path conditions processed by EvoSuite.
* The bloom filter structure is produced using the concrete and abstract
* path conditions. The bloom filter structure is added to the training
* set associated with label 0:infeasible or 1:feasible.
* If LogManager.generateCSV is set to true the data (path condition,
* abstract path condition, concrete path condition, bloom filter structure,
* label) are added to csv.
*/
public class TrainingSetManager {
//print the bitSet array as a series of bits
public static String[] printBits(BitSet[] array) {
String[] arr = new String[ConvertPCToBloomFilter.N_ROWS];
for (int i = 0; i < ConvertPCToBloomFilter.N_ROWS; i++) {
StringBuilder s = new StringBuilder();
for (int j = 0; j < ConvertPCToBloomFilter.N_COLUMNS; j++) {
s.append(array[i].get(j) ? "1" : "0");
}
arr[i] = s.toString();
}
return arr;
}
//save training set information in file.csv
public static void PrintToCSV(String PathToString, String[] generalArray, String[] generalArraySliced, String[] specificArray, String[] specificArraySliced, Object[] clauseArray, BitSet[] bloomFilterStructure, String label) throws IOException {
File directory = new File(LogManager.PATH);
if (!directory.exists()){
directory.mkdir();
}
File csv = new File(LogManager.PATH+"trainingSet.csv");
try(FileWriter fw = new FileWriter(csv, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
if (csv.length()==0) {
out.println("Original path condition;General path condition;General path condition sliced;Specific path condition;Specific path condition sliced;ClauseArray;BloomFilterStructure;Label");
out.println(PathToString+";"+Arrays.toString(generalArray)+";"+Arrays.toString(generalArraySliced)+";"+Arrays.toString(specificArray)+";"+Arrays.toString(specificArraySliced)+";"+Arrays.toString(clauseArray)+";"+Arrays.toString(printBits(bloomFilterStructure))+";"+label);
}
else {
out.println(PathToString+";"+Arrays.toString(generalArray)+";"+Arrays.toString(generalArraySliced)+";"+Arrays.toString(specificArray)+";"+Arrays.toString(specificArraySliced)+";"+Arrays.toString(clauseArray)+";"+Arrays.toString(printBits(bloomFilterStructure))+";"+label);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
//manage the path conditions from which EvoSuite is able or not able to generate test cases
public static void PCEvosuiteSuccessFailure(Collection<Clause> PC, boolean evosuiteResult) throws IOException {
if(PC!=null) {
Object[] clauseArray = shorten(PC).toArray();
String PathToString = Util.stringifyPathCondition(shorten(PC));
//split pc clauses into array
String[] generalArray = PathToString.split(" && ");
String[] specificArray = PathToString.split(" && ");
//generate general clauses
for (int i=0; i < generalArray.length; i++){
generalArray[i]=generalArray[i].replaceAll("[0-9]", "");
}
//Slicing call
Object[] outputSliced = SlicingManager.Slicing(specificArray, clauseArray, generalArray);
String[] specificArraySliced = (String[]) outputSliced[0];
String[] generalArraySliced = (String[]) outputSliced[1];
BitSet[] bloomFilterStructure = ConvertPCToBloomFilter.bloomFilter(specificArraySliced, generalArraySliced);
//add to trainingSet
if (evosuiteResult == true) {
Main.trainingSet.add(new StructureLaberPair(bloomFilterStructure, 1));
if (LogManager.generateCSV)
PrintToCSV(PathToString, generalArray, generalArraySliced, specificArray, specificArraySliced, clauseArray, bloomFilterStructure, "1");
System.out.println("[ML MODEL] For path condition: " + PathToString);
System.out.println("[ML MODEL] PCEvosuiteSuccess: Data add to Training Set");
}
else {
Main.trainingSet.add(new StructureLaberPair(bloomFilterStructure, 0));
if (LogManager.generateCSV)
PrintToCSV(PathToString, generalArray, generalArraySliced, specificArray, specificArraySliced, clauseArray, bloomFilterStructure, "0");
System.out.println("[ML MODEL] For path condition: " + PathToString);
System.out.println("[ML MODEL] PCEvosuiteFailure: Data add to Training Set");
}
}
}
//manage the path conditions of EvoSuite seed tests: remove the last clause and rerun the workflow
public static void PCEvosuiteSuccessSeedTest(Collection<Clause> PC) throws IOException {
if(PC!=null) {
Object[] clauseArray = shorten(PC).toArray();
String PathToString = Util.stringifyPathCondition(shorten(PC));
//split pc clauses into array
String[] generalArray = PathToString.split(" && ");
String[] specificArray = PathToString.split(" && ");
//generate general clauses
for (int i=0; i < generalArray.length; i++){
generalArray[i]=generalArray[i].replaceAll("[0-9]", "");
}
//Slicing call
Object[] outputSliced = SlicingManager.Slicing(specificArray, clauseArray, generalArray);
String[] specificArraySliced = (String[]) outputSliced[0];
String[] generalArraySliced = (String[]) outputSliced[1];
BitSet[] bloomFilterStructure = ConvertPCToBloomFilter.bloomFilter(specificArraySliced, generalArraySliced);
//add to trainingSet
Main.trainingSet.add(new StructureLaberPair(bloomFilterStructure, 1));
if (LogManager.generateCSV)
PrintToCSV(PathToString, generalArray, generalArraySliced, specificArray, specificArraySliced, clauseArray, bloomFilterStructure, "1");
//remove the last clause and rerun the workflow
for (int i=specificArray.length - 1; i > 0; i--) {
String[] specificArrayNoLast = new String[i];
Object[] clauseArrayNoLast = new Object[i];
String[] generalArrayNoLast = new String[i];
System.arraycopy(specificArray, 0, specificArrayNoLast, 0, i);
System.arraycopy(clauseArray, 0, clauseArrayNoLast, 0, i);
System.arraycopy(generalArray, 0, generalArrayNoLast, 0, i);
//Slicing call
Object[] outputSlicedNoLast = SlicingManager.Slicing(specificArrayNoLast, clauseArrayNoLast, generalArrayNoLast);
String[] specificArraySlicedNoLast = (String[]) outputSlicedNoLast[0];
String[] generalArraySlicedNoLast = (String[]) outputSlicedNoLast[1];
BitSet[] bloomFilterStructureNoLast = ConvertPCToBloomFilter.bloomFilter(specificArraySlicedNoLast, generalArraySlicedNoLast);
Main.trainingSet.add(new StructureLaberPair(bloomFilterStructureNoLast, 1));
if (LogManager.generateCSV)
PrintToCSV("---", generalArrayNoLast, generalArraySlicedNoLast, specificArrayNoLast, specificArraySlicedNoLast, clauseArrayNoLast, bloomFilterStructureNoLast, "1");
}
}
}
}
|
package com.example.paton.intent1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
/**
* Created by paton on 3/24/2016.
*/
public class Segunda extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.segunda_activity);
Intent intent= getIntent();
Log.d("Segunda", "mensagem anexada a intent " + getIntent().getStringExtra("tag"));
}
}
|
package com.juancrud.evaluacion3.pojo;
public class Foto {
private int imagen;
private int rating;
public Foto(int imagen, int rating) {
setImagen(imagen);
setRating(rating);
}
public int getImagen() {
return imagen;
}
public void setImagen(int imagen) {
this.imagen = imagen;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
|
package com.si.ha.vaadin.security;
import java.util.UUID;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.session.mgt.*;
import com.vaadin.server.VaadinSession;
/**
* A {@link SessionManager} implementation that uses the {@link VaadinSession} for the current user to persist and locate the Shiro {@link Session}. This tightly ties the Shiro security Session
* lifecycle to that of the VaadinSession allowing expiration, persistence, and clustering to be handled only in the Vaadin configuration rather than be duplicated in both the Vaadin and Shiro
* configuration.
*
* @author mpilone
* http://mikepilone.blogspot.hu/2013/07/vaadin-shiro-and-push.html
*
*/
public class VaadinSessionManager implements SessionManager {
/**
* The session attribute name prefix used for storing the Shiro Session in the VaadinSession.
*/
private final static String SESSION_ATTRIBUTE_PREFIX = VaadinSessionManager.class.getName() + ".session.";
/**
* The session factory used to create new sessions. In the future, it may make more sense to simply implement a {@link Session} that is a lightweight wrapper on the {@link VaadinSession} rather
* than storing a {@link SimpleSession} in the {@link VaadinSession}. However by using a SimpleSession, the security information is contained in a neat bucket inside the overall VaadinSession.
*/
private SessionFactory sessionFactory;
/**
* Constructs the VaadinSessionManager.
*/
public VaadinSessionManager() {
sessionFactory = new SimpleSessionFactory();
}
/*
* (non-Javadoc)
*
* @see org.apache.shiro.session.mgt.SessionManager#start(org.apache.shiro.session .mgt.SessionContext)
*/
@Override
public Session start(SessionContext context) {
// Retrieve the VaadinSession for the current user.
VaadinSession vaadinSession = VaadinSession.getCurrent();
// Assuming security is used within a Vaadin application, there should
// always be a VaadinSession available.
if (vaadinSession == null) {
throw new IllegalStateException("Unable to locate VaadinSession " + "to store Shiro Session.");
}
// Create a new security session using the session factory.
SimpleSession shiroSession = (SimpleSession) sessionFactory.createSession(context);
// Assign a unique ID to the session now because this session manager
// doesn't use a SessionDAO for persistence as it delegates to any
// VaadinSession configured persistence.
shiroSession.setId(UUID.randomUUID().toString());
// Put the security session in the VaadinSession. We use the session's ID as
// part of the key just to be safe so we can double check that the security
// session matches when it is requested in getSession.
vaadinSession.setAttribute(SESSION_ATTRIBUTE_PREFIX + shiroSession.getId(), shiroSession);
return shiroSession;
}
/*
* (non-Javadoc)
*
* @see org.apache.shiro.session.mgt.SessionManager#getSession(org.apache.shiro .session.mgt.SessionKey)
*/
@Override
public Session getSession(SessionKey key) throws SessionException {
// Retrieve the VaadinSession for the current user.
VaadinSession vaadinSession = VaadinSession.getCurrent();
String attributeName = SESSION_ATTRIBUTE_PREFIX + key.getSessionId();
if (vaadinSession != null) {
// If we have a valid VaadinSession, try to get the Shiro Session.
SimpleSession shiroSession = (SimpleSession) vaadinSession.getAttribute(attributeName);
if (shiroSession != null) {
// Make sure the Shiro Session hasn't been stopped or expired (i.e. the
// user logged out).
if (shiroSession.isValid()) {
return shiroSession;
} else {
// This is an invalid or expired session so we'll clean it up.
vaadinSession.setAttribute(attributeName, null);
}
}
}
return null;
}
}
|
package org.hogel.android.narouviewer.app.activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.common.base.Optional;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import org.apache.http.Header;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.hogel.android.narouviewer.app.R;
import org.hogel.android.narouviewer.app.util.HtmlCacheStore;
import org.hogel.android.narouviewer.app.view.NarouWebView;
import org.hogel.android.narouviewer.app.webview.NarouUrl;
import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import javax.inject.Inject;
import java.nio.charset.Charset;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BrowserActivity extends RoboActivity {
class NarouViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
currentNarouUrl = NarouUrl.parse(url);
if (!currentNarouUrl.isNarouUrl()) {
startActivity(new Intent(Intent.ACTION_VIEW, currentNarouUrl.getUri()));
return true;
}
if (currentNarouUrl.isNcodeUrl()) {
loadNcodeUrl(url);
return true;
}
return false;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
setProgressBarIndeterminateVisibility(true);
}
@Override
public void onPageFinished(WebView view, String url) {
setProgressBarIndeterminateVisibility(false);
syncCookie();
}
}
@InjectView(R.id.mainWebView)
NarouWebView narouWebView;
@Inject
private HtmlCacheStore htmlCacheStore;
private AsyncHttpClient asyncHttpClient;
private PersistentCookieStore persistentCookieStore;
private NarouUrl currentNarouUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_action_bar_title);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.browser_view);
narouWebView.setWebViewClient(new NarouViewClient());
asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.setUserAgent(narouWebView.getSettings().getUserAgentString());
persistentCookieStore = new PersistentCookieStore(this);
asyncHttpClient.setCookieStore(persistentCookieStore);
Uri data = getIntent().getData();
narouWebView.loadUrl(data.toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.browser_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_top:
goTop();
return true;
case R.id.action_user_home:
goUserHome();
return true;
case R.id.action_ranking:
goRanking();
return true;
case R.id.action_reload:
reload();
return true;
case R.id.action_finish:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void goTop() {
narouWebView.loadUrl(getString(R.string.url_narou_top));
}
private void goUserHome() {
narouWebView.loadUrl(getString(R.string.url_narou_user_home));
}
private void goRanking() {
narouWebView.loadUrl(getString(R.string.url_narou_ranking));
}
private void reload() {
if (currentNarouUrl.isNcodeUrl()) {
loadNcodeUrl(currentNarouUrl.getUrl(), true);
} else {
narouWebView.reload();
}
}
public void loadNcodeUrl(String url) {
loadNcodeUrl(url, false);
}
public void loadNcodeUrl(final String url, boolean isReload) {
setProgressBarIndeterminateVisibility(true);
if (!isReload) {
Optional<String> cache = htmlCacheStore.findCache(url);
if (cache.isPresent()) {
narouWebView.loadDataWithBaseURL(url, cache.get(), "text/html", "utf-8", url);
return;
}
}
asyncHttpClient.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String data = new String(responseBody, Charset.forName("UTF-8"));
narouWebView.loadDataWithBaseURL(url, data, "text/html", "utf-8", url);
htmlCacheStore.addCache(url, data);
prefetchNcodeHtml(data);
}
});
}
private static final Pattern PREFETCH_ANCHOR_PATTERN = Pattern.compile("<a rel=\"(?:prev|next)\" href=\"([^\"]+)\"");
private void prefetchNcodeHtml(String html) {
Matcher matcher = PREFETCH_ANCHOR_PATTERN.matcher(html);
while (matcher.find()) {
MatchResult matchResult = matcher.toMatchResult();
String href = matchResult.group(1);
final String url = "http://ncode.syosetu.com" + href;
if (htmlCacheStore.hasCache(url)) {
continue;
}
asyncHttpClient.get(url, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String data = new String(responseBody, Charset.forName("UTF-8"));
htmlCacheStore.addCache(url, data);
}
});
}
}
private void syncCookie() {
String webviewCookiesValues = CookieManager.getInstance().getCookie(getString(R.string.syostu_cookie_url));
for (String webviewCookieValue : webviewCookiesValues.split("; ")) {
String[] nameAndVal = webviewCookieValue.split("=");
BasicClientCookie cookie = new BasicClientCookie(nameAndVal[0], nameAndVal[1]);
cookie.setDomain(getString(R.string.syostu_cookie_url));
persistentCookieStore.addCookie(cookie);
}
asyncHttpClient.setCookieStore(persistentCookieStore);
}
}
|
package Services;
import Domain.Rental;
/**
* Created by Emma on 8/12/2018.
*/
public interface RentalServices
{
Rental create(Rental rent);
Rental read(long id);
Rental update(Rental rent);
void delete(long id);
Iterable<Rental> readAll();
Iterable<Rental> findAllById(long id);//single search
}
|
/*
* 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 gt.com.atel.assigncar.implementation;
import gt.com.atel.interceptors.Loggable;
/**
*
* @author atel
*/
public interface CarService {
@Loggable
public String assignCarToEmployee();
}
|
package com.example.week3daily3.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import static com.example.week3daily3.database.DBContract.COL_ID;
import static com.example.week3daily3.database.DBContract.COL_IMAGE;
import static com.example.week3daily3.database.DBContract.COL_NAME;
import static com.example.week3daily3.database.DBContract.COL_SOUND;
import static com.example.week3daily3.database.DBContract.COL_TYPE;
import static com.example.week3daily3.database.DBContract.DB_VERSION;
import static com.example.week3daily3.database.DBContract.TABLE_NAME;
import static com.example.week3daily3.database.DBContract.createQuery;
import static com.example.week3daily3.database.DBContract.getWhereClauseById;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(@Nullable Context context) {
super(context, TABLE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createQuery());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
public long insertAnimalToDB(@NonNull Animal animal) {
SQLiteDatabase writableDB = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, animal.getName());
contentValues.put(COL_IMAGE, animal.getImageUrl());
contentValues.put(COL_SOUND, animal.getSound());
contentValues.put(COL_TYPE, animal.getType());
return writableDB.insert(TABLE_NAME, null, contentValues);
}
public Animal getAnimalById(int id) {
SQLiteDatabase readableDB = getReadableDatabase();
Animal animal = new Animal();
Cursor cursor = readableDB.rawQuery(DBContract.getAnimalById(id), null);
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex(COL_NAME));
String img = cursor.getString(cursor.getColumnIndex(COL_IMAGE));
String sound = cursor.getString(cursor.getColumnIndex(COL_SOUND));
String type = cursor.getString(cursor.getColumnIndex(COL_TYPE));
animal = new Animal(id, type, name, sound, img);
}
cursor.close();
return animal;
}
public ArrayList<Animal> getAllAnimalsInDB() {
ArrayList<Animal> animals = new ArrayList<>();
SQLiteDatabase readableDB = getReadableDatabase();
Cursor cursor = readableDB.rawQuery(DBContract.getAllAnimalsQuery(), null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(COL_ID));
String name = cursor.getString(cursor.getColumnIndex(COL_NAME));
String type = cursor.getString(cursor.getColumnIndex(COL_TYPE));
String sound = cursor.getString(cursor.getColumnIndex(COL_SOUND));
String img = cursor.getString(cursor.getColumnIndex(COL_IMAGE));
animals.add(new Animal(id, type, name, sound, img));
} while (cursor.moveToNext());
}
cursor.close();
return animals;
}
//delete entry(ies) from the database
public long deleteFromDatabaseById(int id) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
return sqLiteDatabase.delete(TABLE_NAME, getWhereClauseById() + id, null);
}
}
|
package tests.main_view_partner;
import baseplatformANDROID.BaseTest;
import baseplatform.DataClass;
import objects.android.MainViewDR;
import objects_partner.MainViewPartner;
import org.testng.annotations.*;
import utility.ReusMeth;
import java.io.IOException;
import static org.testng.Assert.assertEquals;
/*
by Sergey
*/
public class SendDemoToAccessory extends BaseTest {
private MainViewPartner mvp;
private MainViewDR mv;
String testName = null;
@BeforeClass
public void setUpLaunching() {
testName = this.getClass().getSimpleName();
mvp = new MainViewPartner(driver);
mv = new MainViewDR(driver);
}
@BeforeMethod
public void onStartingMethodWithinClass() {
driver.launchApp();
}
@AfterMethod
public void onFinishingMethodWithinCLass() {
driver.closeApp();
}
@Test(invocationCount = 3, dataProvider = "FTP_Demo_Provider", dataProviderClass = DataClass.class)
public void verifySendImageToAccessory(String ftpDemo, int pause) throws IOException, InterruptedException {
mvp.inputFieldFTP(ftpDemo);
mvp.demoModeButtonTap();
ReusMeth.waiting(pause);
//TODO Add Assert
}
@AfterClass
public void tearDown() throws InterruptedException {
ReusMeth.waiting(5);
}
}
|
package com.meehoo.biz.core.basic.enumeration;
/**
* 字段类型
* Created by CZ on 2018/1/8.
*/
public enum FieldType {
NUMBER,//编号字段
OPERATOR,//操作员字段
SETBYSYS,//后台赋值字段
COLUMN,// 一般列
FOREIGN,//外键
COLLECTION//集合
}
|
package com.nitnelave.CreeperHeal.block;
import org.bukkit.block.BlockState;
public class CreeperButton extends CreeperBlock
{
protected CreeperButton(BlockState b)
{
super(b);
b.setRawData((byte) (getRawData() & 7));
}
}
|
package com.ws.service;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
/**
* @author shuo.wang
* @date 19-9-17
*/
@Service
public class FileService {
private String uploadDir;
public FileService(){
try {
File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
File upload = new File(rootPath.getAbsolutePath(), "upload");
if (!upload.exists()) {
upload.mkdirs();
}
uploadDir = upload.getAbsolutePath();
}catch (FileNotFoundException e){
uploadDir="/data/upload";
}
}
public void uploadFiles(MultipartFile[] files)throws Exception{
for(MultipartFile file:files){
String fileName= UUID.randomUUID().toString().replace("-","");
File targetFile=new File(uploadDir+File.separator+fileName);
FileOutputStream fileOutputStream=new FileOutputStream(targetFile);
IOUtils.copy(file.getInputStream(),fileOutputStream);
fileOutputStream.close();
}
}
public String uploadFile(MultipartFile file)throws Exception{
String fileName= UUID.randomUUID().toString().replace("-","");
File targetFile=new File(uploadDir+File.separator+fileName);
FileOutputStream fileOutputStream=new FileOutputStream(targetFile);
IOUtils.copy(file.getInputStream(),fileOutputStream);
fileOutputStream.close();
return fileName;
}
public void downloadFile (String fileName, HttpServletRequest request, HttpServletResponse response)throws Exception {
File file=new File(uploadDir,fileName);
if(file.exists()){
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
byte[] buffer=new byte[1024];
FileInputStream in=new FileInputStream(file);
BufferedInputStream bin=new BufferedInputStream(in);
OutputStream out=response.getOutputStream();
int i=bin.read(buffer);
while(i!=-1){
out.write(buffer,0,i);
i=bin.read(buffer);
}
if(bin!=null){
bin.close();
}
if(in!=null){
in.close();
}
}
}
/**
* 支持断点续传
* @param fileName
* @param request
* @param response
*/
public void downloadFile2(String fileName, HttpServletRequest request,HttpServletResponse response)throws Exception{
File targetFile=new File(uploadDir,fileName);
response.setContentType("application/oct-stream");
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
response.setHeader("Accept-Ranges","bytes");
long fileLength=targetFile.length();
long fromPos=0,toPos=0;
int downloadSize;
if(request.getHeader("Range")==null){
response.setContentLengthLong(fileLength);
downloadSize=(int)fileLength;
}else {
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String range = request.getHeader("Range");
String bytes = range.replaceAll("bytes=", "");
String[] arr = bytes.split("-");
if (arr.length == 2) {
toPos = Long.parseLong(arr[1]);
}
if (toPos > fromPos) {
downloadSize = (int)(toPos - fromPos);
} else {
downloadSize =(int) (fileLength - fromPos);
}
response.setContentLengthLong(downloadSize);
}
RandomAccessFile in=new RandomAccessFile(targetFile,"rw");
OutputStream out=response.getOutputStream();
if(fromPos>0)
in.seek(fromPos);
int bufLen=downloadSize< 2048?downloadSize:2048;
byte[] buffer=new byte[bufLen];
int i=in.read(buffer);
int count=0;
while(i!=-1){
out.write(buffer,0,i);
count+=i;
//计算不满缓冲区的大小
if(downloadSize-count<bufLen){
bufLen=downloadSize-count;
if(bufLen==0){
break;
}
buffer=new byte[bufLen];
}
i=in.read(buffer);
}
response.flushBuffer();
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
|
package domain;
public class MainCourse extends Menu{
String mainID;
String foodItem;
public MainCourse(Builder builder) {
}
public MainCourse(String mainID, String foodItem) {
this.mainID = mainID;
this.foodItem = foodItem;
}
public String getMainID() {
return mainID;
}
public void setMainID(String mainID) {
this.mainID = mainID;
}
public String getFoodItem() {
return foodItem;
}
public void setFoodItem(String foodItem) {
this.foodItem = foodItem;
}
public static class Builder{
private String mainID;
private String foodItem;
public Builder(){}
public Builder mainID(String value)
{
this.mainID = value;
return this;
}
public Builder foodItem(String value)
{
this.foodItem = value;
return this;
}
public Builder copy(MainCourse value) {
this.mainID = value.mainID;
this.foodItem = value.foodItem;
return this;
}
public MainCourse build()
{
return new MainCourse(this);
}
}
@Override
public String toString() {
return "MainCourse{" +
"foodItem='" + foodItem + '\'' +
", mainID='" + mainID + '\'' +
'}';
}
}
|
/**
* Copyright (C) 2014-2017 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* 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.helger.commons.error.list;
import java.util.Iterator;
import java.util.function.Predicate;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.ext.CommonsArrayList;
import com.helger.commons.collection.ext.ICommonsList;
import com.helger.commons.error.IError;
import com.helger.commons.hashcode.HashCodeGenerator;
import com.helger.commons.lang.ICloneable;
import com.helger.commons.state.EChange;
import com.helger.commons.string.ToStringGenerator;
/**
* Default implementation of {@link IErrorList}.
*
* @author Philip Helger
* @since 8.5.0
*/
@NotThreadSafe
public class ErrorList implements IErrorList, ICloneable <ErrorList>
{
private final ICommonsList <IError> m_aList;
/**
* Default constructor.
*/
public ErrorList ()
{
m_aList = new CommonsArrayList<> ();
}
/**
* Constructor taking a list of iterable objects.
*
* @param aList
* The list to be added. May be <code>null</code>.
*/
public ErrorList (@Nullable final Iterable <? extends IError> aList)
{
m_aList = aList == null ? new CommonsArrayList<> () : new CommonsArrayList<> (aList);
}
/**
* Constructor taking a list of iterable objects.
*
* @param aList
* The array to be added. May be <code>null</code>.
*/
public ErrorList (@Nullable final IError... aList)
{
m_aList = aList == null ? new CommonsArrayList<> () : new CommonsArrayList<> (aList);
}
/**
* Copy constructor.
*
* @param aErrorList
* The error list to copy from. May be <code>null</code>.
*/
public ErrorList (@Nonnull final ErrorList aErrorList)
{
m_aList = aErrorList == null ? new CommonsArrayList<> () : aErrorList.m_aList.getClone ();
}
public boolean isEmpty ()
{
return m_aList.isEmpty ();
}
@Nonnegative
public int getSize ()
{
return m_aList.size ();
}
@Nonnull
public Iterator <IError> iterator ()
{
return m_aList.iterator ();
}
@Nonnull
@ReturnsMutableCopy
public ICommonsList <IError> getAllItems ()
{
return m_aList.getClone ();
}
@Nonnull
public ErrorList getSubList (@Nullable final Predicate <? super IError> aFilter)
{
if (aFilter == null)
return getClone ();
final ErrorList ret = new ErrorList ();
m_aList.findAll (aFilter, ret.m_aList::add);
return ret;
}
@Nonnull
public ErrorList add (@Nonnull final IError aError)
{
ValueEnforcer.notNull (aError, "Error");
m_aList.add (aError);
return this;
}
public void addAll (@Nullable final Iterable <? extends IError> aErrorList)
{
if (aErrorList != null)
for (final IError aFormError : aErrorList)
add (aFormError);
}
public void addAll (@Nullable final IError... aErrorList)
{
if (aErrorList != null)
for (final IError aFormError : aErrorList)
add (aFormError);
}
@Nonnull
public EChange remove (@Nullable final IError aError)
{
if (aError == null)
return EChange.UNCHANGED;
return m_aList.removeObject (aError);
}
@Nonnull
public EChange removeAll (@Nullable final Iterable <? extends IError> aErrors)
{
EChange ret = EChange.UNCHANGED;
if (aErrors != null)
for (final IError aError : aErrors)
ret = ret.or (remove (aError));
return ret;
}
@Nonnull
public EChange removeAll (@Nullable final IError... aErrors)
{
EChange ret = EChange.UNCHANGED;
if (aErrors != null)
for (final IError aError : aErrors)
ret = ret.or (remove (aError));
return ret;
}
@Nonnull
public EChange removeIf (@Nonnull final Predicate <? super IError> aFilter)
{
return EChange.valueOf (m_aList.removeIf (aFilter));
}
@Nonnull
public EChange clear ()
{
return m_aList.removeAll ();
}
@Nonnull
public ErrorList getClone ()
{
return new ErrorList (this);
}
@Override
public boolean equals (final Object o)
{
if (o == this)
return true;
if (o == null || !getClass ().equals (o.getClass ()))
return false;
final ErrorList rhs = (ErrorList) o;
return m_aList.equals (rhs.m_aList);
}
@Override
public int hashCode ()
{
return new HashCodeGenerator (this).append (m_aList).getHashCode ();
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("List", m_aList).getToString ();
}
}
|
package cs3500.animator.view.panels;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Font;
import javax.swing.JPanel;
import javax.swing.JEditorPane;
import javax.swing.JScrollPane;
import javax.swing.BorderFactory;
import java.util.ArrayList;
/**
* A panel for our visual log, which catalogs actions from the user.
*/
public class LogPanel extends JPanel {
private ArrayList<String> log = new ArrayList<String>();
private JEditorPane textPane = new JEditorPane();
/**
* Constructor for the panel.
*/
public LogPanel() {
textPane.setEditable(false);
JScrollPane paneScrollPane = new JScrollPane(textPane);
paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
paneScrollPane.setPreferredSize(new Dimension(1500, 1000));
textPane.add(paneScrollPane.getVerticalScrollBar());
paneScrollPane.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Action Log"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
this.setBackground(Color.BLACK);
}
/**
* Add a command to the log.
* @param command The command to add
*/
public void addToLog(String command) {
if (log.size() > 6) {
log.remove(0);
}
log.add(command);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.GREEN);
g2d.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
for (int index = 0; index < log.size(); index += 1) {
g2d.drawString(log.get(index), 20, 30 + 30 * index);
}
}
}
|
package com.cs.rest.status;
import com.cs.payment.IncorrectBankAccountException;
/**
* @author Hadi Movaghar
*/
public class IncorrectBankAccountMessage extends ErrorMessage {
private static final long serialVersionUID = 1L;
private static final String INVALID_OR_MISSING_BANK_NAME_OR_BANK_LOCATION_ERROR = "142";
private static final String INVALID_IBAN_ERROR = "161";
private static final String INCONSISTENT_IBAN_ERROR = "162";
private static final String INVALID_BIC_ERROR = "163";
protected IncorrectBankAccountMessage(final StatusCode statusCode, final String message) {
super(statusCode, message);
}
public static IncorrectBankAccountMessage of(final IncorrectBankAccountException exception) {
return new IncorrectBankAccountMessage(extractStatusCodeFromExceptionMessage(exception.getMessage()), exception.getMessage());
}
private static StatusCode extractStatusCodeFromExceptionMessage(final String message) {
if (message.contains(INVALID_OR_MISSING_BANK_NAME_OR_BANK_LOCATION_ERROR)) {
return StatusCode.INVALID_OR_MISSING_BANK_NAME_OR_BANK_LOCATION;
} else if (message.contains(INVALID_IBAN_ERROR)) {
return StatusCode.INVALID_IBAN;
} else if (message.contains(INCONSISTENT_IBAN_ERROR)) {
return StatusCode.INCONSISTENT_IBAN;
} else if (message.contains(INVALID_BIC_ERROR)) {
return StatusCode.INVALID_BIC;
} else {
return StatusCode.INCORRECT_BANK_ACCOUNT;
}
}
}
|
package com.leetcode;
/**
* Definition for a binary tree node.
**
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class MaxDepth {
private int res = 0;
public int maxDepth(TreeNode root) {
depthIterator(root,0);
return res;
}
public void depthIterator(TreeNode node,int counter){
if(node!=null){
depthIterator(node.left,counter+1);
depthIterator(node.right,counter+1);
}else{
if(res<counter){
res = counter;
}
}
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
TreeNode node = new TreeNode(20);
root.right = node;
node.left = new TreeNode(15);
node.right = new TreeNode(7);
MaxDepth depth = new MaxDepth();
int res = depth.maxDepth(root);
System.out.println(res);
}
}
|
package OnlinemusicstoreClasses;
import javafx.collections.ObservableList;
import java.util.HashMap;
//This class exists just to send a playlistobject from one scene to another
public class PlaylistSingleton {
//private ObservableList<Song> songs = FXCollections.observableArrayList();
private HashMap<Integer,ObservableList<Song>> playlist = new HashMap<>();
private static int playlistNum = 0;
private static PlaylistSingleton ourInstance = new PlaylistSingleton();
public static PlaylistSingleton getInstance() {
return ourInstance;
}
private PlaylistSingleton() {
}
public HashMap<Integer,ObservableList<Song>> getPlaylist() {
return playlist;
}
public void setPlaylist(ObservableList<Song> songs) {
playlist.put(playlistNum, songs);
playlistNum++;
}
}
|
package net.anatolich.db;
import com.github.springtestdbunit.bean.DatabaseConfigBean;
import com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* Configures custom property for datasource to be used in tests.
*/
@Configuration
public class CustomDataSourceConfiguration {
@Bean
public DatabaseConfigBean dbUnitDatabaseConfig() {
final DatabaseConfigBean config = new DatabaseConfigBean();
config.setAllowEmptyFields(true);
return config;
}
/**
* Create datasource factory. It is very important for this bean to have id
* equal to <code>dbUnitDatabaseConnection</code>
* @see com.github.springtestdbunit.DbUnitTestExecutionListener for details
* @param dataSource
* @return
*/
@Bean
public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection(DataSource dataSource) {
final DatabaseDataSourceConnectionFactoryBean dataSourceFactoryBean = new DatabaseDataSourceConnectionFactoryBean(dataSource);
dataSourceFactoryBean.setDatabaseConfig(dbUnitDatabaseConfig());
return dataSourceFactoryBean;
}
}
|
package pl.basistma.receiver;
import javax.enterprise.inject.Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@Model
public class Users implements Serializable {
private List<User> users = new ArrayList<>();
public void add(User user) {
users.add(user);
}
public List<User> getAll() {
return users;
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
/*
* ID: nareddyt
* LANG: JAVA
* TASK: baseball
*/
public class baseball
{
public static void main(String[] args) throws IOException
{
BufferedReader f = new BufferedReader(new FileReader("baseball.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("baseball.out")));
StringTokenizer st = new StringTokenizer(f.readLine());
int n = Integer.parseInt(st.nextToken());
int[] positions = new int[n];
for (int i = 0; i < n; i++)
{
st = new StringTokenizer(f.readLine());
positions[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(positions);
int count = 0;
for (int a = 0; a < n; a++)
{
for (int b = a + 1; b < n; b++)
{
for (int c = b + 1; c < n; c++)
{
int bc = positions[c] - positions[b];
int ab = positions[b] - positions[a];
if (bc >= ab && bc <= 2 * ab)
{
count++;
}
}
}
}
out.println(count);
f.close();
out.close();
System.exit(0);
}
}
|
package com.ayadykin.message.system.services;
import java.util.Map;
import com.ayadykin.message.system.dto.MessageDto;
import com.ayadykin.message.system.model.User;
public interface MessageService {
public Map<String, User> getMessages();
public boolean createMesage(MessageDto message);
public boolean updateMesage(MessageDto message);
public boolean deleteMesage(MessageDto message);
}
|
package Problem_1992;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N;
static int[][] arr;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
N = Integer.parseInt(str);
arr = new int[N][N];
for(int i = 0; i<N; i++) {
str = br.readLine();
for(int j = 0; j<N;j++) {
arr[i][j] = str.charAt(j)-'0';
}
}
System.out.println(getTree(0, 0, N));
}
static String getTree(int starti, int startj, int size) {
String data = "";
int d = arr[starti][startj];
boolean flag = true;
for(int i = starti; i<starti+size;i++) {
for(int j = startj; j<startj+size;j++) {
if(arr[i][j] != d) {
flag = false;
break;
}
}
}
if(flag) {
return String.valueOf(d);
}
else {
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(getTree(starti, startj, size/2));
sb.append(getTree(starti, startj + size/2, size/2));
sb.append(getTree(starti + size/2, startj, size/2));
sb.append(getTree(starti+size/2, startj + size/2, size/2));
sb.append(")");
return sb.toString();
}
}
}
|
// import java.io.*;
// import java.util.*;
// class Node implements Comparable<Node> {
// int x1;
// int x2;
// int idx;
// Node(int idx, int x1, int x2) {
// this.idx = idx;
// this.x1 = x1;
// this.x2 = x2;
// }
// public int compareTo(Node that) {
// if (this.x1 < that.x1) {
// return -1;
// } else if (this.x1 == that.x1) {
// return 0;
// }
// return 1;
// }
// }
// class baek__17619 {
// static int find(int a, int[] parent) {
// return a == parent[a] ? a : (parent[a] = find(parent[a], parent));
// }
// static void union(int a, int b, int[] parent, int[] size) {
// int r1 = find(a, parent);
// int r2 = find(b, parent);
// if (size[r1] > size[r2]) {
// int temp = r1;
// r1 = r2;
// r2 = temp;
// }
// parent[r1] = r2;
// size[r2] += size[r1];
// }
// public static void main(String[] args) throws IOException {
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// String[] temp = br.readLine().split(" ");
// int n = Integer.parseInt(temp[0]);
// int[] parent = new int[n + 1];
// int[] size = new int[n + 1];
// Node[] nodes = new Node[n + 1];
// for (int i = 1; i <= n; i++) {
// parent[i] = i;
// size[i] = 1;
// }
// int q = Integer.parseInt(temp[1]);
// nodes[0] = new Node(-1, -1, -1);
// for (int i = 1; i <= n; i++) {
// temp = br.readLine().split(" ");
// nodes[i] = new Node(i, Integer.parseInt(temp[0]), Integer.parseInt(temp[1]));
// }
// Arrays.sort(nodes);
// for (int i = 1; i <= n; i++) {
// for (int j = i + 1; j <= n; j++) {
// if (nodes[i].x2 >= nodes[j].x1) {
// union(nodes[i].idx, nodes[j].idx, parent, size);
// } else {
// break;
// }
// }
// }
// StringBuilder sb = new StringBuilder();
// while (q-- > 0) {
// temp = br.readLine().split(" ");
// int u = Integer.parseInt(temp[0]);
// int v = Integer.parseInt(temp[1]);
// int r1 = find(u, parent);
// int r2 = find(v, parent);
// if (r1 == r2) {
// sb.append(1 + "\n");
// } else {
// sb.append(0 + "\n");
// }
// }
// System.out.print(sb);
// }
// }
|
package nl.guuslieben.circle.views.main;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.littemplate.LitTemplate;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.template.Id;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import lombok.Setter;
import nl.guuslieben.circle.ClientService;
import nl.guuslieben.circle.ServerResponse;
import nl.guuslieben.circle.common.UserData;
import nl.guuslieben.circle.common.rest.LoginRequest;
import nl.guuslieben.circle.common.util.CertificateUtilities;
import nl.guuslieben.circle.common.util.KeyUtilities;
import nl.guuslieben.circle.common.util.PasswordUtilities;
import nl.guuslieben.circle.views.MainLayout;
@Route(value = "login", layout = MainLayout.class)
@RouteAlias(value = "login", layout = MainLayout.class)
@PageTitle("The Circle - Login")
@Tag("login-view")
@JsModule("./views/login-view.ts")
public class LoginView extends LitTemplate {
private final transient ClientService service;
@Setter
private transient Consumer<UserData> afterLogin = ud -> {};
@Id
private TextField email;
@Id
private PasswordField password;
@Id
private Button login;
public LoginView(ClientService service) {
this.service = service;
this.email.addValueChangeListener(event -> this.onValidate());
this.password.addValueChangeListener(event -> this.onValidate());
this.onValidate();
this.login.addClickListener(this::onLogin);
}
public void onValidate() {
boolean enabled = !(this.email.getValue().isEmpty() || this.password.getValue().isEmpty());
this.login.setEnabled(enabled);
}
public void onLogin(ClickEvent<Button> event) {
final String password = this.password.getValue();
final String username = this.email.getValue();
final Optional<X509Certificate> x509Certificate = CertificateUtilities.get(username);
if (x509Certificate.isEmpty()) {
Notification.show("Could not verify account");
return;
}
final X509Certificate certificate = x509Certificate.get();
final PublicKey publicKey = certificate.getPublicKey();
final Optional<PrivateKey> privateKey = this.getPrivateKey(username, password, publicKey);
if (privateKey.isEmpty()) {
Notification.show("Could not verify account");
return;
}
KeyPair pair = new KeyPair(publicKey, privateKey.get());
this.service.setPair(pair);
final LoginRequest request = new LoginRequest(username, PasswordUtilities.encrypt(password, password, publicKey));
final ServerResponse<UserData> response = this.service.login(request);
if (response.accepted()) {
Notification.show("Welcome, " + response.getObject().getName());
this.afterLogin.accept(response.getObject());
} else {
Notification.show(response.getMessage());
}
}
private Optional<PrivateKey> getPrivateKey(String email, String password, Key publicKey) {
File keys = new File("store/keys");
final File file = new File(keys, email + ".pfx");
if (!file.exists()) return Optional.empty();
try {
final List<String> lines = Files.readAllLines(file.toPath());
final String encodedKey = lines.get(0);
final String decrypted = PasswordUtilities.decrypt(encodedKey, password, publicKey);
if (decrypted == null) return Optional.empty();
return KeyUtilities.decodeBase64ToPrivate(decrypted);
}
catch (IOException e) {
return Optional.empty();
}
}
}
|
package be.odisee.pajotter.domain;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@DiscriminatorValue("Bestelling")
public class Bestelling extends Bericht implements Serializable{
public Bestelling(){}
@Column
//@NotEmpty(message="Vul een aantal in AUB")
private int aantal;
@Column
//@NotEmpty(message = "Vul Leverancier in aub")
private int LeverancierId;
public Bestelling(int id, String status, Partij partij, String tekst, int aantal) throws Exception {
super(id, status, partij, tekst);
this.aantal = aantal;
// if (reactieOp == null) throw new Exception("FOUT");
// this.reactieOp = reactieOp;
}
public Bestelling(String status, Partij partij, String tekst, int aantal, int LeverancierId) throws Exception {
super(status, partij, tekst);
this.aantal = aantal;
this.LeverancierId=LeverancierId;
// if (reactieOp == null) throw new Exception("FOUT");
// this.reactieOp = reactieOp;
}
public Bestelling(String status, Partij partij, String tekst) throws Exception {
super(status, partij, tekst);
}
public Bericht getReactieOp(){
return reactieOp;
}
public void setReactieOp(Bericht newVal){
reactieOp = newVal;
}
public int getAantal() {
return aantal;
}
public void setAantal(int aantal) {
this.aantal = aantal;
}
public int getLeverancierId() {
return LeverancierId;
}
public void setLeverancierId(int leverancierId) {
LeverancierId = leverancierId;
}
}
|
package com.example.mike.testinstagramlogin;
import android.content.Intent;
import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import java.io.IOException;
import java.net.URISyntaxException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
}
public void authorizeLogin(View view) throws ParserConfigurationException, SAXException, IOException, URISyntaxException {
startActivity(new Intent("android.intent.action.VIEW", Uri.parse(createAuthURL())));
}
private String createAuthURL() throws ParserConfigurationException, SAXException, IOException {
String authenticationURI = AuthConfiguration.getInstance(this).getAuthenticationURI();
String clientID = AuthConfiguration.getInstance(this).getClientID();
String redirectURI = AuthConfiguration.getInstance(this).getRedirectURI();
String responseType = AuthConfiguration.getInstance(this).getResponseType();
Builder buildUpon = Uri.parse(authenticationURI).buildUpon();
buildUpon.appendQueryParameter("client_id", clientID);
buildUpon.appendQueryParameter("redirect_uri", redirectURI);
buildUpon.appendQueryParameter("response_type", responseType);
buildUpon.appendQueryParameter("scope", "follower_list");
return buildUpon.build().toString();
}
}
|
package com.codingchili.authentication.model;
import com.codingchili.core.security.Account;
import com.codingchili.core.storage.Storable;
/**
* @author Robin Duda
* Database mapping not shared outside storage.
*/
public class AccountMapping implements Storable {
private String username;
private String email;
private String hash;
public AccountMapping() {
}
public AccountMapping(Account account) {
this.username = account.getUsername();
this.email = account.getEmail();
}
public String getUsername() {
return username;
}
public AccountMapping setUsername(String username) {
this.username = username;
return this;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getEmail() {
return email;
}
public AccountMapping setEmail(String email) {
this.email = email;
return this;
}
@Override
public String getId() {
return username;
}
@Override
public int hashCode() {
return username.hashCode();
}
@Override
public boolean equals(Object other) {
return compareTo(other) == 0;
}
}
|
package servicenow.api;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
public class RestTableReaderTest {
Logger logger = LoggerFactory.getLogger(this.getClass());
static Session session;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
session = TestingManager.getSession();
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testSetQuery() throws Exception {
String someDeptName = TestingManager.getProperty("some_department_name");
boolean found = true;
Table dept = session.table("cmn_department");
RecordListAccumulator accumulator = new RecordListAccumulator(dept);
TableReader reader = dept.rest().getDefaultReader();
reader.setWriter(accumulator);
reader.call();
for (Record rec : accumulator.getRecords()) {
String deptName = rec.getValue("name");
String deptHead = rec.getValue("dept_head");
logger.debug(deptName + "|" + deptHead);;
if (someDeptName.equals(deptName)) found = true;
}
if (!found) fail("Expected department not found");
}
@Test
public void testSetDisplayValuesTrue() throws Exception {
String someDeptName = TestingManager.getProperty("some_department_name");
String someDeptHead = TestingManager.getProperty("some_department_head");
Table dept = session.table("cmn_department");
RecordListAccumulator accumulator = new RecordListAccumulator(dept);
TableReader reader = dept.rest().getDefaultReader();
reader.setWriter(accumulator);
reader.setDisplayValue(true);
reader.call();
for (Record rec : accumulator.getRecords()) {
String deptName = rec.getValue("name");
String deptHead = rec.getDisplayValue("dept_head");
logger.debug(deptName + "|" + deptHead);;
if (someDeptName.equals(deptName)) {
if (!someDeptHead.equals(deptHead))
fail("Department head name not found");
}
}
}
@Test
public void testSetDisplayValuesFalse() throws Exception {
Table dept = session.table("cmn_department");
RecordListAccumulator accumulator = new RecordListAccumulator(dept);
TableReader reader = dept.rest().getDefaultReader();
reader.setWriter(accumulator);
reader.setDisplayValue(false);
reader.call();
for (Record rec : accumulator.getRecords()) {
String deptName = rec.getValue("name");
String deptHead = rec.getDisplayValue("dept_head");
logger.debug(deptName + "|" + deptHead);
if (deptHead != null) fail("Department head should be null");
}
}
@Test @Ignore
public void testSetColumns() {
fail("Not yet implemented");
}
}
|
package at.fhv.itm14.fhvgis.analysis.classification;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import javax.naming.ConfigurationException;
import at.fhv.itm14.fhvgis.analysis.config.Config;
import at.fhv.itm14.fhvgis.analysis.config.model.ClassifierConfig;
import at.fhv.itm14.fhvgis.analysis.model.ClassificationResult;
import weka.attributeSelection.CfsSubsetEval;
import weka.attributeSelection.GreedyStepwise;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.BayesNet;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.functions.MultilayerPerceptron;
import weka.classifiers.meta.AttributeSelectedClassifier;
import weka.classifiers.rules.DecisionTable;
import weka.classifiers.rules.PART;
import weka.classifiers.trees.DecisionStump;
import weka.classifiers.trees.J48;
import weka.classifiers.trees.RandomForest;
import weka.core.FastVector;
import weka.core.Instance;
import weka.core.Instances;
/**
* Holds an array of all classifiers according to Config.xml Responsible for
* building the classifiers with the given training data. Responsible for the
* classification process of test data. Responsible for validation of the
* trained classifiers (with cross validation).
*
*/
class Classification {
private Controller controller;
private Classifier[] classifiers;
private Map<String, Classifier> classifierMap;
Classification(Controller controller) throws ConfigurationException {
this.controller = controller;
init(controller.getConfig());
}
private void init(Config config) throws ConfigurationException {
classifierMap = new HashMap<>();
for (ClassifierConfig c : config.getClassifierConfigs()) {
if (c.isEnabled()) {
switch (c.getName()) {
case "J48":
classifierMap.put("J48", new J48());
break;
case "PART":
classifierMap.put("PART", new PART());
break;
case "DecisionTable":
classifierMap.put("DecisionTable", new DecisionTable());
break;
case "DecisionStump":
classifierMap.put("DecisionStump", new DecisionStump());
break;
case "RandomForest":
classifierMap.put("RandomForest", new RandomForest());
break;
case "NaiveBayes":
classifierMap.put("NaiveBayes", new NaiveBayes());
break;
case "BayesNet":
classifierMap.put("BayesNet", new BayesNet());
break;
case "MultilayerPerceptron":
MultilayerPerceptron mlp = new MultilayerPerceptron();
// TODO configuration?!
// Setting Parameters
mlp.setLearningRate(0.1);
mlp.setMomentum(0.2);
mlp.setTrainingTime(2000);
// creates a 'nrOfInputs-5-nrOfOutputs' NN
mlp.setHiddenLayers("5");
// use it like this: to create a
// 'nrOfInputs-8-6-4-nrOfOutputs' NN
// mlp.setHiddenLayers("8, 6, 4");
classifierMap.put("MultilayerPerceptron", mlp);
break;
default:
throw new ConfigurationException();
}
}
}
classifiers = new Classifier[classifierMap.values().size()];
classifiers = classifierMap.values().toArray(classifiers);
}
void buildAllClassifiers(Instances trainingData) throws Exception {
Classifier[] classifiers = controller.getClassifiers();
for (int j = 0; j < classifiers.length; j++) {
classifiers[j].buildClassifier(trainingData);
}
}
/**
* Runs through all classifiers specified within the Config.xml and
* evaluates the given instance. It returns the most prevalent
* transportation mode as an integer (the mode that occurs most). The
* buildAllClassifiers() method must be called before (at least once).
*
* @param instance
* @return
* @throws Exception
*/
ClassificationResult classifyInstance(Instance instance) throws Exception {
Classifier classifier;
ClassificationResult result = new ClassificationResult();
// attribute selection classifier
AttributeSelectedClassifier attrSelClassifier = null;
attrSelClassifier = new AttributeSelectedClassifier();
CfsSubsetEval attrSelectionEval = new CfsSubsetEval();
GreedyStepwise search = new GreedyStepwise();
search.setSearchBackwards(true);
attrSelClassifier.setEvaluator(attrSelectionEval);
attrSelClassifier.setSearch(search);
for (Entry<String, Classifier> e : classifierMap.entrySet()) {
if (Config.getInstance().isFeatureSelectionEnabled(e.getKey())) {
attrSelClassifier.setClassifier(e.getValue());
classifier = attrSelClassifier;
} else {
classifier = e.getValue();
}
Evaluation eval = new Evaluation(controller.getTrainingSet());
double prediction = eval.evaluateModelOnce(classifier, instance);
// This returns the predicted probability distribution over the
// labels
// double[] preds = classifier.distributionForInstance(instance);
result.addResult(e.getKey(), prediction);
}
// TODO weighted classifiers...
// TODO POI plausibility control...
// TODO could be that two or more modes are equally frequent
return result;
}
/**
* Runs through all specified (in Config.xml) classifiers and evaluates the
* given test data. The buildAllClassifiers() method must be called before
* (at least once). Assumes labeled test data.
*
* @param testData
* the test data
* @param trainingData
* necessary due to definition/structure of data
* @param useAttributeSelection
* If true -> attribute selection is applied
* @return TODO
* @throws Exception
*/
String classify(Instances testData, Instances trainingData, boolean useAttributeSelection) throws Exception {
Classifier[] classifiers = controller.getClassifiers();
Classifier classifier;
// attribute selection classifier
AttributeSelectedClassifier attrSelClassifier = null;
if (useAttributeSelection) {
attrSelClassifier = new AttributeSelectedClassifier();
CfsSubsetEval eval = new CfsSubsetEval();
GreedyStepwise search = new GreedyStepwise();
search.setSearchBackwards(true);
attrSelClassifier.setEvaluator(eval);
attrSelClassifier.setSearch(search);
}
for (int j = 0; j < classifiers.length; j++) {
if (useAttributeSelection && attrSelClassifier != null) {
attrSelClassifier.setClassifier(classifiers[j]);
classifier = attrSelClassifier;
} else {
classifier = classifiers[j];
}
Evaluation eval = new Evaluation(trainingData);
eval.evaluateModel(classifier, testData);
System.out.println(eval.toSummaryString());
}
// TODO return type
return null;
}
/**
* Runs through all specified (in Config.xml) classifiers and labels the
* given test data. The buildAllClassifiers() method must be called before
* (at least once). Assumes unlabeled test data. TODO test - code refactor
* (uses same blocks as classify)
*
* @param testData
* @param trainingData
* @param useAttributeSelection
* @return
* @throws Exception
*/
String classifyUnlabled(Instances testData, Instances trainingData, boolean useAttributeSelection)
throws Exception {
Classifier[] classifiers = controller.getClassifiers();
Classifier classifier;
// attribute selection classifier
AttributeSelectedClassifier attrSelClassifier = null;
if (useAttributeSelection) {
attrSelClassifier = new AttributeSelectedClassifier();
CfsSubsetEval eval = new CfsSubsetEval();
GreedyStepwise search = new GreedyStepwise();
search.setSearchBackwards(true);
attrSelClassifier.setEvaluator(eval);
attrSelClassifier.setSearch(search);
}
Instances labeled = new Instances(testData);
for (int j = 0; j < classifiers.length; j++) {
if (useAttributeSelection && attrSelClassifier != null) {
attrSelClassifier.setClassifier(classifiers[j]);
classifier = attrSelClassifier;
} else {
classifier = classifiers[j];
}
for (int i = 0; i < testData.numInstances(); i++) {
double clsLabel = classifier.classifyInstance(testData.instance(i));
labeled.instance(i).setClassValue(clsLabel);
}
System.out.println(labeled.toSummaryString());
}
// TODO return type
return null;
}
// for testing, evaluation
String runCrossValidation(int nrOfFolds, boolean useAttributeSelection) throws Exception {
Instances data = controller.getTrainingSet();
Classifier[] classifiers = controller.getClassifiers();
Classifier classifier;
// attribute selection classifier
AttributeSelectedClassifier attrSelClassifier = null;
StringBuilder result = new StringBuilder(
"\n\n############### Test runCrossValidation START ###############\n\n");
if (useAttributeSelection) {
attrSelClassifier = new AttributeSelectedClassifier();
CfsSubsetEval eval = new CfsSubsetEval();
GreedyStepwise search = new GreedyStepwise();
search.setSearchBackwards(true);
attrSelClassifier.setEvaluator(eval);
attrSelClassifier.setSearch(search);
}
for (int j = 0; j < classifiers.length; j++) {
if (useAttributeSelection && attrSelClassifier != null) {
attrSelClassifier.setClassifier(classifiers[j]);
classifier = attrSelClassifier;
} else {
classifier = classifiers[j];
}
/**
* Note: The classifier (in our example tree) should not be trained
* when handed over to the crossValidateModel method. Why? If the
* classifier does not abide to the Weka convention that a
* classifier must be re-initialized every time the buildClassifier
* method is called (in other words: subsequent calls to the
* buildClassifier method always return the same results), you will
* get inconsistent and worthless results. The crossValidateModel
* takes care of training and evaluating the classifier. (It creates
* a copy of the original classifier that you hand over to the
* crossValidateModel for each run of the cross-validation.)
*/
Evaluation eval = new Evaluation(data);
eval.crossValidateModel(classifier, data, nrOfFolds, new Random(1));
String classifierResult = eval.toSummaryString("Classifier: " + classifiers[j].getClass().getSimpleName(),
true);
result.append("Date ").append(new Date().toString()).append("\n");
result.append(classifierResult);
result.append("\n-------------------------------\n\n");
}
result.append("\n############### Test runCrossValidation END ###############\n");
return result.toString();
}
// for testing, evaluation
String evaluateAllClassifiers(Instances testData, boolean useAttributeSelection) throws Exception {
Instances trainingData = controller.getTrainingSet();
Classifier[] classifiers = controller.getClassifiers();
Classifier classifier;
// attribute selection classifier
AttributeSelectedClassifier attrSelClassifier = null;
StringBuilder result = new StringBuilder(
"\n\n############### Test runClassification START ###############\n\n");
if (useAttributeSelection) {
attrSelClassifier = new AttributeSelectedClassifier();
CfsSubsetEval eval = new CfsSubsetEval();
GreedyStepwise search = new GreedyStepwise();
search.setSearchBackwards(true);
attrSelClassifier.setEvaluator(eval);
attrSelClassifier.setSearch(search);
}
for (int j = 0; j < classifiers.length; j++) {
if (useAttributeSelection && attrSelClassifier != null) {
attrSelClassifier.setClassifier(classifiers[j]);
classifier = attrSelClassifier;
} else {
classifier = classifiers[j];
}
classifier.buildClassifier(trainingData);
Evaluation eval = new Evaluation(trainingData);
eval.evaluateModel(classifier, testData);
String classifierResult = eval.toSummaryString("Classifier: " + classifiers[j].getClass().getSimpleName(),
true);
result.append("Date ").append(new Date().toString()).append("\n");
result.append(classifierResult);
result.append("\n-------------------------------\n\n");
}
result.append("\n############### Test runClassification END ###############\n");
return result.toString();
}
@Deprecated
// for testing, evaluation
private Evaluation classify(Classifier model, Instances trainingSet, Instances testingSet) throws Exception {
Evaluation evaluation = new Evaluation(trainingSet);
model.buildClassifier(trainingSet);
evaluation.evaluateModel(model, testingSet);
return evaluation;
}
@Deprecated
// for testing, evaluation
String runCustomCrossValidation(int nrOfFolds) throws Exception {
Instances data = controller.getTrainingSet();
Instances[][] split = Validation.createCrossValidationSplit(data, 10);
// Separate split into training and testing arrays
Instances[] trainingSplits = split[Validation.TRAINING_POS];
Instances[] testingSplits = split[Validation.TESTING_POS];
Classifier[] classifiers = controller.getClassifiers();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < classifiers.length; j++) {
// Collect every group of predictions for current model in a
// FastVector
FastVector predictions = new FastVector();
// For each training-testing split pair, train and test the
// classifier
for (int i = 0; i < trainingSplits.length; i++) {
Evaluation validation = classify(classifiers[j], trainingSplits[i], testingSplits[i]);
predictions.appendElements(validation.predictions());
}
// Calculate overall accuracy of current classifier on all splits
double accuracy = Validation.calculateAccuracy(predictions);
sb.append("Accuracy of " + classifiers[j].getClass().getSimpleName() + ": "
+ String.format("%.2f%%", accuracy) + "\n---------------------------------\n");
}
return sb.toString();
}
Classifier[] getClassifiers() {
return classifiers;
}
Classifier getClassifierByName() throws Exception {
// TODO
throw new Exception("not implemented");
}
}
|
package com.training.apps;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.training.beans.AppContext;
import com.training.beans.Teacher;
public class JavaConfigApplication {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
BeanFactory ctx=new AnnotationConfigApplicationContext(AppContext.class);
Teacher teacher=ctx.getBean("teacher",Teacher.class);
System.out.println(teacher);
teacher=ctx.getBean("getTeacher",Teacher.class);
System.out.println(teacher);
} catch (Exception e) {
// TODO: handle exception
}
}
}
|
package com.whl.datafiles.web.wxpay;
import com.whl.datafiles.config.WxpayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@EnableAutoConfiguration
@RequestMapping("/wxpay")
public class WxpayController {
@Autowired
private WxpayConfig wxpayConfig;
@RequestMapping("/index.html")
public String index(){
return "wxpay/index";
}
}
|
package com.explore.service;
import com.explore.common.ServerResponse;
import com.explore.pojo.Staff;
public interface IStaffService {
ServerResponse findAll();
ServerResponse findById(Integer id);
ServerResponse deleteById(Integer id);
ServerResponse save(Staff staff);
ServerResponse modify(Staff staff);
Integer allCount();
}
|
package com.beike.interceptors;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.beike.service.log.BeikeLogService;
import com.beike.util.DateUtils;
import com.beike.util.WebUtils;
/**
* <p>
* Title:超级拦截器
* </p>
* <p>
* Description:
* </p>
* <p>
* Copyright: Copyright (c) 2011
* </p>
* <p>
* Company: Sinobo
* </p>
*
* @date Apr 27, 2011
* @author ye.tian
* @version 1.0
*/
public abstract class BaseBeikeInterceptor extends HandlerInterceptorAdapter {
private final Log log = LogFactory.getLog(BaseBeikeInterceptor.class);
private List<String> path;
private BeikeLogService beikeLogService;
private Date beginDate;
private Date endDate;
private static final ThreadLocal<Map<String, String>> _config = new ThreadLocal<Map<String, String>>();
public BeikeLogService getBeikeLogService() {
return beikeLogService;
}
public void setBeikeLogService(BeikeLogService beikeLogService) {
this.beikeLogService = beikeLogService;
}
abstract protected Serializable createLog(Map<String, String> map,
HttpServletRequest request);
// 报文拼装日志
protected String paramdata(Map<String, String> map) {
StringBuilder sb = new StringBuilder();
Set<String> set = map.keySet();
for (String string : set) {
sb.append(string);
sb.append(":");
sb.append(map.get(string));
sb.append(",");
}
String returnString = "";
if (map != null && map.size() > 0) {
returnString = sb.substring(0, sb.lastIndexOf(","));
}
return returnString;
}
// 是否为我们过滤的路径
private boolean filterPath(HttpServletRequest request) {
boolean flag = false;
String requesturi = request.getRequestURI();
for (String listpath : path) {
if (requesturi.indexOf(listpath) != -1) {
flag = true;
log.debug("拦截器过滤:" + listpath);
break;
}
}
return flag;
}
private void paramLogs(HttpServletRequest request) {
Map map = request.getParameterMap();
Set set = map.keySet();
for (Object object : set) {
Object value = map.get(object);
log.debug("参数:" + object.toString());
String[] values = (String[]) value;
// log.info(request.getRequestURI()+"-->参数列表:"+object.toString()+":"+value);
for (String s : values) {
log.debug("参数值:" + s);
}
}
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
// 判断是否我们过滤的路径
boolean flag = filterPath(request);
// 假如需要过滤的
if (flag) {
// 打印参数
paramLogs(request);
// 访问者IP地址
String ipAddr = WebUtils.getIpAddr(request);
// 访问路径
String reuqestUrl = request.getRequestURI().toString();
// TODO:需要判断是否需要日志策略,是记录到数据库里,还是正常打日志文件
// 组装基本日志参数
addConfig("ipAddr", ipAddr);
addConfig("reuqestUrl", reuqestUrl);
// TODO:放置访问参数
// _config.get().putAll();
beginDate = new Date();
addConfig("beginDate", DateUtils.dateToStr(beginDate));
return true;
}
return false;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
boolean flag = filterPath(request);
if (flag) {
// 方法执行结束时间
endDate = new Date();
// action执行相隔时间
// addConfig("disTime", DateUtils.disTime(beginDate, endDate));
// 组装额外的参数
}
Serializable logObj = createLog(getLogConfig(), request);
// 相应的日志service去执行记录日志
if (beikeLogService != null) {
beikeLogService.processLog(logObj);
}
if (ex != null) {
// 异常信息记录日志
// log.info(ex);
// String extmsg=BaseException.getErrorMessage(ex);
// addConfig("errMsg", extmsg);
// Serializable logErrObj=createLog(getLogConfig(),request);
// 相应的日志service去执行记录日志 记录错误信息
// beikeLogService.processLog(logErrObj);
}
}
private void addConfig(String key, String value) {
getLogConfig().put(key, value);
}
private Map<String, String> getLogConfig() {
Map<String, String> map = _config.get();
if (map == null) {
map = new HashMap<String, String>();
_config.set(map);
}
return map;
}
public List<String> getPath() {
return path;
}
public void setPath(List<String> path) {
this.path = path;
}
}
|
package com.example.fileshare.exception;
public class OrderNotFoundException extends Throwable {
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.reactive.result.view;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link DefaultRenderingBuilder}.
*
* @author Rossen Stoyanchev
*/
public class DefaultRenderingBuilderTests {
@Test
public void defaultValues() {
Rendering rendering = Rendering.view("abc").build();
assertThat(rendering.view()).isEqualTo("abc");
assertThat(rendering.modelAttributes()).isEqualTo(Collections.emptyMap());
assertThat(rendering.status()).isNull();
assertThat(rendering.headers()).isEmpty();
}
@Test
public void defaultValuesForRedirect() throws Exception {
Rendering rendering = Rendering.redirectTo("abc").build();
Object view = rendering.view();
assertThat(view.getClass()).isEqualTo(RedirectView.class);
assertThat(((RedirectView) view).getUrl()).isEqualTo("abc");
assertThat(((RedirectView) view).isContextRelative()).isTrue();
assertThat(((RedirectView) view).isPropagateQuery()).isFalse();
}
@Test
public void viewName() {
Rendering rendering = Rendering.view("foo").build();
assertThat(rendering.view()).isEqualTo("foo");
}
@Test
public void modelAttribute() throws Exception {
Foo foo = new Foo();
Rendering rendering = Rendering.view("foo").modelAttribute(foo).build();
assertThat(rendering.modelAttributes()).isEqualTo(Collections.singletonMap("foo", foo));
}
@Test
public void modelAttributes() throws Exception {
Foo foo = new Foo();
Bar bar = new Bar();
Rendering rendering = Rendering.view("foo").modelAttributes(foo, bar).build();
Map<String, Object> map = new LinkedHashMap<>(2);
map.put("foo", foo);
map.put("bar", bar);
assertThat(rendering.modelAttributes()).isEqualTo(map);
}
@Test
public void model() throws Exception {
Map<String, Object> map = new LinkedHashMap<>();
map.put("foo", new Foo());
map.put("bar", new Bar());
Rendering rendering = Rendering.view("foo").model(map).build();
assertThat(rendering.modelAttributes()).isEqualTo(map);
}
@Test
public void header() throws Exception {
Rendering rendering = Rendering.view("foo").header("foo", "bar").build();
assertThat(rendering.headers()).hasSize(1);
assertThat(rendering.headers().get("foo")).isEqualTo(Collections.singletonList("bar"));
}
@Test
public void httpHeaders() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.add("foo", "bar");
Rendering rendering = Rendering.view("foo").headers(headers).build();
assertThat(rendering.headers()).isEqualTo(headers);
}
@Test
public void redirectWithAbsoluteUrl() throws Exception {
Rendering rendering = Rendering.redirectTo("foo").contextRelative(false).build();
Object view = rendering.view();
assertThat(view.getClass()).isEqualTo(RedirectView.class);
assertThat(((RedirectView) view).isContextRelative()).isFalse();
}
@Test
public void redirectWithPropagateQuery() throws Exception {
Rendering rendering = Rendering.redirectTo("foo").propagateQuery(true).build();
Object view = rendering.view();
assertThat(view.getClass()).isEqualTo(RedirectView.class);
assertThat(((RedirectView) view).isPropagateQuery()).isTrue();
}
private static class Foo {}
private static class Bar {}
}
|
package com.zhicai.byteera.activity.community.dynamic.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.zhicai.byteera.R;
import butterknife.ButterKnife;
public class MyHomeItemView extends RelativeLayout {
private Context mContext;
private TextView rightText1;
public MyHomeItemView(Context context) {
this(context, null);
}
public MyHomeItemView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyHomeItemView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.mContext = context;
initView(attrs);
}
private void initView(AttributeSet attrs) {
TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.MyHomeItem);
Drawable leftDrawable = attributes.getDrawable(R.styleable.MyHomeItem_leftImg);
String middleText = attributes.getString(R.styleable.MyHomeItem_middleText);
String rightText = attributes.getString(R.styleable.MyHomeItem_rightText);
View inflate = LayoutInflater.from(mContext).inflate(R.layout.my_home_item, this, true);
ImageView leftImg = ButterKnife.findById(inflate, R.id.iv_left);
TextView middleText1 = ButterKnife.findById(inflate,R.id.tv_middle);
rightText1 = ButterKnife.findById(inflate,R.id.tv_right);
View view = new View(mContext);
view.setBackgroundColor(getResources().getColor(R.color.line));
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
view.setLayoutParams(params);
this.addView(view);
leftImg.setImageDrawable(leftDrawable);
middleText1.setText(middleText);
rightText1.setText(rightText);
}
public void setContent(String content){
rightText1.setText(content);
}
}
|
package com.liujc.commonlibrary.router;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.Toast;
import com.liujc.commonlibrary.AppContext;
import com.liujc.commonlibrary.BuildConfig;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
/**
* 类名称:RounterBus
* 创建者:Create by liujc
* 创建时间:Create on 2017/3/30 9:45
* 描述:TODO
*/
public class RounterBus {
//静态map存储代理接口的实例
private static HashMap<Class, Object> sRounterMap = new HashMap<Class, Object>();
/**
* 得到动态代理路由接口的实例
*
* @param c 接口类
* @return
*/
public static IRouterUri getRounter(Class<?> c) {
IRouterUri rounter = (IRouterUri) sRounterMap.get(c);
if (rounter == null) {
rounter = (IRouterUri) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, new InvocationHandler() {
@Override public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//从方法注解的获取uri
RouterUri routerUri = method.getAnnotation(RouterUri.class);
if (routerUri == null || TextUtils.isEmpty(routerUri.value())) {
throw new IllegalArgumentException(
"invoke a rounter method, bug not assign a rounterUri");
}
Uri.Builder uriBuilder = Uri.parse(routerUri.value()).buildUpon();
//从参数值和参数注解,获取信息,拼入uri的query
Annotation[][] annotations = method.getParameterAnnotations();
if (annotations != null && annotations.length > 0) {
for (int i = 0, n = annotations.length; i < n; i++) {
Annotation[] typeAnnotation = annotations[i];
if (typeAnnotation == null || typeAnnotation.length == 0) {
throw new IllegalArgumentException("method " + method.getName() + ", args at " + i + " lack of annotion RouterUri");
}
boolean findAnnotaion = false;
for (Annotation a : typeAnnotation) {
if (a != null && (a.annotationType() == RounterParam.class)) {
uriBuilder.appendQueryParameter(((RounterParam) a).value(), GsonInstance.getInstance().toJson(args[i]));
findAnnotaion = true;
break;
}
}
if (!findAnnotaion) {
throw new IllegalArgumentException("method " + method.getName() + " args at " + i + ", lack of annotion RouterUri");
}
}
}
return getIntentByRouterUri(uriBuilder.build());
}
});
sRounterMap.put(c, rounter);
}
return rounter;
}
private static Intent getIntentByRouterUri(Uri uriBuilder) {
Context context = AppContext.get();
PackageManager pm = context.getPackageManager();
Uri uri = uriBuilder;
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//查询这个intent是否能被接收用来进行跳转
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities != null && !activities.isEmpty()) {
return intent;
} else {
if (BuildConfig.IS_DEBUG) {
Toast.makeText(context, "子模块作为独立程序启动时,跳不到其他模块", Toast.LENGTH_SHORT).show();
} else {
throw new IllegalArgumentException("can't resolve uri with " + uri.toString());
}
}
return null;
}
}
|
package com.yusys.workFlow;
import java.util.List;
import java.util.Map;
public interface WorkFlowNodeDao {
//查询流程下所有节点
public List<Map<String,Object>> queryAllNode4WF(Map<String,Object> map);
//根据条件查询对应的节点信息
public List<Map<String,Object>> queryOneNodeInfo(Map<String,String> map);
//插入一个节点
public void addNodeInfo(Map<String,String> map);
//更新一个节点信息
public void updateNodeInfo(Map<String,String> map);
//根据选择的id删除该节点
public void deleteNodeInfo(Map<String,String> map);
//根据选择的id修改该节点状态为停用
public void updateNodeStateById(Map<String,String> map);
}
|
package persistencia;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import modelo.Remito;
import org.omg.CORBA.ULongLongSeqHelper;
public class RemitoDAO {
ArrayList<String> listaCodigosExistentes;
ArrayList<Integer> planos;
ArrayList<Integer> cantidades;
int ultimoNumeroRemito;
StockSerializadoDAO stock=new StockSerializadoDAO();
ArrayList<Integer> idRemitosPendientes;
ArrayList<String> fechaRemitoPendiente;
ArrayList<Integer> planoEleccion;
ArrayList<Integer> cantidadEleccion;
ArrayList<Integer> remitoEleccion = new ArrayList<>();
ArrayList<String> descripciones = new ArrayList<>();
ArrayList<String> descripcionesEleccion;
public ArrayList<String> getDescripcionEleccion() {
return descripciones;
}
public void setDescripcionEleccion(ArrayList<String> descripcionEleccion) {
this.descripciones = descripcionEleccion;
}
public ArrayList<Integer> getIdRemitosPendientes() {
return idRemitosPendientes;
}
public void setIdRemitosPendientes(ArrayList<Integer> idRemitosPendientes) {
this.idRemitosPendientes = idRemitosPendientes;
}
public ArrayList<String> getFechaRemitoPendiente() {
return fechaRemitoPendiente;
}
public void setFechaRemitoPendiente(ArrayList<String> fechaRemitoPendiente) {
this.fechaRemitoPendiente = fechaRemitoPendiente;
}
public RemitoDAO() {
cargar(); //carga la lista de codigos completos
getPlanoCantidadDesc(); //carga lista de planos y cantidades
}
public ArrayList<Integer> getPlano() {
return planos;
}
public ArrayList<Integer> getCantidad() {
return cantidades;
}
public int getUltimoRemito() {
return ultimoNumeroRemito;
}
public void cargar() {
listaCodigosExistentes=stock.cargarListaCodigosExistentes();
}
public ArrayList<String> getListaCodigosExistentes() {
return listaCodigosExistentes;
}
public void ponerDespachado(ArrayList<String> plano,ArrayList<String> serie, ArrayList<String> verificacion) {
stock.ponerDespachadoArticulos(plano, serie, verificacion);
}
public void ponerEspera(ArrayList<String> plano, ArrayList<String> serie,ArrayList<String> verificacion) {
stock.ponerEsperaArticulos(plano, serie, verificacion);
}
public void getPlanoCantidadDesc() {
stock.cargarPlanoCantidadesDescripciones(); //carga las cosas
planos=stock.getcodigosPlanos();
cantidades=stock.getcantidadeseses();
descripciones=stock.getdescripciones();
}
public void getElecciones(int idRemito) {
cantidadEleccion=new ArrayList<>();
descripcionesEleccion=new ArrayList<>();
planoEleccion=new ArrayList<>();
Remito r = null;
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("SELECT remito_id,a.codigo_plano,cantidad ,d.descripcion_str ");
sb.append("FROM [EleccionPyC] e ");
sb.append("INNER JOIN [Stock Productos Serializados] sps on sps.id=e.sps_id ");
sb.append("INNER JOIN Articulo a on sps.codigo_plano=a.codigo_plano ");
sb.append("INNER JOIN Descripcion d on d.id=a.descripcion_id ");
sb.append("WHERE remito_id= " + idRemito + "");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
rs = stm.executeQuery();
while (rs.next()) {
remitoEleccion.add(rs.getInt(1));
planoEleccion.add(rs.getInt(2));
cantidadEleccion.add(rs.getInt(3));
descripcionesEleccion.add(rs.getString("descripcion_str"));
}
r = new Remito(planoEleccion, cantidadEleccion, remitoEleccion.get(0), descripcionesEleccion, this);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"error en la carga de elecciones");
}
//return r;
}
public ArrayList<String> getArticulosCargados(int idRemito) {
ArrayList<String> articulos = new ArrayList<>();
Remito r = null;
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("SELECT s.codigo_plano,s.numero_serie,s.verificador ");
sb.append("FROM [Remito-SPS] r, [Stock Productos Serializados] s ");
sb.append("WHERE r.sps_id=s.id AND r.remito_id=" + idRemito + "");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
rs = stm.executeQuery();
while (rs.next()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(rs.getInt(1));
sb1.append(rs.getString(2));
sb1.append(rs.getInt(3));
articulos.add(sb1.toString());
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,
"error en la carga de articulos de reito pendiente");
}
return articulos;
}
public void guardarRemito(ArrayList<String> listaPara,ArrayList<Integer> planosRequeridos,ArrayList<Integer> cantidadesRequeridas, int idRemito ) {
insertarRemito();
// ultimoNumeroRemito = obtenerUltimoRemito();
ultimoNumeroRemito=idRemito;
guardarElecciones(planosRequeridos, cantidadesRequeridas);
ArrayList<Integer> idsps = obtenerIdByCodigo(listaPara);
guardarListaArticulos(idsps);
}
public void guardarRemito(ArrayList<String> listaPara,int remitoId) {
// insertarRemito();
ultimoNumeroRemito = remitoId;
// guardarElecciones();
ArrayList<Integer> idsps = obtenerIdByCodigo(listaPara);
updateListaArticulos(idsps,remitoId);
}
private void insertarRemito() {
Connection con;
ResultSet rs = null;
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO Remito (estado_id,fecha_inicio) ");
sb.append("VALUES ('10', GETDATE()) ");
// sb.append("WHERE [codigo_plano]=? AND [numero_serie]=? AND [verificador]=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
stm.executeUpdate();
// JOptionPane.showMessageDialog(null, "Despachado Correctamente");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error guardar remito");
}
}
public int obtenerUltimoRemito() {
int ultimoNumeroRemito;
Connection con;
ResultSet rs = null;
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
// sb.append("SELECT MAX(id) ");
// sb.append("FROM Remito ");
sb.append("SELECT IDENT_CURRENT('Remito')");
// sb.append("VALUES ('10') ");
// sb.append("WHERE [codigo_plano]=? AND [numero_serie]=? AND [verificador]=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
rs = stm.executeQuery();
rs.next();
ultimoNumeroRemito = rs.getInt(1);
// JOptionPane.showMessageDialog(null, "Despachado Correctamente");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error ver ultomo id remito");
return 0;
}
return ultimoNumeroRemito+1;
}
private void guardarElecciones(ArrayList<Integer> planoRequerido,ArrayList<Integer> cantidadRequerido) {
Connection con;
ResultSet rs = null;
rs = null;
StockSerializadoDAO car=new StockSerializadoDAO();
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO EleccionPyC (sps_id,cantidad,remito_id) ");
String obtenerId="(SELECT TOP 1 s.id FROM [Stock Productos Serializados] s WHERE s.codigo_plano=?)";
sb.append("VALUES ("+obtenerId+",?,?)");
// sb.append("VALUES ('10') ");
// sb.append("WHERE [codigo_plano]=? AND [numero_serie]=? AND [verificador]=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
int j = 0;
for (Integer i : planoRequerido) {
stm.setInt(1, i);
stm.setInt(2, cantidadRequerido.get(j));
stm.setInt(3, ultimoNumeroRemito);
stm.executeUpdate();
j++;
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error guardar eleccionpyc");
}
}
private void guardarListaArticulos(ArrayList<Integer> idsps) {
Connection con;
ResultSet rs = null;
rs = null;
// int idsps=obtenerIdByCodigo(codigo)
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("INSERT INTO [Remito-SPS] (remito_id,sps_id) ");
sb.append("VALUES (?,?) ");
// sb.append("VALUES ('10') ");
// sb.append("WHERE [codigo_plano]=? AND [numero_serie]=? AND [verificador]=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
for (Integer i : idsps) {
stm.setInt(1, ultimoNumeroRemito);
stm.setInt(2, i);
stm.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane
.showMessageDialog(null, "error guardar lista articulos");
}
}
private void updateListaArticulos(ArrayList<Integer> idsps,int remitoId) {
Connection con;
ResultSet rs = null;
rs = null;
// int idsps=obtenerIdByCodigo(codigo)
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("IF NOT EXISTS(SELECT * FROM [Remito-SPS] WHERE sps_id=? AND remito_id=?)");
sb.append("BEGIN ");
sb.append("INSERT INTO [Remito-SPS] (remito_id,sps_id) ");
sb.append("VALUES (?,?) ");
sb.append("END");
// sb.append("VALUES ('10') ");
// sb.append("WHERE [codigo_plano]=? AND [numero_serie]=? AND [verificador]=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
for (Integer i : idsps) {
stm.setInt(1, i);
stm.setInt(2, remitoId);
stm.setInt(3, remitoId);
stm.setInt(4, i);
stm.executeUpdate();
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane
.showMessageDialog(null, "error guardar update articulos");
}
}
private ArrayList<Integer> obtenerIdByCodigo(ArrayList<String> codigo) {
Connection con;
ResultSet rs = null;
int id = 0;
ArrayList<Integer> idsps = new ArrayList<>();
rs = null;
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("SELECT s.id ");
sb.append("FROM [Stock Productos Serializados] s ");
sb.append("WHERE s.codigo_plano=? AND s.numero_serie=? AND s.verificador=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
for (String s : codigo) {
stm.setInt(1, Integer.parseInt(s.substring(0, 4)));
stm.setString(2, s.substring(4, 11));
stm.setInt(3, Integer.parseInt(s.substring(11, 12)));
rs = stm.executeQuery();
if (rs.next()) {
id = rs.getInt(1);
idsps.add(id);
}
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error gobtener id by codigo");
}
return idsps;
}
public void guardarRemitoEspera(int idRemito) {
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE [Remito] ");
sb.append("SET estado_id=11 ");
sb.append("WHERE id=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
stm.setInt(1, idRemito);
stm.executeUpdate();
// JOptionPane.showMessageDialog(null,
// "Puesto en espera dso de guardado");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error update espera");
}
}
public void guardarRemitoActivo(int idRemito) {
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE [Remito] ");
sb.append("SET estado_id=10 ");
sb.append("WHERE id=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
stm.setInt(1, idRemito);
stm.executeUpdate();
// JOptionPane.showMessageDialog(null,
// "Puesto en espera dso de guardado");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error update espera");
}
}
public void guardarRemitoDespachado(int idRemito) {
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE [Remito] ");
sb.append("SET estado_id=12,fecha_fin=GETDATE() ");
sb.append("WHERE id=? ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
stm.setInt(1, idRemito);
stm.executeUpdate();
// JOptionPane.showMessageDialog(null,
// "Puesto en despachado al remito que estaba guardado");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error update espera");
}
}
public void cargarRemitosPendientes() {
Connection con;
ResultSet rs = null;
int id = 0;
idRemitosPendientes = new ArrayList<>();
fechaRemitoPendiente=new ArrayList<>();
rs = null;
try {// --------------------------------
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("SELECT r.id ,r.fecha_inicio ");
sb.append("FROM [Remito] r ");
sb.append("WHERE r.estado_id=11 ");
// PREPARAR CONSULTA
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
rs = stm.executeQuery();
while (rs.next()) {
id = rs.getInt("id");
idRemitosPendientes.add(id);
fechaRemitoPendiente.add(rs.getDate("fecha_inicio").toString());
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error cargar pedidos pendientes");
}
}
public void liberaArticulo(String articulo) {
Connection con;
ResultSet rs = null;
try {// ---------------------------------select todos en stock
Conexion cn1 = new Conexion();
con = cn1.getConexion();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE [Stock Productos Serializados] ");
sb.append("SET estado_id=1 ");
sb.append("WHERE codigo_plano=? AND numero_serie=? AND verificador=? ");
PreparedStatement stm;
stm = con.prepareStatement(sb.toString());
stm.setInt(1, Integer.parseInt(articulo.substring(0, 4)));
stm.setString(2, articulo.substring(4, 11));
stm.setInt(3, Integer.parseInt(articulo.substring(11, 12)));
stm.executeUpdate();
// JOptionPane.showMessageDialog(null,"Puesto en despachado al remito que estaba guardado");
System.out.println("articulo liberado");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error libera articuloa");
}
}
public String getDescripcionByCodigo(String codigo){
// String cod=stock.getdescripcionesByCodigo(codigo);
int co=Integer.parseInt(codigo.substring(0,4).trim());
int indice=planos.indexOf(co);
String desc=descripciones.get(indice);
return desc;
}
public ArrayList<String> getDescripcionesByCodigosList(ArrayList<Integer> planoBuscar){
ArrayList<String> descrip=new ArrayList<>();
StringBuilder sb=new StringBuilder();
for(int j=0;j<planoBuscar.size();j++){
int indice=planos.indexOf(planoBuscar.get(j));
String desc=this.descripciones.get(indice);
descrip.add(desc);
}
return descrip;
}
}
|
package com.ssi.cinema.backend.data.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.validation.constraints.NotNull;
@Entity
public class Repertoire extends AbstractEntity {
@NotNull
@Column(length = 1000000)
private Room room;
@NotNull
@Column(length = 1000000)
private Movie movie;
@NotNull
private Date date;
public Repertoire() {
// An empty constructor is needed for all beans
}
public Room getRoom() {
return room;
}
public void setRoom(Room room) {
this.room = room;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
|
package connect;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnUtils {
public static MySQLConnUtils getMySQLConnection()
throws ClassNotFoundException, SQLException {
String hostName = "localhost";
String dbName = "mytest";
String username = "root";
String password = "";
return getMySQLConnection(hostName, dbName, username, password);
}
public static MySQLConnUtils getMySQLConnection(String hostName, String dbName,
String userName, String password) throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
String connectionURL = "jdbc:mysql://localhost:3306/javaweb";
java.sql.Connection conn = DriverManager.getConnection(connectionURL, userName,
password);
System.out.println("ok");
return (MySQLConnUtils) conn;
}
}
|
package com.example.server;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class DefaultUserRepository implements UserRepository {
private JdbcOperations jdbcOperations;
public DefaultUserRepository(JdbcOperations jdbcOperations) {
this.jdbcOperations = jdbcOperations;
}
@Override
public List<User> getAll() {
String sql = "SELECT * FROM USER_MASTER";
return jdbcOperations.query(sql, new UserMapper());
}
@Override
public User get(String id) {
String sql = "SELECT * FROM USER_MASTER WHERE ID='" + id + "'";
return jdbcOperations.queryForObject(sql, new UserMapper());
}
}
|
package messages;
import java.sql.Date;
import beans.*;
import java.io.Serializable;
public class RezervacijaMessage implements Serializable {
static final long serialVersionUID = 42L;
private Date datumOd, datumDo;
private Kupac kupac;
private Soba soba;
public Date getDatumOd() {
return datumOd;
}
public void setDatumOd(Date datumOd) {
this.datumOd = datumOd;
}
public Date getDatumDo() {
return datumDo;
}
public void setDatumDo(Date datumDo) {
this.datumDo = datumDo;
}
public Kupac getKupac() {
return kupac;
}
public void setKupac(Kupac kupac) {
this.kupac = kupac;
}
public Soba getSoba() {
return soba;
}
public void setSoba(Soba soba) {
this.soba = soba;
}
}
|
package com.dassa.controller.guest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.dassa.service.UserService;
import com.dassa.vo.UserVO;
@Controller
@RequestMapping("/login")
public class GuestLoginController {
@Resource
private UserService userService;
//로그인 홈페이지로 이동
@RequestMapping(value="/")
public String GuestLogin() {
return "guest/login/loginHome";
}
//이전페이지로 이동할때 사용
@RequestMapping(value="/reLogin")
public String RedirectLogin(Model model, HttpServletRequest request ) {
String referer = request.getHeader("Referer");
model.addAttribute("referer", referer);
return "guest/login/loginHome";
}
@RequestMapping(value="/logout")
public String GuestLogout(HttpSession session, Model model) {
session.invalidate();
model.addAttribute("msg", "로그아웃 되었습니다.");
model.addAttribute("loc", "/login/index");
return "guest/common/msg";
}
//메인페이지로 이동
@RequestMapping(value="/index")
public String IndexHome() {
return "redirect:/index.jsp";
}
//socialLogin
@RequestMapping(value="/socialLogin")
public String LoginHome(HttpSession session, Model model, @RequestParam String socialId) throws Exception{
UserVO user = userService.guestLogin(socialId);
String view = "";
if(user != null) {
session.setAttribute("user", user);
model.addAttribute("msg", "로그인 되었습니다.");
model.addAttribute("loc", "/login/index");
view= "guest/common/msg";
} else {
model.addAttribute("socialId", socialId);
view="guest/insert/commonInsert";
}
return view;
}
@RequestMapping(value="/commonLogin")
public String Login(HttpSession session, Model model,String userId,String userPw, String referer) throws Exception {
UserVO userVO =new UserVO();
userVO.setUserId(userId);
userVO.setUserPw(userPw);
UserVO user =userService.selectOneUser(userVO);
if(user!=null) {
if(user.getStatus().equals("1")) {
session.setAttribute("user", user);
if(referer == "") {
session.setAttribute("user", user);
model.addAttribute("msg", "로그인 되었습니다.");
model.addAttribute("loc", "/login/index");
return "guest/common/msg";
}else {
model.addAttribute("msg", "로그인 되었습니다.");
model.addAttribute("loc", referer);
return "guest/common/msg";
}
}else {
model.addAttribute("msg", "승인 대기중입니다.");
model.addAttribute("loc", "/login/index");
return "guest/common/msg";
}
}else {
model.addAttribute("msg", "아이디와 비밀번호를 확인해주세요");
model.addAttribute("loc", "/login/");
return "guest/common/msg";
}
}
//네이버 로그인 콜백 페이지로 이동
@RequestMapping(value="/callBack")
public String CallBack() {
return "guest/login/callBack";
}
}
|
package com.potato.hermes.services;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
public class ReceiveFcmEventService extends FirebaseMessagingService {
private static final String TAG = "ReceiveFcmEventService";
public long downloadID;
private Context context = this;
private Uri packageUri;
BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1) == downloadID) {
Toast.makeText(ReceiveFcmEventService.this, "Download complete", Toast.LENGTH_SHORT).show();
installPackage();
}
}
};
public ReceiveFcmEventService() {
}
public void installPackage() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(packageUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
public void onMessageReceived(final RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().toString());
downloadApkFromLink(remoteMessage.getData().get("Url"));
}
@Override
public void onDeletedMessages() {
super.onDeletedMessages();
}
private void downloadApkFromLink(String url) {
Uri uri = Uri.parse(url);
packageUri = uri;
DownloadManager.Request request = new DownloadManager.Request(uri);
File direct = new File(Environment.getExternalStorageDirectory() + "/hermes");
if (!direct.exists()) {
direct.mkdirs();
}
File checkFile = new File(Environment.getExternalStorageDirectory() + "/hermes" + FilenameUtils.getName(uri.getPath()));
if (checkFile.exists()) {
checkFile.delete();
}
request.setDescription("Downloading seamless app update");
request.setDestinationInExternalPublicDir("/hermes", FilenameUtils.getName(uri.getPath()));
request.setTitle(FilenameUtils.getName(uri.getPath()));
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
downloadID = manager.enqueue(request);
}
@Override
public void onCreate() {
super.onCreate();
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
}
|
package com.example.idp4;
public class BluetoothException extends Exception
{
public String attrName ;
BluetoothException(String name)
{
super(name) ;
attrName = name ;
}
}
|
package example.controllers;
import common.models.Project;
import example.services.AnotherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class AnotherController {
private final AnotherService anotherService;
@Autowired
public AnotherController(AnotherService anotherService) {
this.anotherService = anotherService;
}
@RequestMapping("/")
public List<Project> index() {
return this.anotherService.getAllProjects();
}
}
|
package poi;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.*;
/**
* @Description
* @auther denny
* @create 2020-01-02 15:02
*/
public class CrawlTest {
public static void main(String[] args) {
List<Map<String, String>> mapList = Arrays.asList(
new HashMap<String, String>() {{ put("name","XT新塘地王广场");put("gps","113.614610,23.116868");put("adcode","增城区"); }}
);
String url = "https://apis.map.qq.com/bigdata/popinsight/v1/flownum";
for (int i=0;i<mapList.size();i++) {
Map<String, String> map = mapList.get(i);
String params = "{ \"boundary_type\": \"circle\", \"center\": \"%s\", \"range\": \"500\", \"adcode\": \"%s\", \"min_area\": \"10000\", \"month\": \"201911\", \"date_type\": \"1,2,3\", \"key\":\"UJMBZ-T35WG-UEDQL-IGGWO-7V7TV-OGB4A\"}";
String[] strings = map.get("gps").split(",");
String gps = strings[1] + "," + strings[0];
String adcode = "440118";
params = String.format(params, gps, adcode);
String result = httpPostRaw(url, params, null, "UTF-8");
JSONObject object = JSON.parseObject(result).getJSONObject("result");
JSONObject data = object.getJSONObject("500m");
Iterator iterator = data.entrySet().iterator();
List<String> list = new ArrayList<>();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry) iterator.next();
String key = (String) entry.getKey();
list.add(key+"_"+ "day_avg");
for(int j=0;j<24;j++){
list.add(key+"_"+ "hour_avg_" + j);
}
}
String[] title = new String[list.size()];
for (int j=0;j<list.size();j++) {
title[j] = list.get(j);
}
System.out.println(title);
}
}
public static String httpPostRaw(String url, String stringJson, Map<String,String> headers, String encode){
if(encode == null){
encode = "utf-8";
}
//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
String content = null;
CloseableHttpResponse httpResponse = null;
try {
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //关闭连接、释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
|
package org.wuxinshui.boosters.designPatterns.builder;
/**
* Created with IntelliJ IDEA.
* User: FujiRen
* Date: 2016/11/11
* Time: 11:15
* To change this template use File | Settings | File Templates.
*/
public class MealA extends MealBuilder {
@Override
public void buildFood() {
meal.setFood("jitui");
}
@Override
public void buildDrink() {
meal.setDrink("kele");
}
}
|
package com.pichincha.prueba.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.pichincha.prueba.model.Transacciones;
@Repository
public interface ITransaccionesDAO extends JpaRepository<Transacciones, Integer>{
}
|
package com.cacadosman.kpujj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KpujjApplication {
public static void main(String[] args) {
SpringApplication.run(KpujjApplication.class, args);
}
}
|
package com.self.modules.dubbo;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
public interface DubboTest {
String hello(String name);
}
|
package rest.test.happilyy.dto;
import java.util.Date;
public class CheatCode {
private String cheatCodeId;
private String cheatCodeInput;
private String gameName;
private String consoleName;
private Date lastUpdated;
public String getCheatCodeId() {
return cheatCodeId;
}
public void setCheatCodeId(String cheatCodeId) {
this.cheatCodeId = cheatCodeId;
}
public String getCheatCodeInput() {
return cheatCodeInput;
}
public void setCheatCodeInput(String cheatCodeInput) {
this.cheatCodeInput = cheatCodeInput;
}
public String getGameName() {
return gameName;
}
public void setGameName(String gameName) {
this.gameName = gameName;
}
public String getConsoleName() {
return consoleName;
}
public void setConsoleName(String consoleName) {
this.consoleName = consoleName;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
|
package com.Exam.Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Exam.DAO.PaymentDAO;
import com.Exam.Entity.Payment;
@Service
public class PaymentService {
@Autowired
PaymentDAO paymentDAO;
// Show all Payment
public List<Payment> showPayment(){
return paymentDAO.findAll();
}
}
|
package Banco.Reserva.Conta.Repository;
import Banco.Reserva.Conta.Domain.Cliente;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface ClientesRepository extends MongoRepository<Cliente, String> {
@Query("{'_id': ?0}")
Optional<Cliente> findById(int id);
}
|
//package sheep.domain;
//
//import javax.persistence.*;
//
//@Entity
//public class Delivery {
//
// @Id
// @GeneratedValue
// private Long id;
//
// @OneToOne(mappedBy = "delivery",fetch = FetchType.LAZY) //mappedby는 상대방 변수명.
// private Order order;
//
// private String city;
//
// private String street;
//
// private String zipcode;
//
// private DeliveryStatus deliveryStatus;
//}
|
package de.varylab.discreteconformal.unwrapper.circlepattern;
import java.util.HashMap;
import java.util.Map;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Vertex;
import de.jtem.jpetsc.Mat;
import de.jtem.jpetsc.PETSc;
import de.jtem.jpetsc.Vec;
import de.jtem.jtao.Tao;
import de.jtem.jtao.Tao.Method;
import de.varylab.discreteconformal.unwrapper.numerics.CPEuclideanApplication;
import de.varylab.discreteconformal.unwrapper.quasiisothermic.QuasiisothermicUtility;
public class CirclePatternUtility {
public static <
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>,
HDS extends HalfEdgeDataStructure<V, E, F>
> Map<F, Double> calculateCirclePatternRhos(HDS hds, Map<E, Double> thetaMap, Map<F, Double> phiMap) {
for (E e : hds.getPositiveEdges()) {
double theta = thetaMap.get(e);
if (theta < 0) {
System.err.println("negative theta at " + e + ": " + theta);
}
}
int dim = hds.numFaces();
Tao.Initialize();
Vec rho = new Vec(dim);
rho.zeroEntries();
rho.assemble();
CPEuclideanApplication<V, E, F, HDS> app = new CPEuclideanApplication<V, E, F, HDS>(hds, thetaMap, phiMap);
app.setInitialSolutionVec(rho);
Mat H = Mat.createSeqAIJ(dim, dim, PETSc.PETSC_DEFAULT, QuasiisothermicUtility.getPETScNonZeros(hds, app.getFunctional()));
H.assemble();
app.setHessianMat(H, H);
Tao tao = new Tao(Method.NTR);
tao.setApplication(app);
tao.setMaximumIterates(200);
tao.setTolerances(1E-15, 0, 0, 0);
tao.setGradientTolerances(1E-15, 0, 0);
tao.solve();
System.out.println(tao.getSolutionStatus());
Map<F, Double> rhos = new HashMap<F, Double>();
for (F f : hds.getFaces()) {
rhos.put(f, rho.getValue(f.getIndex()));
}
return rhos;
}
}
|
package sampleproject.gui;
import java.util.*;
import java.util.logging.*;
import javax.swing.table.*;
import sampleproject.db.*;
/**
* The custom table model used by the <code>MainWindow</code> instance.
*
* @author Denny's DVDs
* @version 2.0
* @see sampleproject.gui.MainWindow
*/
public class DvdTableModel extends AbstractTableModel {
/**
* A version number for this class so that serialization can occur
* without worrying about the underlying class changing between
* serialization and deserialization.
*
* Not that we ever serialize this class of course, but AbstractTableModel
* implements Serializable, so therefore by default we do as well.
*/
private static final long serialVersionUID = 5165L;
/**
* The Logger instance. All log messages from this class are routed through
* this member. The Logger namespace is <code>sampleproject.gui</code>.
*/
private Logger log = Logger.getLogger("sampleproject.gui");
/**
* An array of <code>String</code> objects representing the table headers.
*/
private String [] headerNames = {"UPC", "Movie Title", "Director",
"Lead Actor", "Supporting Actor",
"Composer", "Copies in Stock"};
/**
* Holds all Dvd instances displayed in the main table.
*/
private ArrayList<String[]> dvdRecords = new ArrayList<String[]>(5);
/**
* Returns the column count of the table.
*
* @return An integer indicating the number or columns in the table.
*/
public int getColumnCount() {
return this.headerNames.length;
}
/**
* Returns the number of rows in the table.
*
* @return An integer indicating the number of rows in the table.
*/
public int getRowCount() {
return this.dvdRecords.size();
}
/**
* Gets a value from a specified index in the table.
*
* @param row An integer representing the row index.
* @param column An integer representing the column index.
* @return The object located at the specified row and column.
*/
public Object getValueAt(int row, int column) {
String[] rowValues = this.dvdRecords.get(row);
return rowValues[column];
}
/**
* Sets the cell value at a specified index.
*
* @param obj The object that is placed in the table cell.
* @param row The row index.
* @param column The column index.
*/
public void setValueAt(Object obj, int row, int column) {
Object[] rowValues = this.dvdRecords.get(row);
rowValues[column] = obj;
}
/**
* Returns the name of a column at a given column index.
*
* @param column The specified column index.
* @return A String containing the column name.
*/
public String getColumnName(int column) {
return headerNames[column];
}
/**
* Given a row and column index, indicates if a table cell can be edited.
*
* @param row Specified row index.
* @param column Specified column index.
* @return A boolean indicating if a cell is editable.
*/
public boolean isCellEditable(int row, int column) {
return false;
}
/**
* Adds a row of Dvd data to the table.
*
* @param upc The Dvd upc.
* @param name The name of the movie.
* @param director The movie's director.
* @param leadActor The movie's lead actor.
* @param supportingActor The movie's supporting actor.
* @param composer The movie's composer.
* @param numberOfCopies The number of DvdDvdDvds in stock.
*/
public void addDvdRecord(String upc, String name, String director,
String leadActor, String supportingActor,
String composer, int numberOfCopies) {
String [] temp = {upc, name, director, leadActor, supportingActor,
composer, Integer.toString(numberOfCopies)};
this.dvdRecords.add(temp);
}
/**
* Adds a Dvd object to the table.
*
* @param dvd The Dvd object to add to the table.
*/
public void addDvdRecord(DVD dvd) {
addDvdRecord(dvd.getUPC(), dvd.getName(), dvd.getDirector(),
dvd.getLeadActor(), dvd.getSupportingActor(),
dvd.getComposer(), dvd.getCopy());
}
}
|
package com.acompanhamento.api.service;
import com.acompanhamento.api.domain.Login;
import com.acompanhamento.api.domain.Responsavel;
import org.springframework.data.domain.Page;
import java.util.List;
public interface ResponsavelService {
Responsavel cadastrarLoginResponsavel(Login login);
Page<Responsavel> listarTodosResponsaveis(Integer page, Integer count);
Responsavel buscarResponsavelPeloNome(String nome) throws Exception;
Responsavel buscarResponsavelPeloEmail(String email);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.