text
stringlengths 10
2.72M
|
|---|
package pkg8queen;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import static pkg8queen.Main.simulatedAnnealing;
public class Board extends javax.swing.JFrame {
private JLabel[][] cell = new JLabel[8][8];
private Queen[] insertedQeens = new Queen[8];
public Board() {
initComponents();
setLocationRelativeTo(null);
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
cell[row][col] = new JLabel();
cell[row][col].setVisible(true);
cell[row][col].setSize(70, 70);
cell[row][col].setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/N_PLACED.png")));
cell[row][col].setLocation(70 * col, 70 * row);
add(cell[row][col]);
boardPanel.add(cell[row][col]);
int r = row;
int c = col;
cell[row][col].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (insertedQeens[c] != null && insertedQeens[c].getRow() == r) {
cell[r][c].setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/N_PLACED.png")));
insertedQeens[c] = null;
} else {
if (insertedQeens[c] != null) {
cell[insertedQeens[c].getRow()][c].setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/N_PLACED.png")));
insertedQeens[c] = null;
}
cell[r][c].setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/QUEEN.png")));
insertedQeens[c] = new Queen(r, c);
}
}
});
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
boardPanel = new javax.swing.JPanel();
runButton = new javax.swing.JButton();
randomSA = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(620, 750));
setPreferredSize(new java.awt.Dimension(620, 750));
getContentPane().setLayout(null);
boardPanel.setMinimumSize(new java.awt.Dimension(640, 640));
boardPanel.setPreferredSize(new java.awt.Dimension(640, 640));
boardPanel.setLayout(null);
getContentPane().add(boardPanel);
boardPanel.setBounds(20, 20, 680, 560);
runButton.setText("Run SA");
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
getContentPane().add(runButton);
runButton.setBounds(370, 660, 140, 23);
randomSA.setText("Run SA with random initial");
randomSA.setToolTipText("");
randomSA.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
randomSAActionPerformed(evt);
}
});
getContentPane().add(randomSA);
randomSA.setBounds(80, 660, 280, 23);
pack();
}// </editor-fold>//GEN-END:initComponents
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
State result = simulatedAnnealing(generateInitialState());
System.out.println(result + "\nh : " + result.getH());
}//GEN-LAST:event_runButtonActionPerformed
private void randomSAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_randomSAActionPerformed
State result = simulatedAnnealing(null);
System.out.println(result + "\nh : " + result.getH());
}//GEN-LAST:event_randomSAActionPerformed
State generateInitialState() {
return new State(insertedQeens);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Board.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Board.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Board.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Board.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Board().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel boardPanel;
private javax.swing.JButton randomSA;
private javax.swing.JButton runButton;
// End of variables declaration//GEN-END:variables
}
|
import java.util.Scanner;
public class solution {
public static String getSmallestAndLargest(String s, int k) {
String smallest = "";
String largest = "";
smallest = s.substring(0,k);
largest = s.substring(0,k);
// "Compare to" method doesn't turn just the equel case it also turns a value.
for(int i=0; i<=s.length()-k; i++ ){
String str = s.substring(i,k+i);
int sc = smallest.compareTo(str);
int lc = largest.compareTo(str);
if (sc > 0){
smallest = str;
}
if(lc < 0){
largest=str;
}
}
return smallest + "\n" + largest;
}
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
String s = "welcometojava";
int k = 3;
//scan.close();
System.out.println("Genevieve Xalxo");
System.out.println("Genevieve Xalxo");
System.out.println(getSmallestAndLargest(s, k));
}
}
|
package com.kwik.repositories.client.impl;
import static br.com.six2six.fixturefactory.Fixture.from;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.jstryker.database.DBUnitHelper;
import org.junit.Before;
import org.junit.Test;
import com.kwik.fixture.load.TemplateLoader;
import com.kwik.helper.TestHelper;
import com.kwik.models.Address;
import com.kwik.repositories.client.AddressRespository;
import com.kwik.repositories.client.dao.AddressDao;
public class AddressDaoTest extends TestHelper {
private AddressRespository addressRepository;
@Before
public void setUp() {
addressRepository = new AddressDao(entityManager);
}
@Test
public void shouldFindZipCode() throws Exception {
new DBUnitHelper().cleanInsert("/clients/address.xml");
String zipCode = "01245888";
Address address = addressRepository.findBy(zipCode);
assertThat(address.getZipCode(), is(zipCode));
}
@Test
public void shouldIncludeAddress() throws Exception {
Address fixture = from(Address.class).gimme(TemplateLoader.AddressTemplate.ENDERECO);
Address returned = addressRepository.add(fixture);
assertThat(returned.getId(), is(notNullValue()));
}
}
|
/*
* Copyright 2002-2017 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.core;
import org.springframework.lang.Nullable;
/**
* Any object can implement this interface to provide its actual {@link ResolvableType}.
*
* <p>Such information is very useful when figuring out if the instance matches a generic
* signature as Java does not convey the signature at runtime.
*
* <p>Users of this interface should be careful in complex hierarchy scenarios, especially
* when the generic type signature of the class changes in subclasses. It is always
* possible to return {@code null} to fallback on a default behavior.
*
* @author Stephane Nicoll
* @since 4.2
*/
public interface ResolvableTypeProvider {
/**
* Return the {@link ResolvableType} describing this instance
* (or {@code null} if some sort of default should be applied instead).
*/
@Nullable
ResolvableType getResolvableType();
}
|
package com.spreadtrum.android.eng;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.System;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
public class uaagent extends Activity {
private Button mBtnCancel;
private RadioButton mBtnCustom;
private RadioButton mBtnDefault;
private RadioButton mBtnIphone;
private RadioButton mBtnMtk;
private Button mBtnOk;
private RadioButton mBtnSamsung;
private String mCustomUaStr = null;
private String mDefaultUaStr = null;
private EditText mEditor;
private OnCheckedChangeListener mListener = new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.default_ua:
uaagent.this.mEditor.setText(uaagent.this.mDefaultUaStr);
uaagent.this.mUaChoice = 0;
break;
case R.id.mtk_ua:
uaagent.this.mEditor.setText("Mozilla/5.0 (Linux; U; Android 4.0; en-us; GIONEE GN105 Build/FRF91) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
uaagent.this.mUaChoice = 1;
break;
case R.id.samsung_ua:
uaagent.this.mEditor.setText("Mozilla/5.0 (Linux; U; Android 4.0.3 zh-cn; GT-I9100 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
uaagent.this.mUaChoice = 2;
break;
case R.id.iphone_ua:
uaagent.this.mEditor.setText("Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
uaagent.this.mUaChoice = 3;
break;
case R.id.custom_ua:
uaagent.this.mEditor.setText(uaagent.this.mCustomUaStr);
uaagent.this.mEditor.setSelection(uaagent.this.mEditor.getText().length());
uaagent.this.mUaChoice = 4;
break;
default:
Log.e("eng/user-agent", "checkedId is <" + checkedId + ">");
break;
}
if (4 == uaagent.this.mUaChoice) {
uaagent.this.mEditor.setBackgroundColor(-1);
uaagent.this.mEditor.setTextColor(-16777216);
uaagent.this.mEditor.setFocusableInTouchMode(true);
} else {
uaagent.this.mEditor.setBackgroundColor(-7829368);
uaagent.this.mEditor.setTextColor(-16777216);
uaagent.this.mEditor.setFocusableInTouchMode(false);
uaagent.this.mEditor.clearFocus();
((InputMethodManager) uaagent.this.getSystemService("input_method")).hideSoftInputFromWindow(uaagent.this.mEditor.getWindowToken(), 0);
}
Log.d("eng/user-agent", "mUaChoice: " + uaagent.this.mUaChoice);
}
};
private RadioGroup mRadioGroup;
private int mUaChoice;
private WebView mWebView = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.useragent);
this.mRadioGroup = (RadioGroup) findViewById(R.id.ua_group);
this.mRadioGroup.setOnCheckedChangeListener(this.mListener);
this.mBtnDefault = (RadioButton) findViewById(R.id.default_ua);
this.mBtnMtk = (RadioButton) findViewById(R.id.mtk_ua);
this.mBtnSamsung = (RadioButton) findViewById(R.id.samsung_ua);
this.mBtnIphone = (RadioButton) findViewById(R.id.iphone_ua);
this.mBtnCustom = (RadioButton) findViewById(R.id.custom_ua);
this.mEditor = (EditText) findViewById(R.id.ua_editor);
this.mBtnOk = (Button) findViewById(R.id.btn_ok);
this.mBtnCancel = (Button) findViewById(R.id.btn_cancel);
this.mWebView = new WebView(this);
initView();
}
private void initView() {
this.mUaChoice = System.getInt(getContentResolver(), "user_agent_choice", 0);
this.mCustomUaStr = System.getString(getContentResolver(), "custom_user_agent_string");
this.mDefaultUaStr = this.mWebView.getSettings().getDefaultUserAgentString();
Log.d("eng/user-agent", "-->initView-->mCustomUaStr is <" + this.mCustomUaStr + ">");
Log.d("eng/user-agent", "-->initView-->mDefaultUaStr is <" + this.mDefaultUaStr + ">");
Log.d("eng/user-agent", "-->initView-->mUaChoice is <" + this.mUaChoice + ">");
if (4 == this.mUaChoice) {
this.mEditor.setBackgroundColor(-1);
this.mEditor.setTextColor(-16777216);
} else {
this.mEditor.setBackgroundColor(-7829368);
this.mEditor.setTextColor(-16777216);
}
this.mEditor.setFocusableInTouchMode(false);
this.mEditor.clearFocus();
((InputMethodManager) getSystemService("input_method")).hideSoftInputFromWindow(this.mEditor.getWindowToken(), 0);
switch (this.mUaChoice) {
case 1:
this.mBtnMtk.setChecked(true);
this.mEditor.setText("Mozilla/5.0 (Linux; U; Android 4.0; en-us; GIONEE GN105 Build/FRF91) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
break;
case 2:
this.mBtnSamsung.setChecked(true);
this.mEditor.setText("Mozilla/5.0 (Linux; U; Android 4.0.3 zh-cn; GT-I9100 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
break;
case 3:
this.mBtnIphone.setChecked(true);
this.mEditor.setText("Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
break;
case 4:
this.mBtnCustom.setChecked(true);
this.mEditor.setText(this.mCustomUaStr);
this.mEditor.setSelection(this.mEditor.getText().length());
break;
default:
this.mBtnDefault.setChecked(true);
this.mEditor.setText(this.mDefaultUaStr);
this.mUaChoice = 0;
break;
}
this.mEditor.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("eng/user-agent", "-->mEditor-->onClick()");
if (4 == uaagent.this.mUaChoice) {
Log.d("eng/user-agent", "-->mEditor-->setFocusable = true");
uaagent.this.mEditor.requestFocus();
return;
}
uaagent.this.mEditor.clearFocus();
}
});
this.mEditor.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
Log.d("eng/user-agent", "-->mEditor-->OnFocusChange()");
if (4 != uaagent.this.mUaChoice) {
}
}
});
this.mBtnOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
Log.d("eng/user-agent", "-->mBtnOk.onClick-->mUaChoice is <" + uaagent.this.mUaChoice + ">");
System.putInt(uaagent.this.getContentResolver(), "user_agent_choice", uaagent.this.mUaChoice);
if (4 == uaagent.this.mUaChoice) {
uaagent.this.mCustomUaStr = uaagent.this.mEditor.getText().toString();
Log.d("eng/user-agent", "-->mBtnOk.onClick-->mCustomUaStr is <" + uaagent.this.mCustomUaStr + ">");
System.putString(uaagent.this.getContentResolver(), "custom_user_agent_string", uaagent.this.mCustomUaStr);
}
} catch (NumberFormatException e) {
Log.e("eng/user-agent", "Save User-Agent choice failed!", e);
}
uaagent.this.finish();
}
});
this.mBtnCancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
uaagent.this.finish();
}
});
}
}
|
import java.io.*;
import java.net.*;
import java.util.*;
//Code modified from the Red-Blue Assignment
class MulticastServer {
private static void logIn(String b, InetAddress a)
{
String temp[] = b.split(":");
String userName = temp[1];
String password = temp[2];
byte[] buffer = new byte[256];
if (userName.equals("a") && password.equals("b"))
{
System.out.println("User succesfully logged in");
DatagramSocket clientSocket = null;
buffer = "login Successful".getBytes();
try{
DatagramPacket output = new DatagramPacket(buffer, buffer.length, a, 9876);
DatagramSocket serverSocket = new DatagramSocket();
serverSocket.send(output);
}
catch(IOException ioe){
}
}
else
{
buffer = "login UnSuccessful".getBytes();
try {
DatagramPacket output = new DatagramPacket(buffer, buffer.length, a, 9876);
DatagramSocket serverSocket = new DatagramSocket();
serverSocket.send(output);
}
catch(IOException ioe) {
}
}
}
public static void main(String args[]) throws Exception
{
MulticastSocket serverSocket = null;
serverSocket = new MulticastSocket(8888);
DatagramSocket clientSocket = null;
clientSocket = new DatagramSocket(9876);
Scanner reader = new Scanner(System.in);
System.out.println("Enter an ip between 224.0.0.0 to 239.255.255.255 inclusive. You shall create a server on this multicast ip");
String tempIP = reader.nextLine();
InetAddress IPAddress = InetAddress.getByName(tempIP);
PrintWriter writer = new PrintWriter("chatlog.txt", "UTF-8");
byte[] buffer = new byte[256];
int port = 0, port1 = 0, port2 = 0;
String message = "";
String response = "";
DatagramPacket receivePacket = null;
DatagramPacket sendPacket = null;
int state = 2;
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
byte[] messageBytes = new byte[1024];
serverSocket.joinGroup(IPAddress);
ServerInputHandler A = new ServerInputHandler(writer);
Thread theThread = new Thread(A);
theThread.start();
System.out.println("Type End to end and save chat logging. Make sure to do this before closing the server, or the logs will not be saved.");
while (state < 3){
receiveData = new byte[1024];
sendData = new byte[1024];
switch (state){
case 2: // state 2: Chat mode
receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
message = new String(receivePacket.getData());
String temp = message.substring(0,1);
//Displays the message and channel broadcast to. This is currently debug
//System.out.println(temp);
System.out.println(message);
writer.println(message);
try
{
buffer = message.getBytes();
sendPacket = new DatagramPacket(buffer, buffer.length, IPAddress, 8888);
serverSocket.send(sendPacket);
}
catch (IOException ioe)
{
System.out.println(ioe);
}
//serverSocket.send(sendPacket);
//stay in state 2
break;
} //end switch
} //end while
//send Goodbye messages to both clients
//close the socket
}
}
|
public class HW2_4 {
public static void main(String[] args) {
int i;
int[] ent= new int[10];
for(i=0;i<50;i++) {
int num = (int)(Math.random()*101);
switch(num/10) {
case 10 :
case 9 : ent[9]++; break;
case 8 : ent[8]++; break;
case 7 : ent[7]++; break;
case 6 : ent[6]++; break;
case 5 : ent[5]++; break;
case 4 : ent[4]++; break;
case 3 : ent[3]++; break;
case 2 : ent[2]++; break;
case 1 : ent[1]++; break;
case 0 : ent[0]++; break;
}
}
int max=0;
for(int j=0;j<10;j++) {
if(max<=ent[j])
max = ent[j];
}
for(int j=max;j>0;j--) {
for(int k=0;k<10;k++) {
if(ent[k]==j) {
System.out.print(" * "); ent[k]--;
}
else if(ent[k]!=j)
System.out.print(" ");
}
System.out.println("");
}
for(int j=0;j<10;j++) {
System.out.printf("%3d", j*10+5);
}
}
}
|
package com.scalefocus.java.repository.local;
import com.scalefocus.java.domain.local.Role;
import com.scalefocus.java.domain.local.RoleName;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, Long> {
Optional<Role> findByName(RoleName roleName);
}
|
/*
* 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 dequeproject;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
/**
*
* @author nsalemu2019
*/
public class Permutation {
public static void main(String[] args){
int k = Integer.parseInt(args[0]);
RandomizedQueue<String> rq = new RandomizedQueue<String>();
// read in a sequence of N strings from standard input
while (!StdIn.isEmpty()) {
String item = StdIn.readString();
rq.enqueue(item);
}
// print out exactly k of them, uniformly at random;
// each item from the sequence can be printed out at most once
while (k > 0) {
StdOut.println(rq.dequeue());
k--;
}
}
}
|
package com.futs.resource;
import com.futs.model.Campeonato;
import com.futs.service.impl.CampeonatoServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("campeonatos")
public class CampeonatoResource {
@Autowired
private CampeonatoServiceImpl CampeonatoServiceImpl;
@ApiOperation("Listagem de todos campeonatos")
@GetMapping
public List<Campeonato> buscaTodosCampeonatos() {
return CampeonatoServiceImpl.listarTodosCampeonatos();
}
@ApiOperation("Obtem um único campeonato")
@GetMapping("{codigo}")
public Campeonato obtemUnicoCampeonato(@PathVariable("codigo") Integer codigo) {
return CampeonatoServiceImpl.buscarCampeonatoPeloCodigo(codigo);
}
@ApiOperation("Cadastrar campeonato")
@PostMapping
public ResponseEntity<Campeonato> cadastrarCampeonato(@Valid @RequestBody Campeonato campeonato) {
return CampeonatoServiceImpl.cadastrarCampeonato(campeonato);
}
@ApiOperation("Atualizar campeonato")
@PutMapping("{codigo}")
public ResponseEntity<Campeonato> atualizarCampeonato(@PathVariable("codigo") Integer codigo, @Valid @RequestBody Campeonato campeonato) {
return CampeonatoServiceImpl.atualizarCampeonato(codigo, campeonato);
}
@ApiOperation("Remove um campeonato")
@DeleteMapping("{codigo}")
public void removerCampeonato(@PathVariable("codigo") Integer codigo) {
CampeonatoServiceImpl.removerCampeonato(codigo);
}
}
|
package com.zxt.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author h
*
*/
public class GetMACAddress {
/**
* 直接获取网卡地址
* @return
*/
public static String getMACAddress() {
String address = "";
String os = System.getProperty("os.name");
if (os != null) {
if (os.startsWith("Windows")) {
try {
ProcessBuilder pb = new ProcessBuilder("ipconfig", "/all");
Process p = pb.start();
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
if ((line.indexOf("Physical Address") != -1)||(line.indexOf("物理地址") != -1)) {
int index = line.indexOf(":");
address = line.substring(index + 1);
break;
}
}
br.close();
if (address!=null) {
address.trim();
address= MD5andKL.MD5(address);
}
return address.trim();
} catch (IOException e) {
}
} else if (os.startsWith("Linux")) {
try {
ProcessBuilder pb = new ProcessBuilder("ifconfig");
Process p = pb.start();
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
int index = line.indexOf("硬件地址");
if (index != -1) {
address = line.substring(index + 4);
break;
}
}
br.close();
return address.trim();
} catch (IOException ex) {
// Logger.getLogger(Test.class.getName()).log(Level.SEVERE,
// null, ex);
}
}
}
return address;
}
public static void main(String[] args) {
System.out.println(getMACAddress());
System.out.println(MD5andKL.MD5("sdfsdf"));
}
}
|
package com.example.vmac.myrobot.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class StartService extends Service {
private IBinder iBinder;
public StartService() {
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(this.getClass().getSimpleName(),"*** onDestroy 服务");
}
private class MyBinder extends Binder {
StartService getService(){
return StartService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(this.getClass().getSimpleName(),"***空服务,启动服务");
return super.onStartCommand(intent, flags, startId);
}
}
|
package com.lgbear.weixinplatform.message.service;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import com.lgbear.weixinplatform.base.domain.Pagination;
import com.lgbear.weixinplatform.message.dao.TextDao;
import com.lgbear.weixinplatform.message.domain.Passive;
import com.lgbear.weixinplatform.message.domain.Text;
import com.lgbear.weixinplatform.user.service.UserService;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
@Service
public class EventService {
@Resource
UserService userService;
public void loadEventMessage(Document document, HttpServletResponse response) {
Element root = document.getRootElement();
// Text text = new Text(root.elementText("MsgId"), root.elementText("Content"), Integer.parseInt(root.elementText("CreateTime")), root.elementText("FromUserName"), root.elementText("ToUserName"));
if ("click".equals(root.elementText("Event"))) {
clickEvent(document, response);
} else if ("subscribe".equals(root.elementText("Event"))) {
userService.getUserInfo(root.elementText("FromUserName"));
}
}
public void clickEvent (Document document, HttpServletResponse response) {
Element root = document.getRootElement();
if ("good_event".equals(root.elementText("EventKey"))) {
String reply = "";
sendText(root.elementText("ToUserName"), root.elementText("FromUserName"), System.currentTimeMillis(), reply==""?"收到"+root.elementText("EventKey")+"事件,正在为你准备回应.":reply, response);
}
}
public void sendText(String FromUserName, String ToUserName, Long CreateTime, String content, HttpServletResponse response){
StringBuilder buffer = new StringBuilder();
buffer.append("<xml>\n");
buffer.append("<ToUserName><![CDATA[").append(ToUserName).append("]]></ToUserName>\n");
buffer.append("<FromUserName><![CDATA[").append(FromUserName).append("]]></FromUserName>\n");
buffer.append("<CreateTime><![CDATA[").append(CreateTime).append("]]></CreateTime>\n");
buffer.append("<MsgType><![CDATA[text]]></MsgType>\n");
buffer.append("<Content><![CDATA[").append(content).append("]]></Content>\n");
buffer.append("<FuncFlag>0</FuncFlag>\n");
buffer.append("</xml>\n");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;charset=utf-8");
try {
response.getWriter().println(buffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.myvodafone.android.front.fixed;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.FixedLinePaymentsManager;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.front.VFGRFragment;
import com.myvodafone.android.front.helpers.Dialogs;
import com.myvodafone.android.front.payment.DecimalDigitsInputFilter;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.model.view.VFModelFXLAccount;
import com.myvodafone.android.utils.GlobalData;
import com.myvodafone.android.utils.StaticTools;
import com.myvodafone.android.utils.VFPreferences;
import java.lang.ref.WeakReference;
/**
* Created by kakaso on 2/3/2016.
*/
public class FragmentFXLPayBill extends VFGRFragment implements FixedLinePaymentsManager.FixedLinePaymentsListener {
private static final String TOTAL_AMOUNT_TAG = "TOTAL_AMOUNT_TAG";
private static final String OPEN_AMOUNT_TAG = "OPEN_AMOUNT_TAG";
final float PAYMENTFLAG = -Float.MAX_VALUE;
TextView txtFullCurrentTotal, txtPaymentTerms;
EditText editAmount;
Button btnContinue;
CheckBox checkAgree;
double currentAmount = PAYMENTFLAG;
double openAmount = PAYMENTFLAG;
public static FragmentFXLPayBill newInstance(String totalAmount, String overdueAmount) {
FragmentFXLPayBill fragment = new FragmentFXLPayBill();
Bundle args = new Bundle();
args.putString(TOTAL_AMOUNT_TAG, totalAmount);
args.putString(OPEN_AMOUNT_TAG, overdueAmount);
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fxl_paybill, container, false);
OmnitureHelper.trackView("My bill fixed");
initViews(view);
return view;
}
private void initViews(View v) {
header = (TextView) v.findViewById(R.id.headerTitle);
setFragmentTitle();
txtFullCurrentTotal = (TextView) v.findViewById(R.id.txtFxlCurrentTotal);
btnContinue = (Button) v.findViewById(R.id.btnContinue);
checkAgree = (CheckBox) v.findViewById(R.id.fxlCheckAgree);
txtPaymentTerms = (TextView) v.findViewById(R.id.txtFxlTerms);
editAmount = (EditText) v.findViewById(R.id.editAmount);
// Allow only 2 decimal digits
editAmount.setFilters(new InputFilter[] {new DecimalDigitsInputFilter()});
editAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (VFPreferences.getLanguage() == GlobalData.LANGUAGE_GR) {
if (editAmount.getText().toString().contains(".")) {
editAmount.setText(editAmount.getText().toString().replace(".", ","));
}
} else {
if (editAmount.getText().toString().contains(",")) {
editAmount.setText(editAmount.getText().toString().replace(",", "."));
}
}
editAmount.setSelection(editAmount.getText().length());
}
});
checkAgree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
btnContinue.setEnabled(isChecked);
}
});
checkAgree.setChecked(false);
btnContinue.setEnabled(false);
txtPaymentTerms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.launchActivity(ActPaymentTerms.class);
}
});
// Get cached openAmount
if (MemoryCacheManager.getFixedLineOpenAmount() != null) {
openAmount = MemoryCacheManager.getFixedLineOpenAmount().getResult();
}
btnContinue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OmnitureHelper.trackEvent("My bill fixed pay");
OmnitureHelper.trackEvent("My bill fixed pay continue");
final double amount;
if (VFPreferences.getLanguage() == GlobalData.LANGUAGE_GR && VFPreferences.getAlphaUnavailableMessageGr().length() > 0) {
Dialogs.showDialog(getActivity(), VFPreferences.getAlphaUnavailableMessageGr());
} else if (VFPreferences.getLanguage() == GlobalData.LANGUAGE_EN && VFPreferences.getAlphaUnavailableMessageEn().length() > 0) {
Dialogs.showDialog(getActivity(), VFPreferences.getAlphaUnavailableMessageEn());
} else {
if (editAmount.getText().toString().length() > 0) {
amount = StaticTools.tryParseDouble(editAmount.getText().toString().replace(",", "."), PAYMENTFLAG);
//amount = StaticTools.tryParseDouble(editAmount.getText().toString(), PAYMENTFLAG);
final PaymentValidationError validation = validateAmount(editAmount.getText().toString());
if (currentAmount < amount) {
Runnable positiveRunnable = new Runnable() {
@Override
public void run() {
checkToProceedWithPayment(validation, amount);
}
};
Runnable negativeRunnable = new Runnable() {
@Override
public void run() {
}
};
Dialogs.advancedYesNoDialog(activity, getString(R.string.fixed_payment_user_amount_more_than_normal_amount), getString(R.string.my_vodafone), getString(R.string.ok), getString(R.string.cancel), positiveRunnable, negativeRunnable, true, true, true);
} else {
checkToProceedWithPayment(validation, amount);
}
} else {
if (currentAmount <= 0) {
Dialogs.showErrorDialog(activity, getString(R.string.bill_payment_invalid_message));
} else {
proceedToPayment(currentAmount);
}
}
}
}
});
}
private void checkToProceedWithPayment(PaymentValidationError validation, double amount) {
if (validation == PaymentValidationError.NEGATIVE_OR_ZERO || validation == PaymentValidationError.GENERIC
|| validation == PaymentValidationError.EMPTY || validation == PaymentValidationError.LESS_EXPIRED) {
Dialogs.showErrorDialog(activity, getString(R.string.bill_payment_invalid_message));
} else {
//TODO:handle validation LESS case
proceedToPayment(amount);
}
}
private void proceedToPayment(final double amount) {
if (amount != PAYMENTFLAG) {
if (amount < openAmount) {
Dialogs.simpleYesNoDialog(activity, String.format(getString(R.string.hol_pay_validation_smaller_than_expired_amount), StaticTools.formatNumber(openAmount, 2) + "€"), getString(R.string.my_vodafone), getString(R.string.wifi_settings_popup_message_button), getString(R.string.cancel), new Runnable() {
@Override
public void run() {
replaceFragment(FragmentFXLPayment.newInstance(amount));
}
});
} else {
replaceFragment(FragmentFXLPayment.newInstance(amount));
}
} else {
Dialogs.showErrorDialog(activity, getString(R.string.bill_payment_invalid_message));
}
}
@Override
public void onResume() {
super.onResume();
activity.sideMenuHelper.setToggle(getView().findViewById(R.id.toggleDrawer));
activity.sideMenuHelper.setBackButton(getView().findViewById(R.id.back), activity);
Dialogs.showProgress(activity);
FixedLinePaymentsManager.getAccountDetails(activity, new WeakReference<FixedLinePaymentsManager.FixedLinePaymentsListener>(this));
//BG
StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null);
}
@Override
public BackFragment getPreviousFragment() {
return BackFragment.FragmentMyAccountFixed;
}
@Override
public String getFragmentTitle() {
return getString(R.string.payment_top_label);
}
@Override
public void onSuccessFXLBilling(final VFModelFXLAccount model) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
try {
currentAmount = StaticTools.parseNumber(model.getTotal()).doubleValue();
} catch (Exception e) {
StaticTools.Log(e);
}
txtFullCurrentTotal.setText(StaticTools.formatNumber(currentAmount, 2) + "€");
editAmount.setHint(StaticTools.formatNumber(currentAmount, 2));
}
});
}
@Override
public void onSuccessFXLBillingHistory(String usageDates) {
}
@Override
public void onSuccessOpenAmount(String model) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
}
});
}
@Override
public void onPdfReady(Intent intent) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
}
});
}
@Override
public void onPdfError(int errorCode) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
});
}
@Override
public void onErrorFXLPayments(int errorCode) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
});
}
@Override
public void onGenericError() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
});
}
private PaymentValidationError validateAmount(String amountStr) {
PaymentValidationError error = PaymentValidationError.VALID;
if (amountStr == null || amountStr.equals(""))
return PaymentValidationError.EMPTY;
if (currentAmount != PAYMENTFLAG && openAmount != PAYMENTFLAG) {
double amount = 0;
if (amountStr.startsWith("-")) {
error = PaymentValidationError.NEGATIVE_OR_ZERO;
} else {
try {
amount = StaticTools.tryParseDouble(amountStr.replace(",", "."), PAYMENTFLAG);
} catch (Exception e) {
StaticTools.Log(e.toString());
error = PaymentValidationError.GENERIC;
}
}
if(amount!=PAYMENTFLAG) {
if (amount <= 0) {
error = PaymentValidationError.NEGATIVE_OR_ZERO;
} else if (amount > currentAmount) {
error = PaymentValidationError.VALID;
} else if (amount < currentAmount) {
error = PaymentValidationError.LESS;
}
}
else {
error = PaymentValidationError.GENERIC;
}
// This check removed and replaced by a message according to ticket VFGRMVUAT-2192
// if (amount > 0 && amount < openAmount) {
// error = PaymentValidationError.LESS_EXPIRED;
// }
} else {
error = PaymentValidationError.GENERIC;
}
return error;
}
enum PaymentValidationError {
GENERIC,
EMPTY,
NEGATIVE_OR_ZERO,
LARGER,
LESS,
LESS_EXPIRED,
VALID
}
}
|
package com.dl7.library.user;
import com.dl7.library.BaseResponse;
import com.dl7.library.OnRequestListener;
import com.dl7.library.utils.ServiceHelper;
import com.google.gson.Gson;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by long on 2016/5/11.
* 给客户端调用的接口
*/
public class UserService {
private static IUserService sUserService;
private UserService() {
throw new RuntimeException("UserService cannot be initialized!");
}
/**
* 初始化服务
*
* @param retrofit Retrofit
*/
public static void init(Retrofit retrofit) {
sUserService = retrofit.create(IUserService.class);
}
/**
* 调用流程
*/
public static void userInfo() {
// 创建Retrofit
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.yoururl.com/")
.build();
// 创建IUserService
sUserService = retrofit.create(IUserService.class);
// 创建请求
Call<BaseResponse> call = sUserService.user(10086);
// 执行请求
call.enqueue(new Callback<BaseResponse>() {
@Override
public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
Gson gson = new Gson();
try {
BaseResponse body = response.body();
// 先判断状态值
if (body.getStatus().equals("1")) {
// 将Object对象转化为json字符串
String jsonData = gson.toJson(body.getData());
// 将json字符串转化为对象实体
UserInfo info = gson.fromJson(jsonData, UserInfo.class);
// 判断解析是否成功
if (info == null) {
onFailure(call, new Throwable("对象解析失败"));
} else {
// 获取到数据,开始处理数据
}
} else {
onFailure(call, new Throwable(body.getMsg()));
}
} catch (Exception e) {
onFailure(call, e);
}
}
@Override
public void onFailure(Call<BaseResponse> call, Throwable t) {
// 失败处理
}
});
}
/**
* 获取实体列表
* @param param 参数
* @param listener 请求监听
* @return 通信回调接口,用来取消通信
*/
public static Call userList(String param, OnRequestListener<List<UserInfo>> listener) {
Call<BaseResponse> call = sUserService.userList(param);
ServiceHelper.callEntities(call, UserInfo.class, listener);
return call;
}
/**
* 获取单个实体
* @param id 参数
* @param listener 请求监听
* @return 通信回调接口,用来取消通信
*/
public static Call userInfo(int id, OnRequestListener<UserInfo> listener) {
Call<BaseResponse> call = sUserService.user(id);
ServiceHelper.callEntity(call, UserInfo.class, listener);
return call;
}
}
|
package mlxy.pickerchu;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import java.io.File;
import java.io.IOException;
import mlxy.utils.F;
/** Pika pika. */
public class PickerChu {
private Activity activity;
private Config config;
private File tempPhoto;
private Uri resultImage;
private PickerChu() {}
private PickerChu(Activity activity) {
this.activity = activity;
this.config = new Config(activity);
}
/** Take a photo. */
public void takePhoto() {
tempPhoto = F.createTempFile(activity, System.currentTimeMillis() + "");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempPhoto));
activity.startActivityForResult(intent, Constants.REQUEST_CODE_TAKE_PHOTO);
}
/** Pick a picture from gallery. */
public void pickPicture() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
activity.startActivityForResult(intent, Constants.REQUEST_CODE_PICK_PICTURE);
}
/** Handles <code>onActivityResult()</code> event. Must be called. */
public void handleActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) return;
switch (requestCode) {
case Constants.REQUEST_CODE_TAKE_PHOTO:
if (tempPhoto != null) {
if (config.needToCrop) {
crop(Uri.fromFile(tempPhoto));
} else {
photoAsResult(tempPhoto);
}
}
break;
case Constants.REQUEST_CODE_PICK_PICTURE:
if (data != null && data.getData() != null) {
if (config.needToCrop) {
crop(data.getData());
} else {
pictureAsResult(data.getData());
}
}
break;
case Constants.REQUEST_CODE_CROP:
deliverResult();
break;
}
}
// Sorry dad we're so ugly and would better go die.
private void photoAsResult(File photo) {
try {
createResultImageFile();
F.copy(photo, new File(resultImage.getPath()));
} catch (IOException e) {
e.printStackTrace();
}
deliverResult();
}
// Agreed.
private void pictureAsResult(Uri uri) {
resultImage = uri;
deliverResult();
}
/** Crop image. */
private void crop(Uri imageUri) {
try {
createResultImageFile();
Intent intent = prepareCropIntent(imageUri);
activity.startActivityForResult(intent, Constants.REQUEST_CODE_CROP);
} catch (IOException e) {
e.printStackTrace();
}
}
/** Create file to store cropped image. */
private void createResultImageFile() throws IOException {
File resultImageFile = new File(config.saveIn, System.currentTimeMillis()+".png");
F.delete(resultImageFile);
F.create(resultImageFile);
resultImage = Uri.fromFile(resultImageFile);
}
/** Setup a intent for cropping. */
private Intent prepareCropIntent(Uri photoUri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoUri, "image/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, resultImage);
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("aspectX", config.aspectX);
intent.putExtra("aspectY", config.aspectY);
intent.putExtra("outputX", config.outputX);
intent.putExtra("outputY", config.outputY);
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
intent.putExtra("noFaceDetection", true);
intent.putExtra("return-data", false);
return intent;
}
/** Delete temp photo and callback. */
private void deliverResult() {
F.delete(tempPhoto);
callListener();
}
/** Callback. */
private void callListener() {
if (config.onImageCroppedListener != null && config.saveIn != null) {
config.onImageCroppedListener.onImageCropped(resultImage);
}
}
/** PickerChu's builder. */
public static class Builder {
private Config config;
public Builder(Activity activity) {
config = new Config(activity);
}
/** <p>If needs to crop images. </p> */
public Builder needToCrop(boolean needToCrop) {
config.needToCrop = needToCrop;
return this;
}
/** Save images cropped in <code>dir</code>.
*
* <p>Use <code>SDCard/Android/data/<package_name>/files/Pictures/</code> <br>
* or <code>/data/data/<package_name>/files/</code> <br>
* for <code>dir</code> by default depending on SDCard status. </p>*/
public Builder saveIn(File dir) {
config.saveIn = dir;
return this;
}
/** <p>Crop images by ratio <code>ratioX</code>:<code>ratioY</code>. </p>
*
* <p>1:1 by default. </p> */
public Builder byAspectRatioOf(int ratioX, int ratioY) {
config.aspectX = ratioX;
config.aspectY = ratioY;
return this;
}
/** <p>Scale image cropped to <code>width</code> and <code>height</code>. </p>
*
* <p>(512, 512) by default. </p>*/
public Builder inSizeOf(int width, int height) {
config.outputX = width;
config.outputY = height;
return this;
}
/** Notify <code>onImageCroppedListener</code> when image cropped. */
public Builder onImageCropped(OnImageCroppedListener onImageCroppedListener) {
config.onImageCroppedListener = onImageCroppedListener;
return this;
}
/** I choose you! <b>PickerChu</b>! */
public PickerChu build() {
PickerChu pickerChu = new PickerChu(config.activity);
pickerChu.config = config;
return pickerChu;
}
}
/** PickerChu's configurations. */
static class Config {
Activity activity;
boolean needToCrop;
File saveIn;
int aspectX;
int aspectY;
int outputX;
int outputY;
OnImageCroppedListener onImageCroppedListener;
public Config(Activity activity) {
initByDefault(activity);
}
void initByDefault(Activity activity) {
this.activity = activity;
needToCrop = true;
saveIn = F.getFileDir(activity);
aspectX = 1;
aspectY = 1;
outputX = 512;
outputY = 512;
onImageCroppedListener = null;
}
}
public interface OnImageCroppedListener {
void onImageCropped(Uri imageUri);
}
public void reset() {
config = new Config(activity);
}
/*=======================Setters & Getters=======================*/
public void setNeedToCrop(boolean needToCrop) {
config.needToCrop = needToCrop;
}
public boolean needToCrop() {
return config.needToCrop;
}
public void setSaveTo(File dir) {
config.saveIn = dir;
}
public File getSaveTo() {
return config.saveIn;
}
public void setAspectRatio(int ratioX, int ratioY) {
config.aspectX = ratioX;
config.aspectY = ratioY;
}
public int getAspectRatioX() {
return config.aspectX;
}
public int getAspectRatioY() {
return config.aspectY;
}
public void setSize(int width, int height) {
config.outputX = width;
config.outputY = height;
}
public int getOutputWidth() {
return config.outputX;
}
public int getOutputHeight() {
return config.outputY;
}
public void setOnImageCroppedListener(OnImageCroppedListener onImageCroppedListener) {
config.onImageCroppedListener = onImageCroppedListener;
}
public OnImageCroppedListener getOnImageCroppedListener() {
return config.onImageCroppedListener;
}
/*=======================Setters & Getters=======================*/
}
|
package com.CDH.myapplication.ui.fragments;
import androidx.lifecycle.ViewModelProviders;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.CDH.myapplication.R;
import com.CDH.myapplication.ui.Datos.DbHelper;
import com.CDH.myapplication.ui.vistas.PlanillaFragment2ViewModel;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class planillaFragment2 extends Fragment {
private PlanillaFragment2ViewModel mViewModel;
EditText desayunotxt, almuerzotxt, cenatxt, aguatxt, alojamientotxt, combustibletxt,peajetxt, estacionamientotxt;
TextView total1, total2;
DbHelper FavDB;
public static planillaFragment2 newInstance() {
return new planillaFragment2();
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View vista= inflater.inflate(R.layout.planilla_fragment2_fragment, container, false);
desayunotxt = (EditText) vista.findViewById(R.id.editTextDesayuno);
almuerzotxt = (EditText) vista.findViewById(R.id.editTextAlmuerzo);
cenatxt = (EditText) vista.findViewById(R.id.editTextCena);
aguatxt = (EditText) vista.findViewById(R.id.editTextAgua);
alojamientotxt = (EditText) vista.findViewById(R.id.editTextAlojamiento);
combustibletxt = (EditText) vista.findViewById(R.id.editTextCombustible);
peajetxt =(EditText) vista.findViewById(R.id.editTextPeaje);
estacionamientotxt = (EditText) vista.findViewById(R.id.editTextEstacionamiento);
/* desayunotxt.setText("0");
almuerzotxt.setText("0");
cenatxt.setText("0");
estacionamientotxt.setText("0");
aguatxt.setText("0");
alojamientotxt.setText("0");
combustibletxt.setText("0");
peajetxt.setText("0");*/
total1 = (TextView) vista.findViewById(R.id.textNumero);
total2 = (TextView) vista.findViewById(R.id.textNumero2);
FavDB = new DbHelper(vista.getContext());
Bundle bundle = getArguments();
if(bundle!=null ){
if(bundle.getString("mod").equals("1")){
String codigo = getArguments().getString("codigo");
buscaFactura("http://192.168.56.1/wappservice/buscar_ficha.php?cod="+codigo+"");
}else{
rellena(getArguments().getString("codigo"));
}
}
desayunotxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(desayunotxt.getText().toString().equals("")){
desayunotxt.setText("0");
}else {
total1.setText(suma());
}
}
}
});
almuerzotxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(almuerzotxt.getText().toString().equals("")){
almuerzotxt.setText("0");
}else {
total1.setText(suma());
}
}
}
});
cenatxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(cenatxt.getText().toString().equals("")){
cenatxt.setText("0");
}else {
total1.setText(suma());
}
}
}
});
aguatxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(aguatxt.getText().toString().equals("")){
aguatxt.setText("0");
}else {
total1.setText(suma());
}
}
}
});
alojamientotxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(alojamientotxt.getText().toString().equals("")){
alojamientotxt.setText("0");
}else {
total1.setText(suma());
}
}
}
});
combustibletxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(combustibletxt.getText().toString().equals("")){
combustibletxt.setText("0");
}else {
total2.setText(suma2());
}
}
}
});
peajetxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(combustibletxt.getText().toString().equals("")){
combustibletxt.setText("0");
}else {
total2.setText(suma2());
}
}
}
});
estacionamientotxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if(combustibletxt.getText().toString().equals("")){
combustibletxt.setText("0");
}else {
total2.setText(suma2());
}
}
}
});
return vista;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(this).get(PlanillaFragment2ViewModel.class);
// TODO: Use the ViewModel
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Button button6=view.findViewById(R.id.btnA1);
button6.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String codigo = getArguments().getString("codigo");
Bundle bundle = getArguments();
bundle.putString("codigo", codigo);
agregabdd(codigo);
if(bundle.getString("mod").equals("1")){
ejecutarServicio("http://192.168.56.1/wappservice/modifica2.php",codigo);
Navigation.findNavController(v).navigate(R.id.plantillafragment1_buscar,bundle);
}else{
Navigation.findNavController(v).navigate(R.id.plantillafragment1,bundle);
}
}
});
Button button5=view.findViewById(R.id.btnS1);
button5.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String codigo = getArguments().getString("codigo");
Bundle bundle = getArguments();
bundle.putString("codigo", codigo);
agregabdd(codigo);
if(bundle.getString("mod").equals("1")){
ejecutarServicio("http://192.168.56.1/wappservice/modifica2.php",codigo);
Navigation.findNavController(v).navigate(R.id.planillaFragment3,bundle);
}else{
Navigation.findNavController(v).navigate(R.id.planillaFragment3,bundle);
}
}
});
}
private String suma(){
int desayuno = Integer.parseInt(desayunotxt.getText().toString());
int almuerzo = Integer.parseInt(almuerzotxt.getText().toString());
int cena = Integer.parseInt(cenatxt.getText().toString());
int agua = Integer.parseInt(aguatxt.getText().toString());
int alojamiento = Integer.parseInt(alojamientotxt.getText().toString());
int total=desayuno+almuerzo+cena+agua+alojamiento;
return String.valueOf(total);
}
private String suma2(){
int combustible = Integer.parseInt(combustibletxt.getText().toString());
int peaje = Integer.parseInt(peajetxt.getText().toString());
int estacionamiento = Integer.parseInt(estacionamientotxt.getText().toString());
int total=combustible+peaje+estacionamiento;
return String.valueOf(total);
}
private void rellena(String codigo){
if (FavDB.if_exist(codigo)) {
SQLiteDatabase db = FavDB.getReadableDatabase();
Cursor cursor = FavDB.read_all_data(codigo);
try {
while (cursor.moveToNext()) {
if(cursor.getString(cursor.getColumnIndex(FavDB.DESAYUNO))==null && cursor.getString(cursor.getColumnIndex(FavDB.ALMUERZO))== null && cursor.getString(cursor.getColumnIndex(FavDB.CENA))==null &&
cursor.getString(cursor.getColumnIndex(FavDB.AGUA))==null && cursor.getString(cursor.getColumnIndex(FavDB.ALOJAMIENTO))==null && cursor.getString(cursor.getColumnIndex(FavDB.COMBUSTIBLE))==null && cursor.getString(cursor.getColumnIndex(FavDB.PEAJE))==null &&
cursor.getString(cursor.getColumnIndex(FavDB.ESTACIONAMIENTO))== null){
desayunotxt.setText("0");
almuerzotxt.setText("0");
cenatxt.setText("0");
estacionamientotxt.setText("0");
aguatxt.setText("0");
alojamientotxt.setText("0");
combustibletxt.setText("0");
peajetxt.setText("0");
total1.setText(suma());
total2.setText(suma2());
}else {
desayunotxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.DESAYUNO)));
almuerzotxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.ALMUERZO)));
cenatxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.CENA)));
aguatxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.AGUA)));
alojamientotxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.ALOJAMIENTO)));
combustibletxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.COMBUSTIBLE)));
peajetxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.PEAJE)));
estacionamientotxt.setText(cursor.getString(cursor.getColumnIndex(FavDB.ESTACIONAMIENTO)));
total1.setText(suma());
total2.setText(suma2());
}
//suma
}
} finally {
if (cursor != null && cursor.isClosed())
cursor.close();
db.close();
}
}
}
private void buscaFactura(String URL){
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
//codigoTXT.setText(jsonObject.getString(""));
desayunotxt.setText(jsonObject.getString("Desayuno"));
almuerzotxt.setText(jsonObject.getString("Almuerzo"));
cenatxt.setText(jsonObject.getString("Cena"));
aguatxt.setText(jsonObject.getString("Agua"));
alojamientotxt.setText(jsonObject.getString("Alojamiento"));
combustibletxt.setText(jsonObject.getString("Combustible"));
peajetxt.setText(jsonObject.getString("Peaje"));
estacionamientotxt.setText(jsonObject.getString("Estacionamiento"));
} catch (JSONException e) {
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error de conexion ", Toast.LENGTH_SHORT).show();
}
}
);
RequestQueue requestQueue= Volley.newRequestQueue(this.getContext());
requestQueue.add(jsonArrayRequest);
}
private void agregabdd(String codigo) {
if (!desayunotxt.getText().toString().equals("")) {
int desayuno = Integer.parseInt(desayunotxt.getText().toString());
int almuerzo = Integer.parseInt(almuerzotxt.getText().toString());
int cena = Integer.parseInt(cenatxt.getText().toString());
int agua = Integer.parseInt(aguatxt.getText().toString());
int alojamiento = Integer.parseInt(alojamientotxt.getText().toString());
int combustible = Integer.parseInt(combustibletxt.getText().toString());
int peaje = Integer.parseInt(peajetxt.getText().toString());
int estacionamiento = Integer.parseInt(estacionamientotxt.getText().toString());
//(String codigo,int desayuno, int almuerzo, int cena, int agua, int alojamiento, int combustible, int peaje, int estacionamiento)
FavDB.add_parts(codigo, desayuno, almuerzo, cena, agua, alojamiento, combustible, peaje, estacionamiento);
}
}
private void ejecutarServicio(String URL,final String codigo){
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getActivity(), "PASO "+almuerzotxt.getText().toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "No Paso", Toast.LENGTH_SHORT).show();
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parametros=new HashMap<String, String>();
parametros.put("cod",codigo);
parametros.put("desayuno",desayunotxt.getText().toString());
parametros.put("almuerzo",almuerzotxt.getText().toString());
parametros.put("cena",cenatxt.getText().toString());
parametros.put("agua",aguatxt.getText().toString());
parametros.put("alojamiento",alojamientotxt.getText().toString());
parametros.put("combustible",combustibletxt.getText().toString());
parametros.put("peaje",peajetxt.getText().toString());
parametros.put("estacionamiento",estacionamientotxt.getText().toString());
return parametros;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this.getContext());
requestQueue.add(stringRequest);
}
}
|
package no.nav.vedtak.log.metrics;
public interface LivenessAware {
boolean isAlive();
}
|
import java.util.Scanner;
/**
* Created by Administrator on 2017/8/20.
*/
public class chapter5_6 {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int[] arr = new int[5];
int sum = 0;
for(int i=0;i<arr.length;i++){
System.out.println("请输入第"+(i+1)+"学生的成绩");
arr[i] = in.nextInt();
sum += arr[i];
}
System.out.println("5个学生的平均分为"+sum/5);
}
}
|
package serve.serveup.views.restaurant;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import serve.serveup.R;
import serve.serveup.dataholder.RestaurantInfo;
import serve.serveup.utils.ContentStore;
import serve.serveup.utils.adapters.FoodTypesAdapter;
public class RestaurantActivity extends AppCompatActivity {
private TextView imeRestavracijeText;
private ImageView backButton;
private TextView cenaText;
private RecyclerView foodRecyclerView;
private FoodTypesAdapter foodRecyclerAdapter;
private LinearLayoutManager linearLayoutManager;
private ArrayList<String> foodTypes;
private RestaurantInfo pickedRestaurant;
private LinearLayout goToBasketButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_restaurant);
imeRestavracijeText = findViewById(R.id.imeRestavracijeText);
foodRecyclerView = findViewById(R.id.foodTypesRecyclerview);
cenaText = findViewById(R.id.cenaText);
backButton = findViewById(R.id.backIcon);
goToBasketButton = findViewById(R.id.goToBasketButton);
foodTypes = new ArrayList<>();
populateFoodTypes();
Bundle getBundle = getIntent().getExtras();
if (getBundle != null) {
pickedRestaurant = (RestaurantInfo) getBundle.getSerializable("restaurant_info");
imeRestavracijeText.setText(pickedRestaurant.getImeRestavracije());
}
// Initialize the view components
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
foodRecyclerAdapter = new FoodTypesAdapter(foodTypes, pickedRestaurant);
// Set the layout manager and the adapter of the Recycler View
foodRecyclerView.setLayoutManager(linearLayoutManager);
foodRecyclerView.setAdapter(foodRecyclerAdapter);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
// TODO: go to BasketFragment
// goToBasketButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//
// }
// });
}
@Override
protected void onStart() {
super.onStart();
updateOverallCenaText();
}
private void populateFoodTypes() {
//foodTypes.add(getResources().getString(R.string.kosila));
foodTypes.add(getResources().getString(R.string.glavne_jedi));
foodTypes.add(getResources().getString(R.string.juhe));
foodTypes.add(getResources().getString(R.string.solate));
foodTypes.add(getResources().getString(R.string.sladice));
foodTypes.add(getResources().getString(R.string.pijace));
}
private void updateOverallCenaText() {
ContentStore cntStore = new ContentStore(getApplicationContext());
float overAllPrice = cntStore.getSession().getOverAllPrice();
cenaText.setText(String.format("%.2f €", overAllPrice));
}
}
|
package com.mindstatus.bean.vo;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
/**
* MsPropList entity.
*
* @author MyEclipse Persistence Tools
*/
public class MsPropList implements java.io.Serializable
{
private static final long serialVersionUID = 1675236065672623624L;
private Integer id;
private Integer propTypeId;
private Integer propListId;
private String propListName;
private String memo;
// Constructors
/** default constructor */
public MsPropList()
{
}
/** minimal constructor */
public MsPropList(Integer id)
{
this.id = id;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer id)
{
this.id = id;
}
public Integer getPropTypeId()
{
return this.propTypeId;
}
public void setPropTypeId(Integer propTypeId)
{
this.propTypeId = propTypeId;
}
public Integer getPropListId()
{
return this.propListId;
}
public void setPropListId(Integer propListId)
{
this.propListId = propListId;
}
public String getPropListName()
{
return this.propListName;
}
public void setPropListName(String propListName)
{
this.propListName = propListName;
}
public String getMemo()
{
return this.memo;
}
public void setMemo(String memo)
{
this.memo = memo;
}
public String toString()
{
return ReflectionToStringBuilder.toString(this);
}
}
|
package com.huawei.cost.mapper;
import com.huawei.cost.domain.Cost;
import com.huawei.base.utils.PageBean;
import java.util.List;
/**
* Created by dllo on 17/11/11.
*/
public interface CostMapper {
int save(Cost cost);
int startCost(Cost cost);
int deleteCost(int id);
Cost findSingle(int id);
int updateCost(Cost cost);
int findCount();
List<Cost> findAll(PageBean<Cost> pageBean);
List<Cost> findByCostOrder(PageBean<Cost> pageBean);
Cost findByCost(Cost cost);
}
|
package com.gome.manager.dao;
import java.util.List;
import com.gome.manager.domain.Answer;
import com.gome.manager.domain.ObjectBean;
import com.gome.manager.domain.Question;
import com.gome.manager.domain.Replay;
import com.gome.manager.domain.Selecter;
/**
*
* 会议dao接口.
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 caowei 新建
* </pre>
*/
public interface MeetingSelectMapper {
ObjectBean queryObjectBean(ObjectBean objectBean);
List<Question> queryQuestion(Question question);
List<Selecter> querySelecter(Selecter selecter);
void addAnswer(Answer answer);
String queryPerSelectResult(Answer answer);
Object addReplay(Replay replay);
String queryAllAnswer(Answer answer);
String querySelecterAnswer(Answer answer);
List<Answer> queryAnswerContent(Answer answer);
}
|
package fr.univ_rennes1.istic.sit.groupe2.back_sit.amqp;
import com.fasterxml.jackson.databind.ObjectMapper;
import fr.univ_rennes1.istic.sit.groupe2.back_sit.dao.MissionDao;
import fr.univ_rennes1.istic.sit.groupe2.back_sit.dao.PositionDao;
import fr.univ_rennes1.istic.sit.groupe2.back_sit.models.Mission;
import fr.univ_rennes1.istic.sit.groupe2.back_sit.models.Position;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author VinYarD
* created : 14/02/2019, 11:33
*/
public class PositionReceiver {
Logger log = Logger.getLogger(MissionReceiver.class.getName());
@Autowired
ObjectMapper objectMapper;
@Autowired
private PositionDao positionDao;
@RabbitListener(queues = "#{positionQueue.name}")
public void receivePosition(String json) throws InterruptedException {
try {
Position mission = objectMapper.readValue(json, Position.class);
positionDao.save(mission);
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
}
}
}
|
package com.sirma.itt.javacourse.chat.server.manager;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.sirma.itt.javacourse.chat.common.ChatUser;
import com.sirma.itt.javacourse.chat.common.MessageInterpreter;
import com.sirma.itt.javacourse.chat.common.MessageType;
import com.sirma.itt.javacourse.chat.common.exceptions.ChatException;
import com.sirma.itt.javacourse.chat.server.interfaces.ServerSideController;
import com.sirma.itt.javacourse.chat.server.threads.ClientListenerThread;
/**
* User manager that keeps an accurate list of the current users that are logged
* on to the server.
*
*
* @author siliev
*
*/
public class UserManager {
private static final Logger LOGGER = Logger.getLogger(UserManager.class);
private Map<String, ClientListenerThread> userMap;
private List<ClientListenerThread> tempHolder;
private MessageInterpreter interpretator;
private ChatRoomManager chatRoomManager;
private ServerSideController controler;
/**
* Private constructor.
*
* @param controler
* text area of the main UI to display the disconnected users.
*/
public UserManager(ServerSideController controler) {
userMap = new HashMap<String, ClientListenerThread>();
tempHolder = new ArrayList<ClientListenerThread>();
chatRoomManager = new ChatRoomManager();
interpretator = new ServerMessageInterpreter(this, chatRoomManager);
this.controler = controler;
}
public ChatRoomManager getChatRoomManager() {
return chatRoomManager;
}
public void setChatRoomManager(ChatRoomManager chatRoomManager) {
this.chatRoomManager = chatRoomManager;
}
public Map<String, ClientListenerThread> getUserMap() {
return userMap;
}
public void setUserMap(Map<String, ClientListenerThread> userMap) {
this.userMap = userMap;
}
public List<ClientListenerThread> getTempHolder() {
return tempHolder;
}
public void setTempHolder(List<ClientListenerThread> tempHolder) {
this.tempHolder = tempHolder;
}
public void setInterpretator(MessageInterpreter interpretator) {
this.interpretator = interpretator;
}
/**
* Adds a {@link ChatUser} to the map of users.
*
* @param user
* the user to be added to the map.
* @return true if the user was added false if there is a user with the same
* name logged on.
*/
public boolean addUser(ClientListenerThread user) {
if (isValidName(user.getUser().getUsername())) {
userMap.put(user.getUser().getUsername(), user);
return true;
} else {
return false;
}
}
/**
* Removes a user from the map.
*
* @param user
* the user to be removed.
*/
public void removeUser(ChatUser user) {
userMap.remove(user.getUsername());
}
/**
* Checks if there is a user on the server with the given username.
*
* @param userName
* the username we want to check.
* @return true if there is no user with the given username, false if there
* is a user with this username.
*/
public boolean isValidName(String userName) {
if (!userName.equals(null) && userName.contains("[")
|| userName.contains("]")) {
return false;
}
if (userMap.keySet() != null) {
for (String key : userMap.keySet()) {
if (key.equalsIgnoreCase(userName)) {
return false;
}
}
}
return true;
}
/**
* Retrieves a {@link ChatUser} from the manager.
*
* @param userName
* the user we want to retrieve by given user name.
* @return the {@link ChatUser} object or null if there is no user with this
* username.
*/
public ClientListenerThread getUser(String userName) {
return userMap.get(userName);
}
/**
* Starts the process of registering the user to the server.
*
* @param client
* the client to be registered.
*/
public void acceptUser(Socket client) {
ChatUser user = new ChatUser(null, client);
ClientListenerThread listener;
try {
listener = new ClientListenerThread(user, this);
listener.start();
tempHolder.add(listener);
} catch (ChatException e) {
LOGGER.error(e.getMessage(), e);
}
}
/**
* Retrieves the current {@link MessageInterpreter}.
*
*
* @return the message interpreter.
*/
public MessageInterpreter getInterpretator() {
return interpretator;
}
/**
* Registers a user on the server and sends him the current user list and
* the common room chat.
*
* @param user
* the user to be registered on the server.
*/
public void registerUser(ChatUser user) {
for (ClientListenerThread thread : tempHolder) {
if (thread.getUser().equals(user)) {
tempHolder.remove(thread);
userMap.put(user.getUsername(), thread);
LOGGER.info("Registering user " + user.getUsername());
thread.sendMessage(interpretator.generateMessage(
MessageType.APPROVED, 0,
thread.getUser().getUsername(), thread.getUser()
.getUsername()));
thread.sendMessage(interpretator.generateMessage(
MessageType.STARTCHAT, chatRoomManager.getCommonRoom()
.getId(), chatRoomManager.getCommonRoom()
.getUsers().toString(), MessageType.SERVER
.toString()));
break;
}
}
}
/**
* Rejects the user for invalid user name.
*
* @param user
* the user to send a {@link TYPE.REFUSED}.
*/
public void rejectUser(ChatUser user) {
for (ClientListenerThread thread : tempHolder) {
if (thread.getUser().getUsername().equals(user.getUsername())) {
LOGGER.info("Rejecting user " + user.getUsername());
thread.sendMessage(interpretator.generateMessage(
MessageType.REFUSED, 0,
"The user name you entered is invalid : "
+ thread.getUser().getUsername(),
MessageType.SERVER.toString()));
break;
}
}
}
/**
* Returns the {@link ClientListenerThread} that is associated with a
* client.
*
* @param name
* the name of the client we are looking for.
* @return the thread that is associated with a client.
*/
public ClientListenerThread getClientThreadByName(String name) {
return userMap.get(name);
}
/**
* Retrieves the user list of registered users on the server.S
*
*
* @return the list of connected users that are on the server.
*/
public List<String> getUserList() {
List<String> list = new ArrayList<String>(userMap.keySet());
return list;
}
/**
* Disconnects the user from the chats he is into.
*
* @param user
* removes the user from chats.
*/
public void disconnectUser(ClientListenerThread user) {
chatRoomManager.removeUserFromChats(user);
displayMessage("User has disconnected.");
}
/**
* Displays an information message on to the server UI.
*
* @param message
* the message we want to display on to the UI.
*/
public void displayMessage(String message) {
controler.displayMessage(message);
}
/**
* Disconnects all users from the server.
*/
public void disconnectAllUsers() {
for (Entry<String, ClientListenerThread> user : userMap.entrySet()) {
user.getValue().disconnect();
}
}
}
|
package com.github.iam20.device.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TempHumid {
double celsius;
double humid;
}
|
package com.test.base;
import com.test.SolutionA;
import com.test.SolutionB;
import junit.framework.TestCase;
public class Example extends TestCase
{
private Solution solution;
@Override
protected void setUp()
throws Exception
{
super.setUp();
}
public void testSolutionA()
{
solution = new SolutionA();
assertSolution();
}
public void testSolutionB()
{
solution = new SolutionB();
assertSolution();
}
private void assertSolution()
{
assertEquals(3, solution.singleNumber(new int[] {2, 2, 3, 2}));
assertEquals(99, solution.singleNumber(new int[] {0, 1, 0, 1, 0, 1, 99}));
assertEquals(4, solution.singleNumber(new int[] {-2, -2, 1, 1, -3, 1, -3, -3, 4, -2}));
assertEquals(-4, solution.singleNumber(new int[] {-2, -2, 1, 1, -3, 1, -3, -3, -4, -2}));
assertEquals(1, solution.singleNumber(new int[] {-2147483648, -2147483648, -2147483648, 1}));
assertEquals(2147483647,
solution.singleNumber(new int[] {43, 16, 45, 89, 45, -2147483648, 45, 2147483646, -2147483647, -2147483648,
43, 2147483647, -2147483646, -2147483648, 89, -2147483646, 89, -2147483646, -2147483647, 2147483646,
-2147483647, 16, 16, 2147483646, 43}));
}
@Override
protected void tearDown()
throws Exception
{
super.tearDown();
}
}
|
package ch.erp.management.mvp.contract;
import ch.erp.management.mvp.base.BaseModel;
import ch.erp.management.mvp.base.BasePresenter;
import ch.erp.management.mvp.base.BaseView;
/**
* 启动页-Contract
*/
public interface MStartUpContract {
/**
* 启动页-IView
*/
interface MStartUpIView extends BaseView {
/**
* 进入主页
*/
void delayedJump();
}
/**
* 启动页-Presenter
*/
abstract class MIStartUpActivityP extends BasePresenter<MStartUpIView>{
/**
* 延时进入下一页
*/
protected abstract void delayedJumpMain();
}
/**
* 启动页-Model
*/
abstract class MIStartUpModel extends BaseModel {
}
}
|
package enumrated_datatype;
public class AnnotationDemo
{
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Child c=new Child();
c.turn();
}
}
class Parent
{
public void get()
{
System.out.println("hello in Parent");
}
}
class Child extends Parent
{
@Override
public void get()
{
System.out.println("hello in Child");
}
@Deprecated
void turn()
{
System.out.println("don't use this method ");
}
}
|
package com.liuzhenkun.cms.dao;
import com.liuzhenkun.cms.entity.ArticleVote;
public interface ArticleVoteDao extends BaseDao<ArticleVote>{
}
|
package com.w2a.listeners;
import java.io.IOException;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
import com.relevantcodes.extentreports.LogStatus;
import com.w2a.base.TestBase;
import com.w2a.utilities.TestUtil;
public class CustomListeners extends TestBase implements ITestListener{
public void onTestStart(ITestResult result) {
TestBase.test.log(LogStatus.PASS,result.getName().toUpperCase());
}
public void onTestSuccess(ITestResult result) {
TestBase.test.log(LogStatus.PASS,result.getName().toUpperCase()+"PASS");
reo.endTest(test);
reo.flush();
}
public void onTestFailure(ITestResult result) {
System.setProperty("org.uncommons.reportng.escape-ouput", "false");
Reporter.log("login Successfully executed");
try {
TestUtil.captureScreenshot();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TestBase.test.log(LogStatus.FAIL,result.getName().toUpperCase()+"FAIL");
TestBase.test.log(LogStatus.FAIL,test.addScreenCapture(TestUtil.screenshotName));
Reporter.log("<a target=\"_blank\" href = \"C:\\Users\\Shreya Kardekar\\Pictures\\error.jpg\">Screenshot</a>");
Reporter.log("<br>");
Reporter.log("<a target=\"_blank\" href = \"C:\\Users\\Shreya Kardekar\\Pictures\\error.jpg\">Screenshot</a>");
reo.endTest(test);
reo.flush();
}
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext context) {
}
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
}
}
|
/*
* 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.
*/
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import utils.Calculator;
/**
*
* @author nguyenhongphat0
*/
public class CalculatorTest {
public CalculatorTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
// @Test
// public void hello() {}
@Test
public void test() {
assertEquals(4, Calculator.sqr(2));
}
@Test
public void anotherTest() {
assertEquals(9, Calculator.sqr(3));
}
}
|
package com.culturaloffers.maps.repositories;
import com.culturaloffers.maps.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
User findByUsername(String username);
User findByEmailAddress(String emailAddress);
Page<User> findAll(Pageable pageable);
}
|
package com.prep.algorithm.astar;
import java.util.ArrayList;
import java.util.List;
public class Path {
private List<Node> waypoints = new ArrayList<Node>();
public Node getWaypoints(int index) {
return waypoints.get(index);
}
public int getX(int index){
return getWaypoints(index).getX();
}
public int getY(int index){
return getWaypoints(index).getY();
}
public int getLength(){
return waypoints.size();
}
public void appedWayPoint(Node n){
waypoints.add(n);
}
public void preprenWayPoint(Node n){
waypoints.add(0, n);
}
public boolean contains(int x,int y){
for(Node node:waypoints){
if(node.getX() == x && node.getY() == y ){
return true;
}
}
return false;
}
}
|
package Task1;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by Denis Prokhorin on 12.03.2018.
*/
public class FigureTest {
Figure figure;
@Before
public void init(){
figure= new Figure();
}
@After
public void remove(){
figure=null;
}
@Test
public void drawRectangle() throws Exception {
System.out.println("Rectangle:");
figure.drawRectangle(4, 5);
System.out.println();
}
@Test
public void drawRightTriangle() throws Exception {
System.out.println("Right Rectangle:");
figure.drawRightTriangle(4,4);
System.out.println();
}
@Test
public void drawEquilateralTriangle() throws Exception {
System.out.println("EquilateralTriangle");
figure.drawEquilateralTriangle(5);
System.out.println();
}
@Test
public void drawRhomb() throws Exception {
System.out.println("Rhomb:");
figure.drawRhomb(3);
System.out.println();
}
}
|
package tool.exception;
/**
* 自定义异常,在请求错误时发生,对应了HTTP 400 Bad Request错误
*/
public class BadRequestException extends Exception {
private static final long serialVersionUID = 1L;
/**
* 带参数的构造函数
* @param msg 错误信息
*/
public BadRequestException(String msg) {
super(msg);
}
/**
* 默认构造函数
*/
public BadRequestException() {
super("Bad Request");
}
}
|
package com.atguigu.gmall.product.service.impl;
import com.atguigu.gmall.model.product.SpuImage;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.product.mapper.SpuImageMapper;
import com.atguigu.gmall.product.mapper.SpuSaleAttrMapper;
import com.atguigu.gmall.product.service.SkuInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SkuInfoServiceImpl implements SkuInfoService {
@Autowired
SpuImageMapper spuImageMapper;
@Autowired
SpuSaleAttrMapper spuSaleAttrMapper;
@Override
public List<SpuImage> getSpuImageList(Long spuId) {
QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("spu_id", spuId);
return spuImageMapper.selectList(queryWrapper);
}
@Override
public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
}
}
|
/* */ package test.data;
/* */
/* */ import java.io.Serializable;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class PlayerHotInfo
/* */ implements Serializable
/* */ {
/* */ private static final long serialVersionUID = 1L;
/* */ private String name;
/* */ private String teamName;
/* */ private String position;
/* */ private String field;
/* */ private double value;
/* */ private double upgradeRate;
/* */
/* */ public String getName()
/* */ {
/* 42 */ return this.name;
/* */ }
/* */
/* 45 */ public void setName(String name) { this.name = name; }
/* */
/* */ public String getTeamName() {
/* 48 */ return this.teamName;
/* */ }
/* */
/* 51 */ public void setTeamName(String teamName) { this.teamName = teamName; }
/* */
/* */ public String getPosition() {
/* 54 */ return this.position;
/* */ }
/* */
/* 57 */ public void setPosition(String position) { this.position = position; }
/* */
/* */ public String getField() {
/* 60 */ return this.field;
/* */ }
/* */
/* 63 */ public void setField(String field) { this.field = field; }
/* */
/* */ public double getValue() {
/* 66 */ return this.value;
/* */ }
/* */
/* 69 */ public void setValue(double value) { this.value = value; }
/* */
/* */ public double getUpgradeRate() {
/* 72 */ return this.upgradeRate;
/* */ }
/* */
/* 75 */ public void setUpgradeRate(double upgradeRate) { this.upgradeRate = upgradeRate; }
/* */
/* */
/* */
/* */ public String toString()
/* */ {
/* 81 */ StringBuilder stringBuilder = new StringBuilder();
/* 82 */ String ln = "\n";
/* 83 */ stringBuilder.append(getName()).append(ln);
/* 84 */ stringBuilder.append(getTeamName()).append(ln);
/* 85 */ stringBuilder.append(getPosition()).append(ln);
/* 86 */ stringBuilder.append(getField()).append(ln);
/* 87 */ stringBuilder.append(getValue()).append(ln);
/* 88 */ stringBuilder.append(getUpgradeRate()).append(ln);
/* 89 */ return stringBuilder.toString();
/* */ }
/* */ }
/* Location: G:\学习课件\软件工程与计算3\测试相关文档\docs\功能测试\testData.jar!\test\data\PlayerHotInfo.class
* Java compiler version: 7 (51.0)
* JD-Core Version: 0.7.1
*/
|
package com.joalib.board.action;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.Action;
import org.apache.ibatis.session.SqlSession;
import com.joalib.DTO.ActionForward;
import com.joalib.DTO.BoardDTO;
import com.joalib.board.svc.BoardWriteProService;
import java.util.Calendar;
import java.util.Date;
public class BoardWriteProAction implements dbAction {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
Date date= new Date();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd");
String board_date = simpleDate.format(date);
ActionForward forward=null;
BoardDTO boardBean = null;
ServletContext context = request.getServletContext();
boardBean = new BoardDTO();
boardBean.setBoard_title(request.getParameter("board_title"));
boardBean.setBoard_text(request.getParameter("board_write"));
boardBean.setMember_id(request.getParameter("member_id"));
boardBean.setBoard_date(board_date);
BoardWriteProService boardWriteProService = new BoardWriteProService();
boolean isWriteSuccess = boardWriteProService.registArticle(boardBean);
// System.out.println(isWriteSuccess);
if(!isWriteSuccess){
//게시물 추가 실패
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('등록실패')");
out.println("history.back();");
out.println("</script>");
}
else{
forward = new ActionForward();
forward.setRedirect(true);
forward.setPath("boardPointCharge.po");
}
return forward;
}
}
|
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.Clip;
/**
* LevelManager is the controller class that handles all level operations
*/
public class LevelManager {
private CollisionManager collisionManager; //reference to collision manager created within
private CollisionPolicy collisionPolicy;
private GameManager gameManager; //reference to game manager which creates level manager
private FileManager fileManager; //reference to file manager created within
private int currentLevelId; //current level number
private UserPlane userPlane; //reference to user plane in level
private List<Target> targets; //list of targets in game
private List<TargetPlane> targetPlanes; //reference to list of targets in level
private List<Obstacle> obstacles; //list of obstacles in game
private List<Weapon> userWeapons; //reference to list of user weapons in level
private List<BonusPackage> bonusPackages; //reference to list of bonus packages in level
private List<Integer> weapons; //reference to list of available weapons
private int currentWeaponId; //reference to current weapon
private Level level; //reference to current level
//Constructor of game manager
public LevelManager(GameManager gameManager){
targetPlanes = new ArrayList<TargetPlane>();
userWeapons = new ArrayList<Weapon>();
targets = new ArrayList<Target>();
obstacles = new ArrayList<Obstacle>();
bonusPackages = new ArrayList<BonusPackage>();
collisionManager = new UserPlaneHitCollisionManager(this);
this.gameManager = gameManager;
this.fileManager = new FileManager(this);
level = new Level(this, 1);
currentLevelId = 1;
userPlane = level.getUserPlane();
targetPlanes = level.getTargetPlanes();
userWeapons = level.getUserWeapons();
weapons = level.getWeapons();
targets = level.getTargets();
obstacles = level.getObstacles();
bonusPackages = level.getBonusPackages();
currentWeaponId = 0;
collisionPolicy = new CollisionPolicy(this);
}
//Returns game manager
public GameManager getGameManager() {
return gameManager;
}
//Returns current level
public Level getLevel() {
return level;
}
//Updates current level
public void setLevel(Level level) {
this.level = level;
}
//Moves the user plane in the specified direction
public void moveUserPlane(int direction) {
userPlane.move(direction);
}
//Returns y coordinate of user plane
public int getUserPlaneY() {
return userPlane.getPositionY();
}
//Draws user plane on screen
public void drawUserPlane(Graphics g) {
userPlane.draw(g);
}
//Implements shoot operation
public void shoot(Graphics g) {
Shoot shoot = null;
if( currentWeaponId == 0){
shoot = new Shoot(ShootEnum.BULLET.damage(), 200, userPlane.getPositionY() + 100, ShootEnum.BULLET.image());
userWeapons.add(shoot);
}
if( currentWeaponId == 1){
if( weapons.get(currentWeaponId - 1) > 0 ){
shoot = new Shoot(ShootEnum.METALBALL.damage(), 200, userPlane.getPositionY() + 100, ShootEnum.METALBALL.image());
userWeapons.add(shoot);
updateWeapon( currentWeaponId - 1);
}
}
if( currentWeaponId == 2){
if( weapons.get(currentWeaponId - 1) > 0 ){
shoot = new Shoot(ShootEnum.FLAMEGUN.damage(), 200, userPlane.getPositionY() + 100, ShootEnum.FLAMEGUN.image());
userWeapons.add(shoot);
updateWeapon( currentWeaponId - 1);
}
}
if( currentWeaponId == 3){
if( weapons.get(currentWeaponId - 1) > 0 ){
shoot = new Shoot(ShootEnum.FROSTLASER.damage(), 200, userPlane.getPositionY() + 100, ShootEnum.FROSTLASER.image());
userWeapons.add(shoot);
updateWeapon( currentWeaponId - 1);
}
}
if( currentWeaponId == 4){
if( weapons.get(currentWeaponId - 1) > 0 )
{
shoot = new Shoot(ShootEnum.LASER.damage(), 200, userPlane.getPositionY() + 100, ShootEnum.LASER.image());
userWeapons.add(shoot);
updateWeapon( currentWeaponId - 1);
}
}
if( currentWeaponId == 5){
if( weapons.get(currentWeaponId - 1) > 0 )
{
Explosive explosive = new Explosive(ExplosiveEnum.BOMB.damage(), ExplosiveEnum.BOMB.damageArea(), 200, userPlane.getPositionY() + 100, ExplosiveEnum.BOMB.image() );
userWeapons.add(explosive);
updateWeapon( currentWeaponId - 1);
}
}
if( currentWeaponId == 6 ){
if( weapons.get(currentWeaponId - 1) > 0 )
{
Explosive explosive = new Explosive(ExplosiveEnum.MISSILE.damage(), ExplosiveEnum.MISSILE.damageArea(), 200, userPlane.getPositionY() + 100, ExplosiveEnum.MISSILE.image() );
userWeapons.add(explosive);
updateWeapon( currentWeaponId - 1);
}
}
}
//Draws all game objects on screen
public void drawObjects(Graphics g) {
for( int i = 0; i < targetPlanes.size(); i++ ){
if( targetPlanes.get(i).getPositionX() > -200){
g.drawImage(targetPlanes.get(i).getScaledImage(), targetPlanes.get(i).getPositionX(), targetPlanes.get(i).getPositionY(), null);
targetPlanes.get(i).setPositionX(targetPlanes.get(i).getPositionX() - 5);
}
else
targetPlanes.remove(i);
if( !targetPlanes.isEmpty() && !targetPlanes.get(i).getShoots().isEmpty() ){
if(targetPlanes.get(i).getShoots().get(0).getPositionX() > -10){
g.drawImage(targetPlanes.get(i).getShoots().get(0).getScaledImage(), targetPlanes.get(i).getShoots().get(0).getPositionX(), targetPlanes.get(i).getShoots().get(0).getPositionY(), null);
targetPlanes.get(i).getShoots().get(0).setPositionX(targetPlanes.get(i).getShoots().get(0).getPositionX() - 10);
}
else{
targetPlanes.get(i).removeShoot(0);
if( !targetPlanes.get(i).getShoots().isEmpty() ){
targetPlanes.get(i).setShoot(0, targetPlanes.get(i).getPositionX());
}
}
}
}
for( int i = 0; i < targets.size(); i++ ){
if( targets.get(i).getPositionX() > -200){
g.drawImage(targets.get(i).getScaledImage(), targets.get(i).getPositionX(), targets.get(i).getPositionY(), null);
targets.get(i).setPositionX(targets.get(i).getPositionX() - targets.get(i).getSpeedX());
}
else
targets.remove(i);
}
for( int i = 0; i < obstacles.size(); i++ ){
if( obstacles.get(i).getPositionX() > -200){
g.drawImage(obstacles.get(i).getScaledImage(), obstacles.get(i).getPositionX(), obstacles.get(i).getPositionY(), null);
obstacles.get(i).setPositionX(obstacles.get(i).getPositionX() - obstacles.get(i).getSpeedX());
}
else
obstacles.remove(i);
}
for( int i = 0; i < bonusPackages.size(); i++ ){
if( bonusPackages.get(i).getPositionX() > -200){
g.drawImage(bonusPackages.get(i).getScaledImage(), bonusPackages.get(i).getPositionX(), bonusPackages.get(i).getPositionY(), null);
bonusPackages.get(i).setPositionX(bonusPackages.get(i).getPositionX() - bonusPackages.get(i).getSpeedX());
}
else
bonusPackages.remove(i);
}
}
//Calls level to create objects if the seconds match
public void createObjects(int timeInSeconds, int frameWidth) {
level.createObjects(timeInSeconds,frameWidth);
}
//Draws all user weapons to screen
public void drawUserWeapons(Graphics g) {
for( int i = 0; i < userWeapons.size(); i++ ){
if( userWeapons.get(i).getPositionX() < 4000 ){
g.drawImage(userWeapons.get(i).getScaledImage(), userWeapons.get(i).getPositionX(), userWeapons.get(i).getPositionY(), null);
userWeapons.get(i).setPositionX(userWeapons.get(i).getPositionX() + userWeapons.get(i).getSpeedX());
}
else{
userWeapons.remove(i);
}
}
}
//Checks collisions and tells collision manager to handle them
public void checkCollisions(Graphics g) {
Rectangle userPlaneBorders = userPlane.getBorders();
for( int i = 0; i < targetPlanes.size(); i++ ){
Rectangle targetBorders = targetPlanes.get(i).getBorders();
if( userPlaneBorders.intersects(targetBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.userPlaneDestroyed.value);
collisionManager.handleCollision(userPlane, targetPlanes.get(i), g);
userPlane.setHealth(0);
level.updateUserPlane(userPlane);
gameOver();
}
if( !targetPlanes.isEmpty() && !targetPlanes.get(i).getShoots().isEmpty() ){
Rectangle enemyWeaponBorders = targetPlanes.get(i).getShoots().get(0).getBorders();
if( userPlaneBorders.intersects(enemyWeaponBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.userPlaneHit.value);
collisionManager.handleCollision(userPlane, targetPlanes.get(i).getShoots().get(0), g);
userPlane.setHealth(userPlane.getHealth() - targetPlanes.get(i).getShoots().get(0).getDamage());
level.updateUserPlane(userPlane);
updatePoints((-1)* targetPlanes.get(i).getShoots().get(0).getDamage());
targetPlanes.get(i).removeShoot(0);
if( !targetPlanes.get(i).getShoots().isEmpty() ){
targetPlanes.get(i).setShoot(0, targetPlanes.get(i).getPositionX());
}
}
}
}
for( int i = 0; i < userWeapons.size(); i++ ){
if( userWeapons.get(i) instanceof Explosive )
handleExplosion(g, i);
else{
Rectangle weaponBorders = userWeapons.get(i).getBorders();
for( int j = 0; j < targetPlanes.size(); j++ ){
Rectangle targetBorders = targetPlanes.get(j).getBorders();
if( weaponBorders.intersects(targetBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targetPlanes.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targetPlanes.get(j).setHealth(targetPlanes.get(j).getHealth() - userWeapons.get(i).getDamage());
userWeapons.remove(i);
if( targetPlanes.get(j).getHealth() <= 0 ){
targetPlanes.remove(j);
}
}
}
for( int j = 0; j < targets.size(); j++ ){
Rectangle targetBorders = targets.get(j).getBorders();
if( ! userWeapons.isEmpty()){
if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Carriage){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
userWeapons.remove(i);
if( targets.get(j).getHealth() <= 0 ){
targets.remove(j);
}
}
else if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Rocket){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
userWeapons.remove(i);
if( targets.get(j).getHealth() <= 0 ){
collisionManager.handleCollision(null, targets.get(j), g);
Rectangle rocketExplosionBorders = new Rectangle(
targets.get(j).getPositionX(),
targets.get(j).getPositionY(),
((Rocket) targets.get(j)).getDamageArea(),
((Rocket) targets.get(j)).getDamageArea() );
for( int k = 0; k < targets.size(); k++ ){
if( rocketExplosionBorders.intersects(targets.get(k).getBorders())){
targets.get(k).setHealth( targets.get(k).getHealth() - ((Rocket) targets.get(j)).getDamage() );
updatePoints( ((Rocket) targets.get(j)).getDamage());
}
}
for( int k = 0; k < targetPlanes.size(); k++ ){
if( rocketExplosionBorders.intersects(targetPlanes.get(k).getBorders())){
targetPlanes.get(k).setHealth( targetPlanes.get(k).getHealth() - ((Rocket) targets.get(j)).getDamage() );
updatePoints( ((Rocket) targets.get(j)).getDamage());
}
}
if( rocketExplosionBorders.intersects(userPlaneBorders)){
userPlane.setHealth(userPlane.getHealth() - ((Rocket) targets.get(j)).getDamage() );
updatePoints( ((Rocket) targets.get(j)).getDamage());
}
targets.remove(j);
}
}
else if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Ally){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(-1 * userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
userWeapons.remove(i);
if( targets.get(j).getHealth() <= 0 ){
targets.remove(j);
}
}
}
}
}
}
for( int i = 0; i < targets.size(); i++ ){
Rectangle targetBorders = targets.get(i).getBorders();
if( userPlaneBorders.intersects(targetBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.userPlaneDestroyed.value);
collisionManager.handleCollision(userPlane, targets.get(i), g);
userPlane.setHealth(0);
level.updateUserPlane(userPlane);
gameOver();
}
}
for( int i = 0; i < obstacles.size(); i++ ){
Rectangle obstacleBorders = obstacles.get(i).getBorders();
if( userPlaneBorders.intersects(obstacleBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.userPlaneDestroyed.value);
collisionManager.handleCollision(userPlane, obstacles.get(i), g);
userPlane.setHealth(0);
level.updateUserPlane(userPlane);
gameOver();
}
}
for( int i = 0; i < bonusPackages.size(); i++ ){
Rectangle bonusPackageBorders = bonusPackages.get(i).getBorders();
if( userPlaneBorders.intersects(bonusPackageBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.bonusPackageCollected.value);
if( bonusPackages.get(i) instanceof CoinPackage){
playSound(SoundManager.PRESENT_BONUS_PACKAGE_SOUND).start();
gameManager.addCoins(((CoinPackage) bonusPackages.get(i)).getCoinAmount());
bonusPackages.remove(i);
}
else if( bonusPackages.get(i) instanceof HealthBonusPackage){
playSound(SoundManager.PRESENT_BONUS_PACKAGE_SOUND).start();
userPlane.setHealth(userPlane.getHealth() + ((HealthBonusPackage) bonusPackages.get(i)).getHealthAmount());
bonusPackages.remove(i);
}
else if( bonusPackages.get(i) instanceof HealthTrapPackage){
playSound(SoundManager.TRAP_BONUS_PACKAGE_SOUND).start();
userPlane.setHealth(userPlane.getHealth() - ((HealthTrapPackage) bonusPackages.get(i)).getHealthAmount());
bonusPackages.remove(i);
}
}
}
}
private void handleExplosion(Graphics g, int i) {
Rectangle weaponBorders = userWeapons.get(i).getBorders();
Rectangle explosionBorders = new Rectangle(
userWeapons.get(i).getPositionX(),
userWeapons.get(i).getPositionY(),
((Explosive) userWeapons.get(i)).getDamageArea(),
((Explosive) userWeapons.get(i)).getDamageArea() );
for( int j = 0; j < targetPlanes.size(); j++ ){
Rectangle targetBorders = targetPlanes.get(j).getBorders();
if( weaponBorders.intersects(targetBorders)){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targetPlanes.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targetPlanes.get(j).setHealth(targetPlanes.get(j).getHealth() - userWeapons.get(i).getDamage());
for( int k = 0; k < targets.size(); k++ ){
if( explosionBorders.intersects(targets.get(k).getBorders())){
targets.get(k).setHealth( targets.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
for( int k = 0; k < targetPlanes.size(); k++ ){
if( explosionBorders.intersects(targetPlanes.get(k).getBorders())){
targetPlanes.get(k).setHealth( targetPlanes.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
if( explosionBorders.intersects(userPlane.getBorders())){
userPlane.setHealth(userPlane.getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
userWeapons.remove(i);
if( targetPlanes.get(j).getHealth() <= 0 ){
targetPlanes.remove(j);
}
}
}
for( int j = 0; j < targets.size(); j++ ){
Rectangle targetBorders = targets.get(j).getBorders();
if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Carriage){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
for( int k = 0; k < targets.size(); k++ ){
if( explosionBorders.intersects(targets.get(k).getBorders())){
targets.get(k).setHealth( targets.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
for( int k = 0; k < targetPlanes.size(); k++ ){
if( explosionBorders.intersects(targetPlanes.get(k).getBorders())){
targetPlanes.get(k).setHealth( targetPlanes.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
if( explosionBorders.intersects(userPlane.getBorders())){
userPlane.setHealth(userPlane.getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
userWeapons.remove(i);
if( targets.get(j).getHealth() <= 0 ){
targets.remove(j);
}
}
else if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Rocket){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
if( targets.get(j).getHealth() <= 0 ){
Rectangle rocketExplosionBorders = new Rectangle(
targets.get(j).getPositionX(),
targets.get(j).getPositionY(),
((Rocket) targets.get(j)).getDamageArea(),
((Rocket) targets.get(j)).getDamageArea() );
for( int k = 0; k < targets.size(); k++ ){
if( rocketExplosionBorders.intersects(targets.get(k).getBorders())){
targets.get(k).setHealth( targets.get(k).getHealth() - ((Rocket) targets.get(j)).getDamage() );
}
}
for( int k = 0; k < targetPlanes.size(); k++ ){
if( rocketExplosionBorders.intersects(targetPlanes.get(k).getBorders())){
targetPlanes.get(k).setHealth( targetPlanes.get(k).getHealth() - ((Rocket) targets.get(j)).getDamage() );
}
}
if( rocketExplosionBorders.intersects(userPlane.getBorders())){
userPlane.setHealth(userPlane.getHealth() - ((Rocket) targets.get(j)).getDamage() );
}
targets.remove(j);
}
userWeapons.remove(i);
}
else if( weaponBorders.intersects(targetBorders) && targets.get(j) instanceof Ally){
collisionPolicy.setPolicy(CollisionPolicy.CollisionPolicies.targetHit.value);
collisionManager.handleCollision(userWeapons.get(i), targets.get(j), g);
updatePoints(-1 * userWeapons.get(i).getDamage());
targets.get(j).setHealth(targets.get(j).getHealth() - userWeapons.get(i).getDamage());
for( int k = 0; k < targets.size(); k++ ){
if( explosionBorders.intersects(targets.get(k).getBorders())){
targets.get(k).setHealth( targets.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
for( int k = 0; k < targetPlanes.size(); k++ ){
if( explosionBorders.intersects(targetPlanes.get(k).getBorders())){
targetPlanes.get(k).setHealth( targetPlanes.get(k).getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
}
if( explosionBorders.intersects(userPlane.getBorders())){
userPlane.setHealth(userPlane.getHealth() - ((Explosive) userWeapons.get(i)).getDamage() );
updatePoints(userWeapons.get(i).getDamage());
}
if( targets.get(j).getHealth() <= 0 ){
targets.remove(j);
}
userWeapons.remove(i);
}
}
}
//Ends the game
public void gameOver() {
gameManager.gameOver();
}
//Draws all explosions
public void drawExplosions(Graphics g) {
collisionManager.drawExplosions(g);
}
public void removeExplosions() {
collisionManager.removeExplosions();
}
//Returns level over status text
public String levelPassedText() {
return level.levelPassedText();
}
//Tells level to create objects
public void initiateLevel(int frameWidth) {
fileManager.createLevelFromFile( frameWidth, currentLevelId);
}
//Turns points to coins at the end of the level
public int turnPointsIntoCoins(int points) {
return level.turnPointsIntoCoins(points);
}
//Returns points collected
public int getPoints() {
return level.getPoints();
}
//Initializes a new level
public void initializeLevel(int levelId) {
Level newLevel = new Level(this, levelId);
setLevel(newLevel);
currentLevelId = levelId;
initiateLevel(gameManager.getGameFrame().getWidth());
userPlane = level.getUserPlane();
targetPlanes = level.getTargetPlanes();
userWeapons = level.getUserWeapons();
weapons = level.getWeapons();
currentWeaponId = 0;
targets = level.getTargets();
obstacles = level.getObstacles();
bonusPackages = level.getBonusPackages();
}
//Initializes target objects from file manager
public void setCreatedTargetPlanes(List<TargetPlane> targetPlanes) {
level.setCreatedTargetPlanes(targetPlanes);
}
//Initializes target objects from file manager
public void setCreatedTargets(List<Target> targets) {
level.setCreatedTargets(targets);
}
//Returns whether level is passed
public boolean levelPassed() {
return level.levelPassed();
}
//Returns current levelId
public int getCurrentLevelId() {
return currentLevelId;
}
//Changes time period of the level
public void setLevelTimePeriod(int i) {
level.setLevelTimePeriod(i);
}
//Changes point threshold of the level
public void setLevelPointThreshold(int i) {
level.setLevelPointThreshold(i);
}
//Changes coin coefficient of level
public void setCoinCoefficient(int i) {
level.setCoinCoefficient(i);
}
//Returns sound clip to play sounds
public Clip playSound( int soundId) {
// TODO Auto-generated method stub
return gameManager.playSound( soundId);
}
//increases amount of coins at the end of the level
public void addCoins(int i) {
gameManager.addCoins(i);
}
//Returns list of purchased weapons at the end of the level
public List<Integer> getPurchasedWeapons() {
return gameManager.getPurchasedWeapons();
}
//Changes the current weapon
public void changeWeapon(Graphics graphics) {
if( currentWeaponId == 6)
currentWeaponId = 0;
else
currentWeaponId++;
if( currentWeaponId != 0 ){
while( currentWeaponId != 0 && weapons.get(currentWeaponId - 1) == 0 ){
if( currentWeaponId == 6)
currentWeaponId = 0;
else
currentWeaponId++;
}
}
}
//Updates level screen to view changes
public void updateLevelView() {
gameManager.updateLevelView();
}
//Private method call - updates number of weapons after shooting
private void updateWeapon(int currentWeaponId) {
int i = weapons.get(currentWeaponId);
i--;
weapons.set(currentWeaponId, i);
updateWeaponInCollection(currentWeaponId);
}
//Updates user collection weapons when the user plane shoots
public void updateWeaponInCollection(int currentWeaponId) {
gameManager.updateWeapon(currentWeaponId);
}
//Updates target planes from level
public void updateTargetPlanes(List<TargetPlane> tps) {
this.targetPlanes = tps;
}
//Updates points in level
public void updatePoints(int points) {
level.updatePoints(points);
}
public void updateTargets(List<Target> targets) {
this.targets = targets;
}
public void setCreatedObstacles(List<Obstacle> obstacles) {
level.setCreatedObstacles(obstacles);
}
public void updateObstacles(List<Obstacle> obstacles) {
this.obstacles = obstacles;
}
public void setCreatedBonusPackages(List<BonusPackage> bonusPackages) {
level.setCreatedBonusPackages(bonusPackages);
}
public void updateBonusPackages(List<BonusPackage> bonusPackages) {
this.bonusPackages = bonusPackages;
}
public void setCurrentLevelId(int levelId) {
currentLevelId = levelId;
}
public void setCollisionManager(CollisionManager collisionManager) {
this.collisionManager = collisionManager;
}
}
|
package org.crazyit.event;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
// 实现事件监听器接口
public class MainActivity extends Activity
implements View.OnClickListener
{
EditText show;
Button bn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
show = (EditText) findViewById(R.id.show);
bn = (Button) findViewById(R.id.bn);
// 直接使用Activity作为事件监听器
bn.setOnClickListener(this);
}
// 实现事件处理方法
@Override
public void onClick(View v)
{
show.setText("bn按钮被单击了!");
}
}
|
public class UrlData {
String urlProcessed;
Location location;
public String getUrlProcessed() {
return urlProcessed;
}
public void setUrlProcessed(String urlProcessed) {
this.urlProcessed = urlProcessed;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
|
public class MyBellmanFordSP {
private double[] disTo;
private DirectedEdge[] edgeTo;
private boolean[] onQ;
private Queue<Integer> queue;
private int cost;
private Iterable<DirectedEdge> cycle;
private EdgeWeightedDigraph G;
private int s;
public MyBellmanFordSP(EdgeWeightedDigraph G, int s)
{
this.G = G;
this.s = s;
disTo = new double[G.V()];
for(int i = 0; i < G.V(); ++i)
disTo[i] = Double.POSITIVE_INFINITY;
edgeTo = new DirectedEdge[G.V()];
onQ = new boolean[G.V()];
queue = new Queue<Integer>();
disTo[s] = 0.0;
queue.enqueue(s);
onQ[s] = true;
while (!queue.isEmpty() && !this.hasNegativeCycle())
{
int v = queue.dequeue();
onQ[v] = false;
if(edgeTo[v]== null || !onQ[edgeTo[v].from()])
relax(v);
}
}
private void relax(int v)
{
for(DirectedEdge e: G.adj(v))
{
int w = e.to();
if(disTo[w] > disTo[v] + e.weight())
{
disTo[w] = disTo[v] + e.weight();
edgeTo[w] = e;
if(!onQ[w])
{
onQ[w] = true;
queue.enqueue(w);
}
}
if(cost++ % G.V() == 0)
findNegativeCycle();
}
}
private void findNegativeCycle()
{
int V = edgeTo.length;
EdgeWeightedDigraph spt = new EdgeWeightedDigraph(V);
for(int v = 0; v < V; ++v)
{
if(edgeTo[v] != null)
spt.addEdge(edgeTo[v]);
}
EdgeWeightedDirectedCycle cf = new EdgeWeightedDirectedCycle(spt);
cycle = cf.cycle();
}
public boolean hasNegativeCycle()
{
return cycle != null;
}
public Iterable<DirectedEdge> negativeCycle()
{
return cycle;
}
public double distTo(int v)
{
return disTo[v];
}
public boolean hasPathTo(int v)
{
return disTo[v] != Double.POSITIVE_INFINITY;
}
public Iterable<DirectedEdge> pathTo(int v)
{
Stack<DirectedEdge> stack = new Stack<DirectedEdge>();
while (edgeTo[v] != null)
{
stack.push(edgeTo[v]);
v = edgeTo[v].from();
}
return stack;
}
}
|
package yinq.situation.dataModel;
/**
* Created by YinQ on 2018/11/30.
*/
public class SleepSituationDetModel extends SituationDetModel {
private int code;
private int status;
private int score;
public SleepSituationDetModel(){
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
|
package com.worldchip.bbpawphonechat.activity;
import com.worldchip.bbpawphonechat.R;
import com.worldchip.bbpawphonechat.application.MyApplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.TextView;
public class MyProtocolContentsActivity extends Activity {
private WebView mWebView;
String assetsUri = "";
private TextView mIv_sign_up;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_protocol_contents);
mWebView = (WebView)findViewById(R.id.webview_compontent);
mWebView.getSettings().setJavaScriptEnabled(true);
mIv_sign_up = (TextView) findViewById(R.id.chat_to_name1);
MyApplication.getInstance().ImageAdapter(
mIv_sign_up,
new int[] { R.drawable.register_title_img,
R.drawable.register_title_img_es,
R.drawable.register_title_img_en });
if(MyApplication.getInstance().system_local_language == 0){
assetsUri = "file:///android_asset/www/protocol_cn.html";
}else if(MyApplication.getInstance().system_local_language == 1){
assetsUri = "file:///android_asset/www/protocol_es.html";
}else {
assetsUri = "file:///android_asset/www/protocol_en.html";
}
mWebView.loadUrl(assetsUri);
findViewById(R.id.iv_protocol_back).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package logica;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import bean.Partita;
import bean.Utente;
import dao.GiocoHDao;
import dao.UtenteHDao;
public abstract class UtenteManager {
static ClassPathResource resource = new ClassPathResource("UtenteHDao.xml");
static XmlBeanFactory factory = new XmlBeanFactory(resource);
private static boolean validatore;
public static final boolean verificaPresenzaUtente(String nickname) throws Exception {
UtenteHDao utenteHDao=(UtenteHDao) factory.getBean("utentehdao", UtenteHDao.class);
return utenteHDao.verificaPresenzaUtente(nickname);
}
public static final boolean login(String nickname,String password) throws Exception {
UtenteHDao utenteHDao=(UtenteHDao) factory.getBean("utentehdao", UtenteHDao.class);
Utente utente= utenteHDao.getUtenteLoginSql(nickname,password);
if(utente!=null) {
validatore=true;
}
else {
validatore=false;
}
return validatore;
}
public static final List<Partita> listaClassifica() throws Exception {
GiocoHDao giocoHDao=new GiocoHDao();
List<Partita> risultati=new ArrayList<Partita>();
risultati=giocoHDao.getClassificaCriteria(1);
return risultati;
}
public static final void registraUtente(String nickname,String paese,String password) throws Exception {
Utente utente= new Utente();
UtenteHDao utenteHDao=(UtenteHDao) factory.getBean("utentehdao", UtenteHDao.class);
utente.setNickname(nickname);
utente.setPaese(paese);
utente.setPassword(password);
utenteHDao.crea(utente);
}
}
|
package tjava.base;
import java.util.Objects;
import java.util.function.Supplier;
public abstract class Result<T> {
public abstract boolean isSuccess();
public abstract T getContent();
public abstract T getOrElse(final T defaultValue);
public abstract T getOrElse(final Supplier<T> defaultValue);
public abstract Result<T> orElse(final Supplier<Result<T>> defaultResult);
public abstract <U> Result<U> map(Function<T, U> f);
public abstract <U> Result<U> flatMap(Function<T, Result<U>> f);
/*public Result<T> orElse(Supplier<Result<T>> defaultValue);*/
@SuppressWarnings("rawtypes")
private static Result empty = new Empty();
public abstract void forEach(Effect<T> ef);
public abstract boolean isEmpty();
public abstract void forEachOrThrow(Effect<T> ef);
public abstract Result<RuntimeException> forEachOrException(Effect<T> ef);
public abstract Result<T> mapEmpty();
private static class Empty<V> extends Result<V> {
@Override
public boolean isEmpty(){
return true;
}
@Override
public void forEachOrThrow(Effect<V> ef) {
throw new IllegalStateException();
}
@Override
public Result<RuntimeException> forEachOrException(Effect<V> ef) {
return empty();
}
@Override
public Result<V> mapEmpty() {
return Result.success(null);
}
public Empty() {
super();
}
@Override
public boolean isSuccess() {
return false;
}
@Override
public V getContent() {
throw new IllegalAccessError();
}
@Override
public V getOrElse(final V defaultValue) {
return defaultValue;
}
@Override
public <U> Result<U> map(Function<V, U> f) {
return empty;
}
@Override
public <U> Result<U> flatMap(Function<V, Result<U>> f) {
return empty;
}
@Override
public void forEach(Effect<V> ef) {
//Just do nothing
}
@Override
boolean isFailure() {
return true;
}
@Override
public String toString() {
return "Empty()";
}
@Override
public V getOrElse(Supplier<V> defaultValue) {
return defaultValue.get();
}
@Override
public Result<V> orElse(Supplier<Result<V>> defaultResult) {
return defaultResult.get();
}
}
public static class Success<T> extends Result<T> {
private final T value;
@Override
public Result<RuntimeException> forEachOrException(Effect<T> ef) {
ef.apply(value);
return empty();
}
@Override
public Result<T> mapEmpty() {
return Result.failure("is not empty");
}
public void forEachOrThrow(Effect<T> ef) {
forEach(ef);
}
public void forEach(Effect<T> ef) {
ef.apply(value);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
Success other = (Success) obj;
return getClass().equals(obj.getClass())
&& this.value.equals(other.value);
}
private Success(T t) {
value = t;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public T getContent() {
return value;
}
@Override
public T getOrElse(T defaultValue) {
return value;
}
@Override
public T getOrElse(Supplier<T> defaultValue) {
return value;
}
@Override
public Result<T> orElse(Supplier<Result<T>> defaultResult) {
return Result.success(value);
}
@Override
public <U> Result<U> map(Function<T, U> f) {
try {
return Result.success(f.apply(value));
}catch(RuntimeException e){
return Result.failure(e);
}
}
@Override
public <U> Result<U> flatMap(Function<T, Result<U>> f) {
return f.apply(value);
}
@Override
public boolean isFailure() {
return false;
}
@Override
public String toString() {
return String.format("Success(%s)", value.toString());
}
}
public static class Failure<T> extends Empty<T> {
private final RuntimeException exception;
@Override
public boolean isEmpty() {
return false;
}
@Override
public Result<RuntimeException> forEachOrException(Effect<T> ef) {
return success(exception);
}
@Override
public void forEachOrThrow(Effect<T> ef) {
throw exception;
}
private Failure(String message) {
this.exception = new IllegalStateException(message);
}
@Override
public <U> Result<U> map(Function<T, U> f) {
return Result.failure(exception);
}
@Override
public <U> Result<U> flatMap(Function<T, Result<U>> f) {
return Result.failure(exception);
}
@Override
public Result<T> mapEmpty() {
return Result.failure("is not empty");
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Failure<?> failure = (Failure<?>) o;
return Objects.equals(toString(), failure.toString());
}
@Override
public int hashCode() {
return Objects.hash(exception);
}
private Failure(RuntimeException e) {
this.exception = e;
}
private Failure(Exception e) {
this.exception = new IllegalStateException(e.getMessage(), e);
}
@Override
public String toString() {
return String.format("Failure(%s)", exception.getMessage());
}
}
abstract boolean isFailure();
public static <V> Result<V> failure(Exception e) {
return new Failure<V>(e);
}
public static <V> Result<V> failure(RuntimeException e) {
return new Failure<V>(e);
}
public static <T> Result<T> failure(String message) {
return new Failure<>(message);
}
public static <T> Result<T> success(T value) {
return new Success<>(value);
}
public static <T> Result<T> empty() {
return empty;
}
public static <T> Result<T> of(T value){
return of(value, "Null value");
}
public static <T> Result<T> of(T value, String message) {
return value==null
?Result.failure(message)
:Result.success(value);
}
public static <T> Result<T> of(Function<T, Boolean> f, T value, String message) {
return ResultUtils.filterEmpty(of(value, message), f);
}
public static <T> Result<T> of(Function<T, Boolean> f, T value) {
return ResultUtils.filterEmpty(of(value), f);
}
}
|
package sg.edu.iss.ad.utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sg.edu.iss.ad.model.*;
import sg.edu.iss.ad.repository.CandleHistoryRepository;
import sg.edu.iss.ad.repository.UserCandleWatchListRepository;
import sg.edu.iss.ad.repository.UserStockWatchListRepository;
import sg.edu.iss.ad.service.CandleService;
import sg.edu.iss.ad.service.UserService;
import sg.edu.iss.ad.service.UserStockWatchListService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Component
public class CandleScheduleTask {
private CandleService candleService;
private UserCandleWatchListRepository userCandleWatchListRepository;
private CandleHistoryRepository candleHistoryRepository;
@Autowired
public void setCandleService(CandleService cs) {
this.candleService = cs;
}
@Autowired
public void setUserCandleWatchListRepository(UserCandleWatchListRepository ucwlrepo) {
this.userCandleWatchListRepository = ucwlrepo;
}
@Autowired
public void setCandleHistoryRepository(CandleHistoryRepository chrepo){
this.candleHistoryRepository = chrepo;
}
// @Scheduled(cron = "*/20 * * * * ?")
// public void checkCandle() throws ParseException {
// System.out.println("time now: "+new Date());
// List<UserCandleWatchList> ucwlLists = userCandleWatchListRepository.findAll();
// for (UserCandleWatchList userCandleWatchList : ucwlLists){
// if (userCandleWatchList.getActive()){
// checkCandle(userCandleWatchList);
// }
// }
// }
private void checkCandle(UserCandleWatchList userCandleWatchList) throws ParseException {
UserStockWatchList currentUserStockWatchList = userCandleWatchList.getUserStockWatchList();
User currentUser = currentUserStockWatchList.getUser();
String currentEmail = currentUser.getEmail();
String currentTicker = currentUserStockWatchList.getStock().getStockTicker();
List<CandleModel> result = candleService.getCandleData(currentTicker);
List<Long> dates;
MailVo mailVo = new MailVo("PCXGudrew@163.com",currentEmail,"","");
boolean sendNotification = false;
/*
* check if the candle exists and send Email
* */
if (userCandleWatchList.getCandle().getId() == 1){
dates = candleService.getBullishEngulfingCandleSignalUNIX(result);
updateCandleHistory(dates,currentUserStockWatchList.getStock(),userCandleWatchList.getCandle(),mailVo);
}
else if(userCandleWatchList.getCandle().getId() == 2){
dates = candleService.getBearishEngulfingCandleSignalUNIX(result);
updateCandleHistory(dates,currentUserStockWatchList.getStock(),userCandleWatchList.getCandle(),mailVo);
}
else if(userCandleWatchList.getCandle().getId() == 3){
dates = candleService.getMorningStarCandleUNIX(result);
updateCandleHistory(dates,currentUserStockWatchList.getStock(),userCandleWatchList.getCandle(),mailVo);
}
else{
dates = candleService.getEveningStarUNIX(result);
updateCandleHistory(dates,currentUserStockWatchList.getStock(),userCandleWatchList.getCandle(),mailVo);
}
}
private void updateCandleHistory(List<Long> dates, Stock stock, Candle candle, MailVo mailVo){
Long date = dates.get(0);
/*
* check if a candleHistory of same datetime, same stock id, same candle id found.
* if not found, save candleHistory and send notification
* if found, do nothing
* */
CandleHistory candleHistoryResult = candleHistoryRepository.getCandleHistoryByStockAndCandleAndTime(stock.getId(),candle.getId(),date);
if (candleHistoryResult == null){
/*
* save candle
* */
CandleHistory candleHistory = new CandleHistory();
candleHistory.setCandle(candle);
candleHistory.setStock(stock);
candleHistory.setDateTimeTrigger(date);
candleHistoryRepository.save(candleHistory);
/*
* send notification
* */
candleService.sendEmailNotification(mailVo);
}
}
}
|
package com.metoo.foundation.service.impl;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.metoo.core.dao.IGenericDAO;
import com.metoo.foundation.domain.GameUserTask;
import com.metoo.foundation.service.IGameUserTaskService;
@Service
@Transactional
public class GameUserTaskServiceImpl implements IGameUserTaskService{
@Resource(name = "gameUserTaskDAO")
private IGenericDAO<GameUserTask> gameUserTaskDao;
@Override
public GameUserTask getObjById(Long id) {
// TODO Auto-generated method stub
return this.gameUserTaskDao.get(id);
}
@Override
public boolean save(GameUserTask instance) {
// TODO Auto-generated method stub
try {
this.gameUserTaskDao.save(instance);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
@Override
public boolean update(GameUserTask instance) {
// TODO Auto-generated method stub
try {
this.gameUserTaskDao.update(instance);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
@Override
public boolean delete(Long id) {
// TODO Auto-generated method stub
try {
this.gameUserTaskDao.remove(id);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
@Override
public List<GameUserTask> query(String query, Map params, int begin, int max) {
// TODO Auto-generated method stub
return this.gameUserTaskDao.query(query, params, begin, max);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cput.codez.angorora.eventstar.model;
/**
*
* @author allen
*/
public final class Address {
private String id;
private String hseNum;
private String street;
private String town;
private String postalCode;
private String country;
private Address() {
}
private Address(Builder build) {
this.id=build.id;
this.postalCode=build.postalCode;
this.hseNum=build.hseNum;
this.street=build.street;
this.town=build.town;
this.country=build.country;
}
public String getId() {
return id;
}
public String getHseNum() {
return hseNum;
}
public String getStreet() {
return street;
}
public String getTown() {
return town;
}
public String getPostalCode() {
return postalCode;
}
public String getCountry() {
return country;
}
public static class Builder{
private String id;
private String hseNum;
private String street;
private String town;
private String postalCode;
private String country;
public Builder(String post) {
this.postalCode=post;
}
public Builder id(String id){
this.id=id;
return this;
}
public Builder hseNum(String hseNum){
this.hseNum=hseNum;
return this;
}
public Builder street(String street){
this.street=street;
return this;
}
public Builder town(String twn){
this.town=twn;
return this;
}
public Builder Country(String country){
this.country=country;
return this;
}
public Address build(){
return new Address(this);
}
public Builder copier(Address addr){
this.id=addr.id;
this.postalCode=addr.postalCode;
this.hseNum=addr.hseNum;
this.street=addr.street;
this.town=addr.town;
this.country=addr.country;
return this;
}
}
@Override
public int hashCode() {
int hash = 7;
hash = 47 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Address other = (Address) obj;
if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) {
return false;
}
return true;
}
}
|
package objetos.aeronaves.enemigos;
import movimiento.Posicion;
import movimiento.patrones.IdasVueltas;
import objetos.Energia;
import objetos.aeronaves.Enemigo;
import objetos.armas.CuartoArmas;
import org.jdom.*;
import vistas.FactoryVistas;
import ar.uba.fi.algo3.titiritero.ControladorJuego;
import ar.uba.fi.algo3.titiritero.vista.Imagen;
import auxiliares.Vector;
/*
* Clase que modela la avioneta enemiga
*/
public class Avioneta extends Enemigo {
public Avioneta() {
super();
this.setTamanio(28);
this.setEnergia(new Energia(20));
this.setVelocidad(new Vector(0, 2));
this.setPatron(new IdasVueltas());
this.setPuntajeOtorgado(20);
this.setVelocidadHuida(new Vector(0, -3));
this.getArsenal().activarLaser();
}
public Avioneta(Posicion posicion) {
this();
this.setPosicion(posicion);
}
public Avioneta(int x, int y) {
this(new Posicion(x, y));
}
@Override
public void mover() {
super.mover();
this.setChanged();
notifyObservers();
}
@Override
public Imagen darVista(ControladorJuego controlador) {
return FactoryVistas.crearVista(this, controlador);
}
/* Persistencia */
public Avioneta(Element nodo) {
this(Integer.parseInt(nodo.getAttributeValue("posicionX")), Integer
.parseInt(nodo.getAttributeValue("posicionY")));
this.setArsenal(new CuartoArmas(nodo.getChild("cuartoArmas")));
this.getArsenal().setBase(this);
}
/* NodoXML a partir de instancia */
@Override
public Element obtenerNodo() {
Element nodo = new Element("avioneta");
nodo.setAttribute(new Attribute("posicionX", Integer.toString(this
.getPosicion().getEnX())));
nodo.setAttribute(new Attribute("posicionY", Integer.toString(this
.getPosicion().getEnY())));
nodo.addContent(this.getArsenal().obtenerNodo());
return nodo;
}
}
|
package org.hibernate.bugs;
import javax.persistence.*;
@Entity
@Table(name = "vendor")
public class Vendor {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "address_id")
private VendorAddress address;
private Vendor() { }
public Vendor(String name, VendorAddress address) {
this.name = name;
this.address = address;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public VendorAddress getAddress() {
return address;
}
}
|
package exam.iz0_803;
public class Exam_076 {
}
/*
Given the code fragment:
String name = "Spot";
int age = 4;
String str = "My dog " + name + " is " + age;
System.out.println(str);
And:
StringBuilder sb = new StringBuilder();
Using StringBuulder, which code fragment is the best potion to build and print following string "My dog Spot is 4"?
A. sb.append("My dog " + name + " is " + age);
System.out.println(sb);
B. sb.insert("My dog ").append(name + " is " + age);
System.out.println(sb);
C. sb.insert("My dog ").insert(name).insert(" is ").insert(age);
System.out.println(sb);
D. sb.append("My dog ").append(name).append(" is ").append(age);
System.out.println(sb);
Answer: AD
*/
|
package common.geo;
public class Location {
private Geocode geocode;
private PostalAddress addr;
public Geocode getGeocode() {
return geocode;
}
public void setGeocode(Geocode geocode) {
this.geocode = geocode;
}
public PostalAddress getAddr() {
return addr;
}
public void setAddr(PostalAddress addr) {
this.addr = addr;
}
@Override
public String toString() {
return addr.toString() + "\n" + geocode.toString();
}
}
|
package org.sky.app.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.sky.app.service.AppBaseCustomerService;
import org.sky.app.utils.AppConst;
import org.sky.base.model.BaseCustomerExample;
import org.sky.sys.utils.Page;
import org.sky.sys.utils.PageListData;
import org.sky.sys.utils.ResultData;
import org.sky.sys.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName: BaseCustomerController
* @Description: TODO(客户接口类)
* @author AK
* @date 2018-5-7 下午7:32:13
*
*/
@RestController
public class AppBaseCustomerController {
private final Logger logger = Logger.getLogger(AppBaseCustomerController.class);
@Autowired
private AppBaseCustomerService appBaseCustomerService;
/**
* 客户分页查询
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/app/BaseCustomer/listBaseCustomerByPage", method =RequestMethod.POST,produces = "application/json;charset=UTF-8")
public ResultData listBaseCustomerByPage(HttpServletRequest request, HttpServletResponse response){
ResultData rd = new ResultData();
try{
//获取用户ID
String user_id = (String) request.getAttribute(AppConst.REQUEST_LOGIN_MSG);
//获取参数
String page = request.getParameter("page");
String rows = request.getParameter("rows");
String type = request.getParameter("type");//0:表示全部用户,1:表示今日客户2:表示重点客户
if(StringUtils.isNull(page)||StringUtils.isNull(rows)||StringUtils.isNull(type)||StringUtils.isNull(user_id)){
rd.setCode(AppConst.PARAMETER_NULL);
rd.setName(AppConst.PARAMETER_NULL_DESCRIPTION);
return rd;
}
Map<String,Object> filterMap = new HashMap<String,Object>();
BaseCustomerExample example = new BaseCustomerExample();
if(AppConst.CUSTOMER_TYPE_1.equals(type)){
filterMap.put("to_char(visit_time,'yyyy-mm-dd')=to_char(sysdate,'yyyy-mm-dd') and 1@=", "1");
}else if(AppConst.CUSTOMER_TYPE_2.equals(type)){
filterMap.put("impCustomer@=", AppConst.APP_IS);
}
filterMap.put("creater@=", user_id);
example.createCriteria();
example.integratedQuery(filterMap);
example.setOrderByClause("update_time desc");
//设置分页
Page p = new Page();
p.setBegin((Integer.valueOf(page)-1)*Integer.valueOf(rows));
p.setEnd(Integer.valueOf(page)*Integer.valueOf(rows));
example.setPage(p);
PageListData pld = appBaseCustomerService.listBaseCustomerByPage(example);
rd.setCode(AppConst.SUCCESS);
rd.setData(pld);
return rd;
}catch(Exception e){
e.printStackTrace();
logger.error(e);
rd.setCode(AppConst.SYS_ERROR);
rd.setName(AppConst.SYS_ERROR_DESCRIPTION);
return rd;
}
}
}
|
package com.pmm.sdgc.model;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
/**
*
* @author dreges
*/
@Entity
@Table(name = "usermsnPreDefinida")
public class UsermsnPreDefinida implements Serializable {
//VAR
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "referencia")
private String referencia;
@Column(name = "tipo")
private String tipo;
@Column(name = "titulo")
private String titulo;
@Column(name = "texto")
private String texto;
@Column(name = "dataHora")
private LocalDateTime dataHora;
@ManyToOne
@JoinColumn(name = "userlogin", referencedColumnName = "id")
@NotFound(action = NotFoundAction.IGNORE)
private UserLogin userLogin;
//SET GET
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getTexto() {
return texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public UserLogin getUserLogin() {
return userLogin;
}
public void setUserLogin(UserLogin userLogin) {
this.userLogin = userLogin;
}
public String getReferencia() {
return referencia;
}
public void setReferencia(String referencia) {
this.referencia = referencia;
}
@Override
public String toString() {
return "UsermsnPreDefinida{" + "id=" + id + ", referencia=" + referencia + ", tipo=" + tipo + ", titulo=" + titulo + ", texto=" + texto + ", userLogin=" + userLogin + '}';
}
}
|
package alien4cloud.tosca;
import alien4cloud.component.ICSARRepositorySearchService;
import alien4cloud.component.repository.ICsarRepositry;
import alien4cloud.component.repository.exception.CSARVersionAlreadyExistsException;
import alien4cloud.model.components.CSARDependency;
import alien4cloud.model.components.Csar;
import alien4cloud.model.git.CsarDependenciesBean;
import alien4cloud.paas.wf.WorkflowsBuilderService;
import alien4cloud.security.AuthorizationUtil;
import alien4cloud.security.model.Role;
import alien4cloud.topology.TopologyServiceCore;
import alien4cloud.topology.TopologyTemplateVersionService;
import alien4cloud.tosca.model.ArchiveRoot;
import alien4cloud.tosca.parser.*;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
@Component
public class ArchiveUploadService {
@Inject
private ArchiveParser parser;
@Inject
private ToscaCsarDependenciesParser dependenciesParser;
@Inject
private ArchiveIndexer archiveIndexer;
@Inject
private ICsarRepositry archiveRepositry;
@Inject
TopologyServiceCore topologyServiceCore;
@Inject
TopologyTemplateVersionService topologyTemplateVersionService;
@Inject
private WorkflowsBuilderService workflowsBuilderService;
@Inject
private ICSARRepositorySearchService searchService;
/**
* Upload a TOSCA archive and index its components.
*
* @param path The archive path.
* @return The Csar object from the parsing.
* @throws ParsingException
* @throws CSARVersionAlreadyExistsException
*/
public ParsingResult<Csar> upload(Path path) throws ParsingException, CSARVersionAlreadyExistsException {
// parse the archive.
ParsingResult<ArchiveRoot> parsingResult = parser.parse(path);
String archiveName = parsingResult.getResult().getArchive().getName();
String archiveVersion = parsingResult.getResult().getArchive().getVersion();
final ArchiveRoot archiveRoot = parsingResult.getResult();
if (archiveRoot.hasToscaTopologyTemplate()) {
AuthorizationUtil.checkHasOneRoleIn(Role.ARCHITECT, Role.ADMIN);
}
if (archiveRoot.hasToscaTypes()) {
AuthorizationUtil.checkHasOneRoleIn(Role.COMPONENTS_MANAGER, Role.ADMIN);
}
if (ArchiveUploadService.hasError(parsingResult, null)) {
// check if any blocker error has been found during parsing process.
if (ArchiveUploadService.hasError(parsingResult, ParsingErrorLevel.ERROR)) {
// do not save anything if any blocker error has been found during import.
return toSimpleResult(parsingResult);
}
}
archiveIndexer.importArchive(archiveRoot, path, parsingResult.getContext().getParsingErrors());
return toSimpleResult(parsingResult);
}
public Map<CSARDependency, CsarDependenciesBean> preParsing(Set<Path> paths) throws ParsingException {
Map<CSARDependency, CsarDependenciesBean> csarDependenciesBeans = Maps.newHashMap();
for (Path path : paths) {
CsarDependenciesBean csarDepContainer = new CsarDependenciesBean();
ParsingResult<ArchiveRoot> parsingResult = parser.parse(path);
csarDepContainer.setPath(path);
csarDepContainer.setSelf(new CSARDependency(parsingResult.getResult().getArchive().getName(), parsingResult.getResult().getArchive().getVersion()));
csarDepContainer.setDependencies(parsingResult.getResult().getArchive().getDependencies());
csarDependenciesBeans.put(csarDepContainer.getSelf(), csarDepContainer);
}
return csarDependenciesBeans;
}
/**
* Create a simple result without all the parsed data but just the {@link Csar} object as well as the eventual errors.
*
* @return The simple result out of the complex parsing result.
*/
private ParsingResult<Csar> toSimpleResult(ParsingResult<ArchiveRoot> parsingResult) {
ParsingResult<Csar> simpleResult = this.<Csar> cleanup(parsingResult);
simpleResult.setResult(parsingResult.getResult().getArchive());
return simpleResult;
}
private <T> ParsingResult<T> cleanup(ParsingResult<?> result) {
ParsingContext context = new ParsingContext(result.getContext().getFileName());
context.getParsingErrors().addAll(result.getContext().getParsingErrors());
ParsingResult<T> cleaned = new ParsingResult<T>(null, context);
return cleaned;
}
/**
* Checks if a given parsing result has any error.
*
* @param parsingResult The parsing result to check.
* @param level The level of error to check. Null means any levels.
* @return true if the parsing result as at least one error of the requested level.
*/
public static boolean hasError(ParsingResult<?> parsingResult, ParsingErrorLevel level) {
for (ParsingError error : parsingResult.getContext().getParsingErrors()) {
if (level == null || level.equals(error.getErrorLevel())) {
return true;
}
}
return false;
}
}
|
package Problem_15645;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[3];
int[] tmp = new int[3];
int[] dp_x = new int[3]; // max
int[] dp_n = new int[3]; // min
for (int i = 0; i < N; i++) {
for (int j = 0; j < 3; j++) arr[j] = sc.nextInt();
tmp[0] = Math.min(dp_n[0] + arr[0], dp_n[1] + arr[0]);
tmp[1] = Math.min(Math.min(dp_n[0] + arr[1], dp_n[1] + arr[1]), dp_n[2] + arr[1]);
tmp[2] = Math.min(dp_n[2] + arr[2], dp_n[1] + arr[2]);
for (int j = 0; j < 3; j++) dp_n[j] = tmp[j];
tmp[0] = Math.max(dp_x[0] + arr[0], dp_x[1] + arr[0]);
tmp[1] = Math.max(Math.max(dp_x[0] + arr[1], dp_x[1] + arr[1]), dp_x[2] + arr[1]);
tmp[2] = Math.max(dp_x[2] + arr[2], dp_x[1] + arr[2]);
for (int j = 0; j < 3; j++) dp_x[j] = tmp[j];
}
int max, min;
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
for (int i = 0; i < 3; i++) if (max < dp_x[i]) max = dp_x[i];
for (int i = 0; i < 3; i++) if (min > dp_n[i]) min = dp_n[i];
System.out.println(max + " " + min);
}
}
|
package com.techm.daos.impl;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.techm.daos.UserDAO;
import com.techm.models.User;
public class UserDAOImpl implements UserDAO {
private Connection con;
private String conURL="jdbc:oracle:thin:@localhost:1521:XE";
private String dbUserName="system";
private String dbPassword="system";
private String driverClass="oracle.jdbc.OracleDriver";
public UserDAOImpl() {
try {
Class.forName(driverClass);
System.out.println("++++++ DRIVER LOADED ++++++");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public UserDAOImpl(String conURL, String dbUserName, String dbPassword,String driverClass) {
this.conURL = conURL;
this.dbUserName = dbUserName;
this.dbPassword = dbPassword;
this.driverClass = driverClass;
try {
Class.forName(driverClass);
System.out.println("++++++ DRIVER LOADED ++++++");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public Connection getConnection() {
try {
con=DriverManager.getConnection(conURL,dbUserName,dbPassword);
System.out.println("++++++ CONNECTED TO DB ++++++");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
@Override
public void closeConnection() {
if(con!=null){
try {
con.close();
System.out.println("++++++ CONNECTION TO DB CLOSED ++++++");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@Override
public boolean addUser(User user) {
String SQL="insert into user_tbl values(?,?,?,?,?,?,?)";
boolean isAdded=false;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ps.clearParameters();
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getUserName());
ps.setString(4, user.getPassword());
ps.setString(5,user.getCellNo());
ps.setString(6, user.getEmail());
ps.setInt(7, user.getAge());
int cnt=ps.executeUpdate();
if(cnt==1){
isAdded=true;
System.out.println("++++++ USER ADDED SUCCESSFULY ++++++");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return isAdded;
}
@Override
public boolean updateUser(User user) {
String SQL="update user_tbl set firstname = ?,"
+ "lastname = ?,password = ?,cellno = ?,"
+ "email =?,age = ? "
+ "where username = ?";
boolean isUpdated=false;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ps.clearParameters();
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getPassword());
ps.setString(4, user.getCellNo());
ps.setString(5, user.getEmail());
ps.setInt(6, user.getAge());
ps.setString(7, user.getUserName());
int cnt=ps.executeUpdate();
if(cnt==1){
isUpdated=true;
System.out.println("++++++ USER UPDATED SUCCESSFULY ++++++");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return isUpdated;
}
@Override
public boolean removeUser(String userName) {
String SQL="delete from user_tbl where username = ?";
boolean isRemoved=false;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ps.clearParameters();
ps.setString(1, userName);
int cnt=ps.executeUpdate();
if(cnt==1){
isRemoved=true;
System.out.println("++++++ USER DELETED SUCCESSFULY ++++++");
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return isRemoved;
}
@Override
public User getUser(String userName) {
String SQL="select * from user_tbl where username = ?";
User user=null;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ps.clearParameters();
ps.setString(1,userName);
ResultSet rs=ps.executeQuery();
if(rs.next()){
user=new User();
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setUserName(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setCellNo(rs.getString("cellno"));
user.setEmail(rs.getString("email"));
user.setAge(rs.getInt("age"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return user;
}
public List<User> getAllUsersUsingStatement(){
String SQL="select * from user_tbl";
ArrayList<User>userList=new ArrayList<User>();
User user=null;
getConnection();
try {
Statement st=con.createStatement();
//Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
//ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery(SQL);
while(rs.next()){
user=new User();
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setUserName(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setCellNo(rs.getString("cellno"));
user.setEmail(rs.getString("email"));
user.setAge(rs.getInt("age"));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{closeConnection();}
return userList;
}
@Override
public List<User> getAllUsers() {
String SQL="select * from user_tbl";
ArrayList<User>userList=new ArrayList<User>();
User user=null;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ResultSet rs=ps.executeQuery();
while(rs.next()){
user=new User();
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setUserName(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setCellNo(rs.getString("cellno"));
user.setEmail(rs.getString("email"));
user.setAge(rs.getInt("age"));
userList.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return userList;
}
@Override
public boolean validateUser(User user) {
String SQL="select * from user_tbl where username = ? and password = ?";
boolean isValid=false;
getConnection();
try {
PreparedStatement ps=con.prepareStatement(SQL);
ps.clearParameters();
ps.setString(1, user.getUserName());
ps.setString(2, user.getPassword());
ResultSet rs=ps.executeQuery();
if(rs.next()){
isValid=true;
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return isValid;
}
@Override
public void getAllUsersForDBTraverse() {
String SQL="select * from user_tbl";
getConnection();
try {
PreparedStatement ps=con.prepareCall(SQL,
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=ps.executeQuery();
rs.first();
System.out.println(rs.getString("firstname")+" : "+rs.getString("lastname"));
rs.absolute(3);
System.out.println(rs.getString("firstname")+" : "+rs.getString("lastname"));
rs.last();
System.out.println(rs.getString("firstname")+" : "+rs.getString("lastname"));
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
}
@Override
public void getDBInfo() {
getConnection();
DatabaseMetaData dmd;
try {
dmd = con.getMetaData();
System.out.println("Database Name :: "+dmd.getDatabaseProductName());
System.out.println("Driver :: "+dmd.getDriverName());
System.out.println("Database Version :: "+dmd.getDatabaseMajorVersion());
ResultSet rs=dmd.getTables(null, null,null,null);
while(rs.next()){
System.out.println(rs.getString("TABLE_NAME"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
closeConnection();
}
}
}
|
package patterns.structure.adaptor;
public class TFCardImpl implements TFCard
{
@Override
public String readTF()
{
return "read from tf card";
}
@Override
public int writeTF(String msg)
{
System.out.println("write into tf card" + msg);
return 1;
}
}
|
package com.jaiaxn.design.pattern.behavioral.chain.of.responsibility;
/**
* @author: wang.jiaxin
* @date: 2019年08月26日
* @description:
**/
public class ErrorLogger extends AbstractLogger {
public ErrorLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Error Logger: " + message);
}
}
|
package factorypattern.noodle.simplefactory;
/**
* The shop sales beef noodle.
*
* @author Thomson Tang
*/
public class NoodleShop {
SimpleNoodleFactory noodleFactory; // now we give BeefNodeShop a reference to a SimpleNoodleFactory.
// BeefNoodleShop gets the factory passed to it in the constructor.
public NoodleShop(SimpleNoodleFactory noodleFactory) {
this.noodleFactory = noodleFactory;
}
/**
* Basic order for a simple beef noodle.
*
* @return #BeefNoodle
*/
Noodle orderBeefNoodle() {
Noodle noodle =
new Noodle(); // for flexibility, we really want this to be an abstract class or interface, but we can't directly instantiate either of those.
noodle.prepare();
noodle.make();
noodle.cook();
noodle.fill();
return noodle;
}
/**
* Order the beef noodle by specific type.
*
* @param type the type
* @return #BeefNoodle
*/
Noodle orderBeefNoodle(String type) {
/*
* ues the factory to create noodle by simply passing on the type of the order.
* we've replaced the new operator with a create method on the factory object,
* no more concrete instantiation here.
*/
Noodle noodle = noodleFactory.createNoodle(type);
// if (type.equals("thinner")) {
// noodle = new ThinnerBeefNoodle();
// } else if (type.equals("thin")) {
// noodle = new ThinBeefNoodle();
// } else if (type.equals("thick")) {
// noodle = new ThickBeefNoodle();
// } else {
// noodle = new BeefNoodle();
// }
noodle.prepare();
noodle.make();
noodle.fill();
return noodle;
}
}
|
package meetingrooms;
import java.util.Scanner;
public class Controller {
private Office office;
private Scanner scanner = new Scanner(System.in);
public void readOffice() {
office = new Office();
System.out.println("Hány darab tárgyalót szeretnél rögzíteni?");
int numberOfMeetengRooms = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < numberOfMeetengRooms; i++) {
System.out.println((i + 1) + " tárgyaló neve: ");
String name = scanner.nextLine();
System.out.println((i + 1) + " tárgyaló szélessége (méter): ");
int width = scanner.nextInt();
scanner.nextLine();
System.out.println((i + 1) + "Tárgyaló hosszúsága (méter): ");
int length = scanner.nextInt();
scanner.nextLine();
office.addMeetingRoom(new MeetingRoom(name, length, width));
}
}
public void printMenu() {
System.out.println("MENÜ");
System.out.println("1. Tárgyalók sorrendben");
System.out.println("2. Tárgyalók visszafele sorrendben");
System.out.println("3. Minden második tárgyaló");
System.out.println("4. Területek");
System.out.println("5. Keresés pontos név alapján");
System.out.println("6. Keresés névtöredék alapján");
System.out.println("7. Keresés terület alapján");
System.out.println("0. Kilépés");
}
public void runMenu() {
printMenu();
int menuIndex = scanner.nextInt();
scanner.nextLine();
switch (menuIndex) {
case 0:
System.out.println("Viszont látásra");
return;
case 1:
office.printNames();
break;
case 2:
office.printNamesReverse();
break;
case 3:
office.printEventNames();
break;
case 4:
office.printAreas();
break;
case 5:
System.out.println("Keresett tárgyaló neve:");
office.printMeetingRoomsWithName(scanner.nextLine());
break;
case 6:
System.out.println("Keresett tárgyaló nevének töredéke:");
office.printMeetingRoomsContaint(scanner.nextLine());
break;
case 7:
System.out.println("Keresett tárgyaló területe:");
int area = scanner.nextInt();
scanner.nextLine();
office.printAreasLargerThan(area);
break;
default:
System.out.println("Érvénytelen menüpont");
break;
}
runMenu();
}
public static void main(String[] args) {
Controller controller = new Controller();
controller.readOffice();
controller.runMenu();
}
}
|
package model.fighter;
import model.board.Content;
import model.element.Blood;
import model.fighter.level.EnemyLevel;
public class Enemy2 extends Enemy {
public Enemy2(int level) {
super(new EnemyLevel(level, 1, 1));
}
@Override
public Content contentLeft() {
return new Blood();
}
@Override
public void heroMoveListener() {
}
}
|
package edu.neu.ccs.cs5010;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Created by xwenfei on 10/23/17.
*/
public class GenerateFile {
private static final String HEADER = "Node ID, Recommended nodes";
/**
* Get the current candy list and file name, create the file.
*
* @param recomendMap the recomend map
* @param dirName the fileName
* @throws IllegalArgumentException if file is not created successfully
*/
public void writeFile(Map<Integer, List<Integer>> recomendMap, String dirName) throws IllegalArgumentException {
if (dirName== null || recomendMap == null) {
throw new IllegalArgumentException("filename and friendList should not be null");
}
//java.io.FileWriter Writer = null;
File directory = new File(dirName);
boolean res = directory.mkdir();
if (!res) {
System.out.print("");
}
File outputFile = new File(directory.getPath(), "file3.csv");
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()));
writer.write(HEADER);
writer.write("\n");
Iterator<Map.Entry<Integer, List<Integer>>> iterator = recomendMap.entrySet().iterator();
while(iterator.hasNext()) {
StringBuffer stringBuffer = new StringBuffer();
Map.Entry<Integer, List<Integer>> entry = iterator.next();
int userID = entry.getKey();
stringBuffer.append(userID + " ");
List<Integer> list = entry.getValue();
for(int i=0; i<list.size(); i++) {
stringBuffer.append(list.get(i) + " ");
}
writer.write(stringBuffer.toString());
writer.write("\n");
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
// try {
// Writer = new FileWriter(dirName);
// Writer.write("User's ID, Gender, Age, City\n");
// for (Users user: friendList) {
// Writer.write("Recomend ID" + " "+ user.getUsersID() + " ");
// Writer.write("Gender" + " " + user.getGender() + " ");
// Writer.write("Age" + " " + user.getAge() + " ");
// Writer.write("City" + " " + user.getCity() + "\n");
// }
// } catch(IOException e) {
// e.getStackTrace();
// } finally {
// if (Writer != null) {
// try {
// Writer.close();
// } catch (IOException e) {
// e.getStackTrace();
// }
// }
// }
}
}
|
package com.metoo.module.app.domain;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.metoo.core.constant.Globals;
import com.metoo.core.domain.IdEntity;
/**
*
* <p>
* Title: AppPushUser.java
* </p>
*
* <p>
* Description: 推送,绑定用户信息
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.koala.com
* </p>
*
* @author lixiaoyang
*
* @date 2015-2-7
*
* @version koala_b2b2c 2.0
*/
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Entity
@Table(name = Globals.DEFAULT_TABLE_SUFFIX + "app_push_user")
public class AppPushUser extends IdEntity {
private String app_id;// 设备id
private String app_type;// 设备类别,Android,ios
private String app_channelId;// 设备频道id
private String user_id;// 用户id,若果没登陆即为空
private String app_userRole;// App用户角色,预留,区分买家app和商家app,"buyer"为买家,seller为商家
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getApp_type() {
return app_type;
}
public void setApp_type(String app_type) {
this.app_type = app_type;
}
public String getApp_userRole() {
return app_userRole;
}
public void setApp_userRole(String app_userRole) {
this.app_userRole = app_userRole;
}
public String getApp_channelId() {
return app_channelId;
}
public void setApp_channelId(String app_channelId) {
this.app_channelId = app_channelId;
}
public String getApp_id() {
return app_id;
}
public void setApp_id(String app_id) {
this.app_id = app_id;
}
}
|
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
public class Graph extends ApplicationFrame
{
private static double equation (double e){
double a = 0.30;
double o = 5.67* Math.pow(10, -8);
double Save = 342;
double partOne = (2*(1-a)*Save);
double partTwo = (o*(2-e));
double prePower = partOne/partTwo;
double fraction = (double) 1/4;
return Math.pow(prePower, fraction);
}
private Graph( String applicationTitle , String chartTitle )
{
super(applicationTitle);
JFreeChart lineChart = ChartFactory.createLineChart(
chartTitle,
"ε","Tp",
createDataset(),
PlotOrientation.VERTICAL,
true,true,false);
ChartPanel chartPanel = new ChartPanel( lineChart );
chartPanel.setPreferredSize( new java.awt.Dimension( 560 , 367 ) );
setContentPane( chartPanel );
}
private DefaultCategoryDataset createDataset( )
{
DefaultCategoryDataset dataset = new DefaultCategoryDataset( );
dataset.addValue( equation(0.0) , "Tp", "0.0" );
dataset.addValue( equation(0.1) , "Tp", "0.1" );
dataset.addValue( equation(0.2) , "Tp", "0.2" );
dataset.addValue( equation(0.3) , "Tp", "0.3" );
dataset.addValue( equation(0.4) , "Tp", "0.4" );
dataset.addValue( equation(0.5) , "Tp", "0.5" );
dataset.addValue( equation(0.6) , "Tp", "0.6" );
dataset.addValue( equation(0.7) , "Tp", "0.7" );
dataset.addValue( equation(0.8) , "Tp", "0.8" );
dataset.addValue( equation(0.9) , "Tp", "0.9" );
dataset.addValue( equation(1.0) , "Tp", "1.0" );
return dataset;
}
public static void main( String[ ] args )
{
Graph chart = new Graph(
"Tp vs ε" ,
"Tp vs ε");
chart.pack( );
RefineryUtilities.centerFrameOnScreen( chart );
chart.setVisible( true );
}
}
|
package netAnalysis;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Random;
import DataModel.NodeUnit;
import FactorGenerate.Generator;
import Simulation.StaticStartup;
public class main {
static final int DAV = 0;
static final int DAV_OPT = 3;
static final int XIAOMI = 1;
static final int CHOUJIANG = 2;
public static int Day = 1440;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DataOperation di = new DataOperation();
boolean flag = false;
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(
"E:\\data_op\\nodes"));
while (true) {
di.initNetwork.add((NodeUnit) ois.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
flag = true;
} catch (EOFException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (flag) {
di.importNetwork("E:\\data_op\\twitter_combined.txt");
di.importBlogs("E:\\data_op\\reposts");
di.sort();
Generator.FactorGenerator(di.initNetwork, di.initBlogs);
di.save();
}
System.out.println(">>>读文件结束");
//di.dataMining();
int[] es = {500, 1000, 1500, 2000};
for(int i:es){
System.out.println(">>>simulating with "+i+" energy");
for(NodeUnit node:di.initNetwork){
node.diactivate();
}
StaticStartup mypropogation=new StaticStartup(di.initNetwork,1000, 10*Day, 100000, 0.0005);
int s[]= di.generateInit(XIAOMI, i);
mypropogation.Run(s, i+".txt");
}
}
}
|
package Http;
import java.io.*;
import java.net.Socket;
public class RequestHandler {
private static final int BUFFER_SIZE = 4096;
public void handleRequest(Socket sock) {
OutputStream out = null;
int value;
try {
String request = RequestMethod.getRequest(sock);
System.out.println(request);
String method = RequestMethod.getMethod(request);
switch (method) {
case "GET":
String uri = RequestMethod.getRequestUri(request);
System.out.println("Received request for - " + uri);
boolean referer = RequestMethod.checkReferer(request);
ResponeMethod responeMethod = new ResponeMethod();
responeMethod.methodrespone(sock, uri);
break;
case "POST":
break;
case "PUT":
break;
case "HEAD":
break;
case "DELETE":
break;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package machinery.artisan.controllers;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldListCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.input.KeyCode;
import javafx.util.StringConverter;
import javafx.util.converter.NumberStringConverter;
import machinery.artisan.Orchestrator;
import machinery.artisan.data.Recipe;
import machinery.artisan.data.RecipeVariant;
import machinery.artisan.data.RecipeVersion;
import machinery.artisan.data.store.RecipeStore;
import machinery.artisan.ui.IngredientInputBuilder;
import machinery.artisan.ui.StepInputBuilder;
import machinery.artisan.ui.builders.ExistingRecipeBuilder;
import machinery.artisan.ui.builders.ExistingVariantBuilder;
import machinery.artisan.ui.builders.NewRecipeBuilder;
import machinery.artisan.ui.builders.NewVariantBuilder;
import machinery.artisan.ui.builders.NewVersionBuilder;
import machinery.artisan.ui.builders.RecipeBuilder;
import machinery.artisan.ui.builders.VariantBuilder;
import machinery.artisan.ui.builders.VersionBuilder;
import java.net.URL;
import java.util.ResourceBundle;
public final class CreateRecipeController implements Initializable
{
public enum Creating
{
RECIPE, VARIANT, VERSION
}
// dependencies
private final RecipeStore recipeStore;
private final Orchestrator orchestrator;
// inputs
private final Creating creating;
/*private final Optional<Recipe> recipe;
private final Optional<RecipeVariant> variant;
private final Optional<RecipeVersion> version;
// state
private final RecipeInputBuilder inputBuilder;*/
private final RecipeBuilder recipeBuilder;
private final VariantBuilder variantBuilder;
private final VersionBuilder versionBuilder;
@FXML
private TextField recipeName, variantName, versionNumber, description;
@FXML
private TableView<IngredientInputBuilder> ingredients;
@FXML
private TableColumn<IngredientInputBuilder, Double> quantityColumn;
@FXML
private TableColumn<IngredientInputBuilder, String> unitColumn, nameColumn;
@FXML
private TextField quantityInput, unitInput, ingredientNameInput;
@FXML
private Button addIngredientButton;
@FXML
private ListView<StepInputBuilder> steps;
@FXML
private TextField stepInput;
@FXML
private Button addStepButton;
@FXML
private Button backButton, saveButton;
public static CreateRecipeController forNewRecipe(final RecipeStore recipeStore, final Orchestrator orchestrator)
{
final RecipeBuilder recipeBuilder = new NewRecipeBuilder();
final VariantBuilder variantBuilder = new NewVariantBuilder(recipeBuilder);
final VersionBuilder versionBuilder = new NewVersionBuilder(variantBuilder);
return new CreateRecipeController(recipeStore, orchestrator, Creating.RECIPE,
recipeBuilder, variantBuilder, versionBuilder);
}
public static CreateRecipeController forNewVariant(final RecipeStore recipeStore, final Orchestrator orchestrator,
final RecipeVersion branchPoint)
{
final RecipeVariant variant = branchPoint.getVariant();
final Recipe recipe = variant.getRecipe();
final RecipeBuilder recipeBuilder = new ExistingRecipeBuilder(recipe);
final VariantBuilder variantBuilder = new NewVariantBuilder(recipeBuilder, variant);
final VersionBuilder versionBuilder = new NewVersionBuilder(variantBuilder, branchPoint, 1);
return new CreateRecipeController(recipeStore, orchestrator, Creating.VARIANT,
recipeBuilder, variantBuilder, versionBuilder);
}
public static CreateRecipeController forNewVersion(final RecipeStore recipeStore, final Orchestrator orchestrator,
final RecipeVersion latestVersion)
{
final RecipeVariant variant = latestVersion.getVariant();
final Recipe recipe = variant.getRecipe();
final RecipeBuilder recipeBuilder = new ExistingRecipeBuilder(recipe);
final VariantBuilder variantBuilder = new ExistingVariantBuilder(variant);
final VersionBuilder versionBuilder = new NewVersionBuilder(variantBuilder, latestVersion,
latestVersion.getVersion() + 1);
return new CreateRecipeController(recipeStore, orchestrator, Creating.VERSION,
recipeBuilder, variantBuilder, versionBuilder);
}
private CreateRecipeController(final RecipeStore recipeStore, final Orchestrator orchestrator,
final Creating creating, final RecipeBuilder recipeBuilder,
final VariantBuilder variantBuilder,
final VersionBuilder versionBuilder)
{
this.recipeStore = recipeStore;
this.orchestrator = orchestrator;
this.creating = creating;
this.recipeBuilder = recipeBuilder;
this.variantBuilder = variantBuilder;
this.versionBuilder = versionBuilder;
}
@Override
public void initialize(final URL location, final ResourceBundle resources)
{
switch (creating)
{
case VERSION:
versionSetup();
break;
case VARIANT:
variantSetup();
break;
case RECIPE:
recipeSetup();
break;
default:
throw new IllegalStateException("Unsupported Creating value of: '" + creating + "'");
}
// Set up bindings for the builder
recipeName.textProperty().bindBidirectional(recipeBuilder.nameProperty());
variantName.textProperty().bindBidirectional(variantBuilder.nameProperty());
versionNumber.textProperty().bindBidirectional(versionBuilder.versionNumberProperty(), new NumberStringConverter());
description.textProperty().bindBidirectional(variantBuilder.descriptionProperty());
quantityColumn.setCellValueFactory(cellData -> cellData.getValue().quantityProperty().asObject());
unitColumn.setCellValueFactory(cellData -> cellData.getValue().unitProperty());
unitColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
ingredients.itemsProperty().bindBidirectional(versionBuilder.ingredientsProperty());
ingredients.setOnKeyPressed(event ->
{
// I was worried that hooking up to keys here would intercept edits within the text cells,
// but it looks like everything operates as hoped-for.
if (event.getCode().equals(KeyCode.BACK_SPACE) || event.getCode().equals(KeyCode.DELETE))
{
final IngredientInputBuilder selected = ingredients.getSelectionModel().getSelectedItem();
if (selected != null)
{
ingredients.getItems().remove(selected);
}
}
});
steps.itemsProperty().bindBidirectional(versionBuilder.stepsProperty());
steps.setCellFactory(TextFieldListCell.forListView(new StringConverter<StepInputBuilder>()
{
@Override
public String toString(final StepInputBuilder step)
{
return step.getInstruction();
}
@Override
public StepInputBuilder fromString(final String string)
{
return new StepInputBuilder(string);
}
}));
steps.setOnKeyPressed(event ->
{
// I was worried that hooking up to keys here would intercept edits within the text cells,
// but it looks like everything operates as hoped-for.
if (event.getCode().equals(KeyCode.BACK_SPACE) || event.getCode().equals(KeyCode.DELETE))
{
final StepInputBuilder selected = steps.getSelectionModel().getSelectedItem();
if (selected != null)
{
steps.getItems().remove(selected);
}
}
});
// Generic widget setup
addIngredientButton.setOnAction(event -> addCurrentIngredient());
addStepButton.setOnAction(event -> addCurrentStep());
backButton.setOnAction(event -> orchestrator.recipeSummaries(false));
saveButton.setOnAction(event -> save());
}
private void versionSetup()
{
recipeName.setDisable(true);
variantName.setDisable(true);
versionNumber.setDisable(true);
description.setDisable(true);
}
private void variantSetup()
{
recipeName.setDisable(true);
versionNumber.setDisable(true);
}
private void recipeSetup()
{
versionNumber.setDisable(true);
}
private void addCurrentIngredient()
{
final double quantity = Double.parseDouble(quantityInput.getText());
final String unit = unitInput.getText();
final String ingredientName = ingredientNameInput.getText();
versionBuilder.withIngredient(new IngredientInputBuilder(quantity, unit, ingredientName));
quantityInput.clear();
unitInput.clear();
ingredientNameInput.clear();
}
private void addCurrentStep()
{
versionBuilder.withStep(new StepInputBuilder(stepInput.getText()));
stepInput.clear();
}
private void save()
{
// No matter what, we're always building a new version. So if we use the output
// of the version's builder, it should trigger builds on all other builders as necessary.
if (!versionBuilder.isValid())
{
final Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Problem Saving");
alert.setHeaderText("I need more information!");
alert.setContentText("Please make sure you've filled in all relevant fields.");
alert.showAndWait();
return;
}
final RecipeVersion finalVersion = versionBuilder.build();
recipeStore.saveEntity(finalVersion);
orchestrator.recipeSummaries(finalVersion);
}
}
|
import javafx.scene.input.DataFormat;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import sun.rmi.rmic.iiop.Generator;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class CommonAPI {
public static WebDriver driver = null;
@Parameters({"platform", "url", "browser"})
@BeforeMethod
public static WebDriver setupDriver(String platform, String url, String browser) {
if (platform.equalsIgnoreCase("mac") && browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "/Users/zann/IdeaProjects/Google/generic/src/main/resources/drivers/chromedriver");
} else if (platform.equalsIgnoreCase("windows") && browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "src/main/resources/drivers/chromedriver.exe");
}
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(url);
return driver;
}
public static void getScreenshot(WebDriver driver) {
DateFormat df = new SimpleDateFormat("(MM.dd.yyyy-HH:mma)");
Date date = new Date();
String name = df.format(date);
File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(file, new File("src/screenshots/" + name + ".png"));
} catch (IOException e) {
e.printStackTrace();
}
driver.quit();
}
@AfterMethod
public void quitDriver() {
driver.quit();
}
public void sleepFor(int Seconds) {
try {
Thread.sleep(Seconds * 1000);
} catch (Exception e) {
}
}
}
|
package haircutter.dataModels;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
@Entity
public class Reservation {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Getter @Setter private Long reservationId;
@Getter @Setter private Date date;
@Getter @Setter private Long userId;
@Getter @Setter private Long employeeId;
// @Getter private List<Appointment>
protected Reservation() {}
public Reservation(Date date, Long userId, Long employeeId) {
this.date = date;
this.userId = userId;
this.employeeId = employeeId;
}
@Override
public String toString() {
return String.format(
"Reservation[reservationId=%d, data='%s']",
reservationId, date);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/* URL
http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=491&sca=50&sfl=wr_hit&stx=1208&sop=and
*/
/* 문제 요약
목장 : a~z, A~Y
헛간 : Z
- 헛간을 제외한 대문자 목장에 소 한마리씩
- 각 목장끼리 길이 연결이 안된 경우도 있고, 두 목장 사이의 길이 2개 이상인 경우도 있음 (여기서 Dijstra로 PriorityQueue 사용 결정)
- 적어도 한 개 이상의 목장에서 헛간으로 가는 길이 존재 (헛간으로 가지 못하는 경우는 없음)
- 길은 일방통행이 아니고, 모든 소의 속도는 동일
결과 : 가장 먼저 헛간에 도착하는 소가 원래 있는 목장 번호, 그 소가 걷는 거리(시간)
*/
public class Main1208_귀가_주석 {
static char leastCow; // 가장 먼저 도착한 소
static int leastTime; // 가장 먼저 도착한 소가 걸린 시간
static TreeSet<Character> cows, farms; // cows: 길이 있는 대문자 목장, farms: 길이 있는 모든 목장
static TreeMap<Character, Road> roads; // 인접 리스트 Map<출발목장번호, 길(도착목장번호, 소요시간)>
static final int MAX_TIME = 99999; // 최대 소요 시간 설정 : 1000 * 52 (길의 최대 길이 * 길 경유 최대 개수)
public static void main(String[] args) throws IOException {
input(); // cows, farms, roads 준비
// cows : 소가 헛간으로 가는 최소시간을 구하기 위해서, 소가 있는 목장만 고르는 작업 필요
// farms : 소가 없는 목장은 경유지로 쓰이기 때문에, visited와 distance 자료 생성을 위해 필요
// roads : 각 목장마다 연결된 목장과 소요시간을 저장하는 인접 리스트
goHuts(); // 길이 있는 대문자 목장(즉, 소가 있는 목장)마다 헛간 도착 시간 계산 및 최소값 갱신
print();
}
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine().trim());
int p = Integer.parseInt(st.nextToken());
int len;
char a, b;
leastTime = MAX_TIME;
cows = new TreeSet<>(); // cows, farms 목장의 리스트이므로
farms = new TreeSet<>(); // 중복 저장을 피하기 위해, 알파벳 순서 정렬을 위해, TreeSet 사용
roads = new TreeMap<>(); // 목장 인덱스를 char 타입으로 관리해야 하므로 Map<Character, Road> 사용
for (int i = 0; i < p; i++) {
st = new StringTokenizer(br.readLine());
a = st.nextToken().charAt(0);
b = st.nextToken().charAt(0);
len = Integer.parseInt(st.nextToken());
// 길에 방향이 없으므로 양방향 모두 고려
input(a, b, len);
input(b, a, len);
farms.add(a);
farms.add(b);
if (Character.isUpperCase(a) && a != 'Z') cows.add(a);
if (Character.isUpperCase(b) && b != 'Z') cows.add(b);
}
}
private static void input(char a, char b, int len) {
Road road = new Road(b, len);
if (!roads.containsKey(a)) roads.put(a, road);
else roads.get(a).add(road);
}
private static void goHuts() {
for (char cow : cows) goHut(cow); // 길이 있는 대문장 목장마다 헛간으로 가는 시간 계산
}
private static void goHut(char start) {
PriorityQueue<Cow> que = new PriorityQueue<>();
HashMap<Character, Boolean> visit = new HashMap<>();
HashMap<Character, Integer> minTimes = new HashMap<>();
for (char farm : farms) visit.put(farm, false); // 모든 목장 방문 false 처리
for (char farm : farms) minTimes.put(farm, MAX_TIME); // 모든 목장 초기값 설정
minTimes.put(start, 0); // 시작 목장 소요시간 0 설정
que.offer(new Cow(start, minTimes.get(start))); // queue에 담고 시작
Cow cow;
Road road;
char fromHut, toHut; // fromHut : 경유 목장 번호, toHut : 목표 목장 번호
int startFrom_Time, fromTo_Time; // startFrom_Time : "시작 목장 -> 경유 목장" 최소 소요 시간
while (!que.isEmpty()) { // fromTo_Time : "시작 목장 -> 목표 목장" 최소 소요 시간
cow = que.poll();
fromHut = cow.hut;
startFrom_Time = cow.time;
if (visit.get(fromHut)) continue;
if (fromHut == 'Z') break;
visit.put(fromHut, true);
road = roads.get(fromHut); // 경유 목장에서 갈 수 있는 목표 목장이 담긴 인접 리스트
while (road !=null) {
toHut = road.hut;
fromTo_Time = road.time;
if (!visit.get(toHut) &&
startFrom_Time + fromTo_Time < minTimes.get(toHut)) {
minTimes.put(toHut, startFrom_Time + fromTo_Time);
que.offer(new Cow(toHut, minTimes.get(toHut)));
}
road = road.next; // 다음 목표 목장 갱신
}
}
if (minTimes.get('Z') < leastTime) { // 해당 시작 목장의 헛간 도착 시간 계산이 끝났으므로
leastCow = start; // 최소 도착 시간과 그 시작 목장 갱신
leastTime = minTimes.get('Z');
}
}
private static void print() {
System.out.println(leastCow + " " + leastTime);
}
}
//class Cow implements Comparable<Cow> {
// char hut;
// int time;
// public Cow(char hut, int time) {
// this.hut = hut;
// this.time = time;
// }
// public String toString() {
// return "[목장 : " + hut + ", 시간=" + time + "]";
// }
// public int compareTo(Cow other) {
// return this.time-other.time;
// }
//}
//
//class Road {
// char hut;
// int time;
// Road next;
// public Road(char hut, int time) {
// this.hut = hut;
// this.time = time;
// }
// public String toString() {
// return "[hut=" + hut + ", time=" + time + ", next=" + next + "]";
// }
// public void add(Road road) {
// road.next = this.next;
// this.next = road;
// }
//}
|
package nh.automation.tools.serviceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nh.automation.tools.dao.UserMapper;
import nh.automation.tools.entity.User;
@Service
public class UserServiceImp {
@Autowired
private UserMapper userMapper;
/**
* 根据用户名查询用户
* @param userName
* @return
*/
public User getUser(String userName){
User user=null;
try {
user = userMapper.getUser(userName);
} catch (Exception e) {
e.printStackTrace();
return user;
}
return user;
}
}
|
package leetCode.copy.Array;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* 295. 数据流的中位数
* 中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。
*
* 例如,
* [2,3,4] 的中位数是 3
* [2,3] 的中位数是 (2 + 3) / 2 = 2.5
*
* 设计一个支持以下两种操作的数据结构:
* void addNum(int num) - 从数据流中添加一个整数到数据结构中。
* double findMedian() - 返回目前所有元素的中位数。
*
* 示例:
* addNum(1)
* addNum(2)
* findMedian() -> 1.5
* addNum(3)
* findMedian() -> 2
*
* 进阶:
* 如果数据流中所有整数都在 0 到 100 范围内,你将如何优化你的算法?基数排序的思想,使用长度101的int数组记录每个值的个数。
* 如果数据流中 99% 的整数都在 0 到 100 范围内,你将如何优化你的算法?使用长度102的数组
*
* 链接:https://leetcode-cn.com/problems/find-median-from-data-stream
*/
public class no295_find_median_from_data_stream {
public static void main(String args[]){
MedianFinder obj = new MedianFinder();
for(int i = 1;i<=10;i++) {
obj.addNum3(i);
System.out.println("add i:"+i+" mid:" + obj.findMedian3());
}
System.out.println();
MedianFinder obj2 = new MedianFinder();
for(int i = 10;i>0;i--) {
obj2.addNum3(i);
System.out.println("add i:"+i+" mid:" + obj2.findMedian3());
}
System.out.println();
MedianFinder obj3 = new MedianFinder();
int nums[] = new int[]{-40,-12,-16,-14};
for(int i = 0;i<nums.length;i++) {
obj3.addNum3(nums[i]);
System.out.println("add i:"+nums[i]+" mid:" + obj3.findMedian3());
}
System.out.println();
MedianFinder obj4 = new MedianFinder();
nums = new int[]{40,12,16,14};
for(int i = 0;i<nums.length;i++) {
obj4.addNum3(nums[i]);
System.out.println("add i:"+nums[i]+" mid:" + obj4.findMedian3());
}
}
}
class MedianFinder {
//如果我们可以用以下方式维护两个堆:
//1 用于存储输入数字中较小一半的最大堆
//2 用于存储输入数字的较大一半的最小堆
// peek 最小值(从小到大 堆排序)
private PriorityQueue<Integer> pMinUp = null;
// peek 最大值(从大到小 堆排序)
private PriorityQueue<Integer> pMaxDown = null;
private int size = 0;
/** initialize your data structure here. */
public MedianFinder() {
pMinUp = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2;
}
});
pMaxDown = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
}
/**
* 我感觉 逻辑不是很清晰 可以简化
* @param num
*/
public void addNum(int num) {
size++;
int shouldSize = (1+size)/2 ;
int leftSize = size - shouldSize;
int midUp = Integer.MIN_VALUE;
if(pMinUp.size()>0) midUp = pMinUp.peek();
int midDown = Integer.MIN_VALUE;
if(pMaxDown.size()>0) midDown = pMaxDown.peek();
if ((num >= midUp) || (pMaxDown.size() > 0) && (num > midDown)) {
if (pMinUp.size() < shouldSize) {
pMinUp.offer(num);
} else if (pMaxDown.size() < leftSize) {
if(num > midUp){
pMinUp.poll();
pMinUp.offer(num);
pMaxDown.offer(midUp);
}else {
pMaxDown.offer(num);
}
} else if (pMinUp.size() == shouldSize) {
pMinUp.poll();
pMinUp.offer(num);
pMaxDown.offer(midUp);
}
} else {
if (pMinUp.size() < shouldSize) {
pMinUp.offer(midDown);
pMaxDown.poll();
pMaxDown.offer(num);
} else if (pMinUp.size() == shouldSize) {
if(num > midUp){
pMinUp.poll();
pMinUp.offer(num);
pMaxDown.offer(midUp);
}else {
pMaxDown.offer(num);
}
}
}
}
/**
* 这种方法 思路清晰些 时间 慢点点
* @param num
*/
public void addNum2(int num) {
size++;
int shouldSize = (1+size)/2 ;
int leftSize = size - shouldSize;
int midUp = Integer.MIN_VALUE;
if(pMinUp.size()>0) midUp = pMinUp.peek();
int midDown = Integer.MIN_VALUE;
if(pMaxDown.size()>0) midDown = pMaxDown.peek();
// 上半区间
if (num > midUp) {
if (pMinUp.size() < shouldSize) {
pMinUp.offer(num);
} else if (pMinUp.size() == shouldSize) {
pMinUp.poll();
pMinUp.offer(num);
pMaxDown.offer(midUp);
}
}
// 中部区间
else if((pMaxDown.size() > 0) && (num >= midDown)){
if (pMinUp.size() < shouldSize) {
pMinUp.offer(num);
} else if (pMinUp.size() == shouldSize) {
pMaxDown.offer(num);
}
}
// 下半区间
else {
if (pMinUp.size() < shouldSize) {
pMinUp.offer(midDown);
pMaxDown.poll();
pMaxDown.offer(num);
} else if (pMinUp.size() == shouldSize) {
pMaxDown.offer(num);
}
}
}
public double findMedian() {
if(size%2 == 0){
int p1 = pMinUp.peek();
int p2 = pMaxDown.peek();
return (p1+p2)/2.0;
}else{
int result = pMinUp.peek();
return (double)result;
}
}
/**
* 参考 很简洁 思想太妙了
* https://leetcode-cn.com/problems/find-median-from-data-stream/solution/you-xian-dui-lie-python-dai-ma-java-dai-ma-by-liwe/
*
* @param num
*/
public void addNum3(int num) {
size += 1;
pMaxDown.offer(num);
pMinUp.add(pMaxDown.poll());
// 如果两个堆合起来的元素个数是奇数,小顶堆要拿出堆顶元素给大顶堆
if ((size & 1) != 0) {
pMaxDown.add(pMinUp.poll());
}
}
public double findMedian3() {
if ((size & 1) == 0) {
// 如果两个堆合起来的元素个数是偶数,数据流的中位数就是各自堆顶元素的平均值
return (double) (pMaxDown.peek() + pMinUp.peek()) / 2;
} else {
// 如果两个堆合起来的元素个数是奇数,数据流的中位数大顶堆的堆顶元素
return (double) pMaxDown.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
|
package com.devpmts.dropaline.parts;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.Focus;
import org.eclipse.e4.ui.di.Persist;
import org.eclipse.e4.ui.model.application.ui.basic.MPart;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import com.devpmts.dropaline.CORE;
import com.devpmts.dropaline.api.PimApi;
import com.devpmts.dropaline.gui.DROPALINE_GUI;
import com.devpmts.dropaline.parser.LineAndNote;
import com.devpmts.util.e4.DI;
@Singleton
public class NoteInputPart {
private static final int NOTE_HEIGHT = 230;
private Text noteInput;
@Inject
@Optional
private LineInputComposite lineInputComposite;
@Inject
@Optional
private MWindow window;
@Inject
@Optional
private MPart part;
@Inject
@Optional
@Named(DROPALINE_GUI.LINE_INPUT)
private Text lineInput;
@Inject
@Optional
@Named(CORE.DEFAULT_API)
private PimApi defaultApi;
@Inject
public NoteInputPart() {
System.err.println("create NotePart");
DI.set(NoteInputPart.class, this);
DI.injectContextIn(this);
}
@PostConstruct
public void postConstruct(Composite parent) {
noteInput = new Text(parent, SWT.MULTI);
noteInput.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(org.eclipse.swt.events.KeyEvent evt) {
noteFieldKeys(evt);
}
});
collapse();
DI.set(DROPALINE_GUI.NOTE_INPUT, noteInput);
}
void noteFieldKeys(org.eclipse.swt.events.KeyEvent evt) {
switch (evt.keyCode) {
case KeyEvent.VK_O: {
// TODO
if (evt.stateMask == 1) {
assert false;
}
break;
}
case KeyEvent.VK_ENTER: {
if (evt.stateMask == 2) {
defaultApi.parse(new LineAndNote(lineInput.getText(), noteInput.getText()));
}
break;
}
case KeyEvent.VK_UP: {
try {
if (noteInput.getCaretPosition() == 0) {
lineInputComposite.collapseNotes();
return;
}
int maxChar = new BufferedReader(new StringReader(noteInput.getText())).readLine().length();
int noteCaret = noteInput.getCaretPosition();
if (noteCaret <= maxChar) {
// int taskLength = DROPALINE.lineInput.getText().length();
// int taskCaret = (taskLength > noteCaret) ? noteCaret :
// taskLength;
lineInput.setFocus();
// input.getTaskField().setCaretPosition(taskCaret);
}
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
break;
}
}
}
@Focus
public void onFocus() {
}
@Persist
public void save() {
}
public void expand() {
part.setVisible(true);
noteInput.setFocus();
window.setHeight(50 + LineInputComposite.LINE_HEIGHT + NOTE_HEIGHT);
DI.set(DROPALINE_GUI.ACTIVE_FIELD, noteInput);
}
public void collapse() {
part.setVisible(false);
window.setHeight(50 + LineInputComposite.LINE_HEIGHT);
DI.set(DROPALINE_GUI.ACTIVE_FIELD, lineInput);
}
public void setText(String content) {
noteInput.setText(content);
}
}
|
package com.example.smartphonesensing2.localization.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
public class AP1 extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "accelerometer.ap1";
// query statements to create table
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
public static final String SQL_CREATE_TABLE =
"CREATE TABLE " + TestingField.TABLE_NAME + " (" +
TestingField.FIELD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
TestingField.FIELD_CELL + TEXT_TYPE + COMMA_SEP +
TestingField.FIELD_0 + TEXT_TYPE + COMMA_SEP +
TestingField.FIELD_1 + TEXT_TYPE +
" );";
// query statement to delete table
private static final String SQL_DELETE_TABLE =
"DROP TABLE IF EXISTS " + TestingField.TABLE_NAME;
public AP1(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_TABLE);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
/*Table 2 to store new records during testing*/
public static abstract class TestingField implements BaseColumns {
public static final String TABLE_NAME = "ap";
public static final String FIELD_ID = "_id";
public static final String FIELD_CELL = "cell";
public static final String FIELD_0 = "rssi0";
public static final String FIELD_1 = "rssi1";
public static final String FIELD_2 = "rssi2";
public static final String FIELD_3 = "rssi3";
public static final String FIELD_4 = "rssi4";
public static final String FIELD_5 = "rssi5";
public static final String FIELD_6 = "rssi6";
public static final String FIELD_7 = "rssi7";
public static final String FIELD_8 = "rssi8";
public static final String FIELD_9 = "rssi9";
public static final String FIELD_10 = "rssi10";
public static final String FIELD_11 = "rssi11";
public static final String FIELD_12 = "rssi12";
public static final String FIELD_13 = "rssi13";
public static final String FIELD_14 = "rssi14";
public static final String FIELD_15 = "rssi15";
public static final String FIELD_16 = "rssi16";
public static final String FIELD_17 = "rssi17";
public static final String FIELD_18 = "rssi18";
public static final String FIELD_19 = "rssi19";
public static final String FIELD_20 = "rssi20";
public static final String FIELD_21 = "rssi21";
public static final String FIELD_22 = "rssi22";
public static final String FIELD_23 = "rssi23";
public static final String FIELD_24 = "rssi24";
public static final String FIELD_25 = "rssi25";
public static final String FIELD_26 = "rssi26";
public static final String FIELD_27 = "rssi27";
public static final String FIELD_28 = "rssi28";
public static final String FIELD_29 = "rssi29";
public static final String FIELD_30 = "rssi30";
public static final String FIELD_31 = "rssi31";
public static final String FIELD_32 = "rssi32";
public static final String FIELD_33 = "rssi33";
public static final String FIELD_34 = "rssi34";
public static final String FIELD_35 = "rssi35";
public static final String FIELD_36 = "rssi36";
public static final String FIELD_37 = "rssi37";
public static final String FIELD_38 = "rssi38";
public static final String FIELD_39 = "rssi39";
public static final String FIELD_40 = "rssi40";
public static final String FIELD_41 = "rssi41";
public static final String FIELD_42 = "rssi42";
public static final String FIELD_43 = "rssi43";
public static final String FIELD_44 = "rssi44";
public static final String FIELD_45 = "rssi45";
public static final String FIELD_46 = "rssi46";
public static final String FIELD_47 = "rssi47";
public static final String FIELD_48 = "rssi48";
public static final String FIELD_49 = "rssi49";
public static final String FIELD_50 = "rssi50";
public static final String FIELD_51 = "rssi51";
public static final String FIELD_52 = "rssi52";
public static final String FIELD_53 = "rssi53";
public static final String FIELD_54 = "rssi54";
public static final String FIELD_55 = "rssi55";
public static final String FIELD_56 = "rssi56";
public static final String FIELD_57 = "rssi57";
public static final String FIELD_58 = "rssi58";
public static final String FIELD_59 = "rssi59";
public static final String FIELD_60 = "rssi60";
public static final String FIELD_71 = "rssi71";
public static final String FIELD_72 = "rssi72";
public static final String FIELD_73 = "rssi73";
public static final String FIELD_74 = "rssi74";
public static final String FIELD_75 = "rssi75";
public static final String FIELD_76 = "rssi76";
public static final String FIELD_77 = "rssi77";
public static final String FIELD_78 = "rssi78";
public static final String FIELD_79 = "rssi79";
public static final String FIELD_80 = "rssi80";
public static final String FIELD_81 = "rssi81";
public static final String FIELD_83 = "rssi82";
public static final String FIELD_84 = "rssi83";
public static final String FIELD_85 = "rssi85";
public static final String FIELD_86 = "rssi86";
public static final String FIELD_87 = "rssi87";
public static final String FIELD_88 = "rssi88";
public static final String FIELD_89 = "rssi89";
public static final String FIELD_90 = "rssi90";
public static final String FIELD_91 = "rssi91";
public static final String FIELD_92 = "rssi92";
public static final String FIELD_93 = "rssi93";
public static final String FIELD_94 = "rssi94";
public static final String FIELD_95 = "rssi95";
public static final String FIELD_96 = "rssi96";
public static final String FIELD_97 = "rssi97";
public static final String FIELD_98 = "rssi98";
public static final String FIELD_99 = "rssi99";
public static final String FIELD_100 = "rssi100";
public static final String FIELD_101 = "rssi101";
public static final String FIELD_102 = "rssi102";
public static final String FIELD_103 = "rssi103";
public static final String FIELD_104 = "rssi104";
public static final String FIELD_105 = "rssi105";
public static final String FIELD_106 = "rssi106";
public static final String FIELD_107 = "rssi107";
public static final String FIELD_108 = "rssi108";
public static final String FIELD_109 = "rssi109";
public static final String FIELD_110 = "rssi110";
public static final String FIELD_111 = "rssi111";
public static final String FIELD_112 = "rssi112";
public static final String FIELD_113 = "rssi113";
public static final String FIELD_114 = "rssi114";
public static final String FIELD_115 = "rssi115";
public static final String FIELD_116 = "rssi116";
public static final String FIELD_117 = "rssi117";
public static final String FIELD_118 = "rssi118";
public static final String FIELD_119 = "rssi119";
public static final String FIELD_120 = "rssi120";
public static final String FIELD_121 = "rssi121";
public static final String FIELD_122 = "rssi122";
public static final String FIELD_123 = "rssi123";
public static final String FIELD_124 = "rssi124";
public static final String FIELD_125 = "rssi125";
public static final String FIELD_126 = "rssi126";
public static final String FIELD_127 = "rssi127";
public static final String FIELD_128 = "rssi128";
public static final String FIELD_129 = "rssi129";
public static final String FIELD_130 = "rssi130";
public static final String FIELD_131 = "rssi131";
public static final String FIELD_132 = "rssi132";
public static final String FIELD_133 = "rssi133";
public static final String FIELD_134 = "rssi134";
public static final String FIELD_135 = "rssi135";
public static final String FIELD_136 = "rssi136";
public static final String FIELD_137 = "rssi137";
public static final String FIELD_138 = "rssi138";
public static final String FIELD_139 = "rssi139";
public static final String FIELD_140 = "rssi140";
public static final String FIELD_141 = "rssi141";
public static final String FIELD_142 = "rssi142";
public static final String FIELD_143 = "rssi143";
public static final String FIELD_144 = "rssi144";
public static final String FIELD_145 = "rssi145";
public static final String FIELD_146 = "rssi146";
public static final String FIELD_147 = "rssi147";
public static final String FIELD_148 = "rssi148";
public static final String FIELD_149 = "rssi149";
public static final String FIELD_150 = "rssi150";
public static final String FIELD_151 = "rssi151";
public static final String FIELD_152 = "rssi152";
public static final String FIELD_153 = "rssi153";
public static final String FIELD_154 = "rssi154";
public static final String FIELD_155 = "rssi155";
public static final String FIELD_156 = "rssi156";
public static final String FIELD_157 = "rssi157";
public static final String FIELD_158 = "rssi158";
public static final String FIELD_159 = "rssi159";
public static final String FIELD_160 = "rssi160";
public static final String FIELD_161 = "rssi161";
public static final String FIELD_162 = "rssi162";
public static final String FIELD_163 = "rssi163";
public static final String FIELD_164 = "rssi164";
public static final String FIELD_165 = "rssi165";
public static final String FIELD_166 = "rssi166";
public static final String FIELD_167 = "rssi167";
public static final String FIELD_168 = "rssi168";
public static final String FIELD_169 = "rssi169";
public static final String FIELD_170 = "rssi170";
public static final String FIELD_171 = "rssi171";
public static final String FIELD_172 = "rssi172";
public static final String FIELD_173 = "rssi173";
public static final String FIELD_174 = "rssi174";
public static final String FIELD_175 = "rssi175";
public static final String FIELD_176 = "rssi176";
public static final String FIELD_177 = "rssi177";
public static final String FIELD_178 = "rssi178";
public static final String FIELD_179 = "rssi179";
public static final String FIELD_180 = "rssi180";
public static final String FIELD_191 = "rssi191";
public static final String FIELD_192 = "rssi192";
public static final String FIELD_193 = "rssi193";
public static final String FIELD_194 = "rssi194";
public static final String FIELD_195 = "rssi195";
public static final String FIELD_196 = "rssi196";
public static final String FIELD_197 = "rssi197";
public static final String FIELD_198 = "rssi198";
public static final String FIELD_199 = "rssi199";
public static final String FIELD_200 = "rssi200";
public static final String FIELD_201 = "rssi201";
public static final String FIELD_202 = "rssi202";
public static final String FIELD_203 = "rssi203";
public static final String FIELD_204 = "rssi204";
public static final String FIELD_205 = "rssi205";
public static final String FIELD_206 = "rssi206";
public static final String FIELD_207 = "rssi207";
public static final String FIELD_208 = "rssi208";
public static final String FIELD_209 = "rssi209";
public static final String FIELD_210 = "rssi210";
public static final String FIELD_211 = "rssi211";
public static final String FIELD_213 = "rssi213";
public static final String FIELD_212 = "rssi212";
public static final String FIELD_214 = "rssi213";
public static final String FIELD_215 = "rssi215";
public static final String FIELD_216 = "rssi216";
public static final String FIELD_217 = "rssi217";
public static final String FIELD_218 = "rssi218";
public static final String FIELD_219 = "rssi219";
public static final String FIELD_220 = "rssi220";
public static final String FIELD_221 = "rssi221";
public static final String FIELD_222 = "rssi222";
public static final String FIELD_223 = "rssi223";
public static final String FIELD_224 = "rssi224";
public static final String FIELD_225 = "rssi225";
public static final String FIELD_226 = "rssi226";
public static final String FIELD_227 = "rssi227";
public static final String FIELD_228 = "rssi228";
public static final String FIELD_229 = "rssi229";
public static final String FIELD_230 = "rssi230";
public static final String FIELD_231 = "rssi231";
public static final String FIELD_232 = "rssi232";
public static final String FIELD_233 = "rssi233";
public static final String FIELD_234 = "rssi234";
public static final String FIELD_235 = "rssi235";
public static final String FIELD_236 = "rssi236";
public static final String FIELD_237 = "rssi237";
public static final String FIELD_238 = "rssi238";
public static final String FIELD_239 = "rssi239";
public static final String FIELD_240 = "rssi240";
public static final String FIELD_241 = "rssi241";
public static final String FIELD_242 = "rssi242";
public static final String FIELD_243 = "rssi243";
public static final String FIELD_244 = "rssi244";
public static final String FIELD_245 = "rssi245";
public static final String FIELD_246 = "rssi246";
public static final String FIELD_247 = "rssi247";
public static final String FIELD_248 = "rssi248";
public static final String FIELD_249 = "rssi249";
public static final String FIELD_250 = "rssi250";
public static final String FIELD_251 = "rssi251";
public static final String FIELD_252 = "rssi252";
public static final String FIELD_253 = "rssi253";
public static final String FIELD_254 = "rssi254";
public static final String FIELD_255 = "rssi255";
}
}
|
// ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package org.springframework.asm;
/**
* An edge in the control flow graph of a method. Each node of this graph is a basic block,
* represented with the Label corresponding to its first instruction. Each edge goes from one node
* to another, i.e. from one basic block to another (called the predecessor and successor blocks,
* respectively). An edge corresponds either to a jump or ret instruction or to an exception
* handler.
*
* @see Label
* @author Eric Bruneton
*/
final class Edge {
/**
* A control flow graph edge corresponding to a jump or ret instruction. Only used with {@link
* ClassWriter#COMPUTE_FRAMES}.
*/
static final int JUMP = 0;
/**
* A control flow graph edge corresponding to an exception handler. Only used with {@link
* ClassWriter#COMPUTE_MAXS}.
*/
static final int EXCEPTION = 0x7FFFFFFF;
/**
* Information about this control flow graph edge.
*
* <ul>
* <li>If {@link ClassWriter#COMPUTE_MAXS} is used, this field contains either a stack size
* delta (for an edge corresponding to a jump instruction), or the value EXCEPTION (for an
* edge corresponding to an exception handler). The stack size delta is the stack size just
* after the jump instruction, minus the stack size at the beginning of the predecessor
* basic block, i.e. the one containing the jump instruction.
* <li>If {@link ClassWriter#COMPUTE_FRAMES} is used, this field contains either the value JUMP
* (for an edge corresponding to a jump instruction), or the index, in the {@link
* ClassWriter} type table, of the exception type that is handled (for an edge corresponding
* to an exception handler).
* </ul>
*/
final int info;
/** The successor block of this control flow graph edge. */
final Label successor;
/**
* The next edge in the list of outgoing edges of a basic block. See {@link Label#outgoingEdges}.
*/
Edge nextEdge;
/**
* Constructs a new Edge.
*
* @param info see {@link #info}.
* @param successor see {@link #successor}.
* @param nextEdge see {@link #nextEdge}.
*/
Edge(final int info, final Label successor, final Edge nextEdge) {
this.info = info;
this.successor = successor;
this.nextEdge = nextEdge;
}
}
|
package 原型模式.非cloneable方式;
/**
* 非Cloneable实现原型模式
*/
public class TestMain {
public static void main(String[] args) {
ConcretePrototype originObj = new ConcretePrototype();
originObj.setName("原始对象的名字");
originObj.showObjInfo();
ConcretePrototype cloneObj = originObj.clone();
cloneObj.showObjInfo();
cloneObj.setName("clone后修改的名字");
cloneObj.showObjInfo();
originObj.showObjInfo();
}
}
|
package ToolsforFileManagement;
public class SlashDelete {
public static void main(String arg[]){
excludeslash("2011/1/12");
}
public static String excludeslash(String in){
String[] tokens = in.split("/");
String yyyymmdd = tokens[0] + String.format("%02d",Integer.valueOf(tokens[1])) + String.format("%02d",Integer.valueOf(tokens[2]));
System.out.println(yyyymmdd);
return yyyymmdd;
}
public static String slashtodash(String in){
String[] tokens = in.split("/");
String yyyymmdd = tokens[0] +"-"+ String.format("%02d",Integer.valueOf(tokens[1])) +"-"+ String.format("%02d",Integer.valueOf(tokens[2]));
System.out.println(yyyymmdd);
return yyyymmdd;
}
}
|
//accept two no ckack highest value and print them
import java.util.*;
class highest
{
public static void main(String args[])
{
Scanner v=new Scanner(System.in);
System.out.print("Enter first String::");
int a=v.nextInt();
System.out.print("Enter Second String::");
int b=v.nextInt();
if(a>b)
System.out.println("Highest value::"+a);
else
System.out.println("Highest value::"+b);
}//close of main
}//close of class
|
package com.packt.backgroundservicedemo;
import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
public class MyIntentService extends IntentService {
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
//private boolean ctr;
private static final String TAG = "MyIntentService";
public MyIntentService() {
super("MyBackgroundIntentThread");
//this.ctr = true;
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i(TAG, "onHandleIntent: Thread: " + Thread.currentThread().getName());
Intent localIntent = new Intent("my.own.broadcast");
int ctr = intent.getIntExtra("sleepTime",-1);
int duration = 0;
while (duration <= ctr) {
Log.i(TAG, "onHandleIntent: Time elapsed: " + ctr + " secs");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
duration++;
localIntent.putExtra("result", duration);
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
@Override
public void onDestroy() {
Log.i(TAG, "onDestroy: Thread: " + Thread.currentThread().getName());
Toast.makeText(this, "Task Execution Finished", Toast.LENGTH_SHORT).show();
LocalBroadcastManager.getInstance(this).unregisterReceiver(myLocalBroadCastReciver);
super.onDestroy();
}
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Task Execution Started", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate: Thread: " + Thread.currentThread().getName());
IntentFilter intentFilter = new IntentFilter("my.own.ServiceBroadCast");
LocalBroadcastManager.getInstance(this).registerReceiver(myLocalBroadCastReciver,intentFilter);
}
private BroadcastReceiver myLocalBroadCastReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//ctr = intent.getBooleanExtra("result",false);
}
};
}
|
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.IOException;
import java.util.Properties;
/**
* Created by pic on 29/04/2017.
*/
@Configuration
@ComponentScan(basePackages = "service")
public class ApplicationConfig extends WebMvcConfigurerAdapter
{
@Bean
public Properties dbProperties()
{
Properties properties = new Properties();
try
{
properties.load(ApplicationConfig.class.getClassLoader().getResourceAsStream("db.properties"));
}catch (IOException ioE)
{
System.err.println("erreur chgment db.properties");
}
return properties;
}
}
|
package com.uchain;
import com.uchain.solidity.CallTransaction;
import com.uchain.solidity.SolcUtils;
import com.uchain.solidity.compiler.CompilationResult;
import com.uchain.solidity.compiler.SolidityCompiler;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Arrays.stream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class ContractTest {
private static final String SRC = "" +
"pragma solidity ^0.4.19;" +
"contract Foo {\n" +
"\n" +
" uint32 idCounter = 1;\n" +
" bytes32 public lastError;\n" +
"\n" +
" // function bar(uint[2] xy) {}\n" +
" function baz(uint32 x, bool y) returns(bool r) {\n" +
" r = x > 32 || y;\n" +
" }\n" +
" // function sam(bytes name, bool z, uint[] data) {}\n" +
" function sam(bytes strAsBytes, bool someFlag, string str) {}\n" +
"}";
private static final String CODE = "112233";
private static final String SRC2 = "contract A { " +
" event message(string msg);" +
" uint public num; " +
" function set(uint a) {" +
" require(a > 100);" +
" num = a; " +
" log1(0x1111, 0x2222);" +
" }" +
" function getPublic() public constant returns (address) {" +
" return msg.sender;" +
" }" +
" function fire() {" +
" message(\"fire\");" +
" }" +
"}";
private static final String SRCCODE = "608060405260016000806101000a81548163ffffffff021916908363ffffffff16021790555" +
"034801561003157600080fd5b506101f4806100416000396000f300608060405260043610610057576000357c010000000000000" +
"0000000000000000000000000000000000000000000900463ffffffff16806329f0de3f1461005c57806390a161301461008f578" +
"063cdcd77c01461014a575b600080fd5b34801561006857600080fd5b506100716101a1565b60405180826000191660001916815" +
"260200191505060405180910390f35b34801561009b57600080fd5b5061014860048036038101908080359060200190820180359" +
"0602001908080601f016020809104026020016040519081016040528093929190818152602001838380828437820191505050505" +
"0509192919290803515159060200190929190803590602001908201803590602001908080601f016020809104026020016040519" +
"08101604052809392919081815260200183838082843782019150505050505091929192905050506101a7565b005b34801561015" +
"657600080fd5b50610187600480360381019080803563ffffffff169060200190929190803515159060200190929190505050610" +
"1ac565b604051808215151515815260200191505060405180910390f35b60015481565b505050565b600060208363ffffffff161" +
"1806101c05750815b9050929150505600a165627a7a72305820c177834ee14ec0a39a0bd5198e259eda9b2e734ae8119f6e9b4ee" +
"605322213450029";
@Before
public void before() {
}
@Test
public void contracts_readSolcVersion() {
assertThat(SolcUtils.getSolcVersion(), is("0.4.25"));
}
@Test
public void contracts_shouldCompileSuccess() throws IOException{
final List<String> contractResults = loadContractBin(SRC2, "A");
final String contractBin = contractResults.get(0);
System.out.println(contractBin);
//assertThat(contractBin, is(SRCCODE));
final String contractAbi = contractResults.get(1);
CallTransaction.Function[] abiDefinition = new CallTransaction.Contract(contractAbi).functions;
boolean compiledAllMethods = stream(abiDefinition)
.map(abi -> abi.name)
.collect(Collectors.toSet())
.containsAll(Arrays.asList("lastError", "baz", "sam"));
assertTrue(compiledAllMethods);
}
private List<String> loadContractBin(String sourceCode, String contractName) throws IOException {
List<String> compileResList = new ArrayList<>();
final SolidityCompiler.Result compiled = SolidityCompiler.compile(sourceCode.getBytes("UTF-8"), true, SolidityCompiler.Options.BIN, SolidityCompiler.Options.ABI);
final CompilationResult result = CompilationResult.parse(compiled.output);
compileResList.add(result.getContract(contractName).bin);
compileResList.add(result.getContract(contractName).abi);
return compileResList;
}
}
|
package slimeknights.tconstruct.library.potion;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.ResourceLocation;
public class TinkerPotion extends Potion {
private final boolean show;
public TinkerPotion(ResourceLocation location, boolean badEffect, boolean showInInventory) {
this(location, badEffect, showInInventory, 0xffffff);
}
public TinkerPotion(ResourceLocation location, boolean badEffect, boolean showInInventory, int color) {
super(badEffect, color);
setPotionName("potion." + location.getResourcePath());
this.setRegistryName(location);
this.show = showInInventory;
}
@Override
public boolean shouldRenderInvText(PotionEffect effect) {
return show;
}
public PotionEffect apply(EntityLivingBase entity, int duration) {
return apply(entity, duration, 0);
}
public PotionEffect apply(EntityLivingBase entity, int duration, int level) {
PotionEffect effect = new PotionEffect(this, duration, level, false, false);
entity.addPotionEffect(effect);
return effect;
}
public int getLevel(EntityLivingBase entity) {
PotionEffect effect = entity.getActivePotionEffect(this);
if(effect != null) {
return effect.getAmplifier();
}
return 0;
}
@Override
public boolean shouldRender(PotionEffect effect) {
return show;
}
}
|
package com.yusys.category;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.yusys.category.PropertyTypeConfig;
public interface IPropertyTypeConfigService {
/**
* 查询所有
* @param req
* @param userid
* @return
*/
public List<Map<String, String>> queryAllCategroy(HttpServletRequest req,String userId);
/**
* 添加类别配置
* @param req
* @return
*/
public Map<String, Object> addProTypeConfig(HttpServletRequest req, String userId, String orgId);
/**
* 根据类型编号,查询一条类别
* @param req
* @return
*/
public PropertyTypeConfig findOneConfigInfo(HttpServletRequest req);
/**
* 修改类别配置
* @param req
* @return
*/
public Map<String, Object> updateProTypeConfig(HttpServletRequest req, String userId);
/**
* 删除类别配置
* @param req
* @return
*/
public Map<String, Object> delProTypeConfig(HttpServletRequest req,String userId);
/**
* 查询所有资产类型
* @param req
* @param userid
* @return
*/
public List<Map<String, String>> queryAllAssetCategroy(HttpServletRequest req,String userId);
}
|
package com.ccloud.oa.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ccloud.oa.user.entity.Role;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* 用户角色权限表 Mapper 接口
* </p>
*
* @author breeze
* @since 2020-08-19
*/
@Mapper
public interface RoleMapper extends BaseMapper<Role> {
}
|
package ar.gob.gcaba.dao;
import java.util.Date;
import java.util.List;
public interface RegistroLUEDAO {
List<Integer> getListaRegistrosId(Long cuil);
Integer agregarDocumentoVinculado(Integer idRegistro, String numeroDocumento, Integer tipoDocumento,
String ruta, Date fechaVencimiento, String acronimo, String referencia);
void insertarDocumentoProcesado(String idDocumento, String filename, String estado, String error);
}
|
package io.report.modules.bddp.entity;
import java.util.List;
public class SqliteEntity {
private List<String> columns;
private List<List<Object>> values;
public void setColumns(List<String> columns){
this.columns = columns;
}
public List<String> getColumns(){
return this.columns;
}
public void setValues(List<List<Object>> values){
this.values = values;
}
public List<List<Object>> getValues(){
return this.values;
}
}
|
package com.cakeworld.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Pincode {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long id;
public String pincode;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
}
|
package com.soa.soap;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for element.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="element">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="STICK_1"/>
* <enumeration value="STICK_2"/>
* <enumeration value="STICK_3"/>
* <enumeration value="STICK_4"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "element")
@XmlEnum
public enum Element {
STICK_1,
STICK_2,
STICK_3,
STICK_4;
public String value() {
return name();
}
public static Element fromValue(String v) {
return valueOf(v);
}
}
|
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.dto.gis;
import javax.ejb.EJB;
import org.inbio.ara.dto.BaseDTOFactory;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.eao.gis.SiteEAOLocal;
import org.inbio.ara.persistence.gis.Site;
import org.inbio.ara.persistence.gis.SiteCoordinate;
/**
*
* @author esmata
*/
public class SiteCoordinateDTOFactory
extends BaseEntityOrDTOFactory<SiteCoordinate, SiteCoordinateDTO>{
@EJB
private SiteEAOLocal siteEAOImpl;
public SiteCoordinateDTO createDTO(SiteCoordinate entity) {
if(entity==null){
return null;
}
else{
SiteCoordinateDTO result = new SiteCoordinateDTO();
result.setLatitude(entity.getLatitude());
result.setLongitude(entity.getLongitude());
result.setOriginalX(entity.getOriginalX());
result.setOriginalY(entity.getOriginalY());
result.setVerbatimLongitude(entity.getVerbatimLongitude());
result.setVerbatimLatitude(entity.getVerbatimLatitude());
result.setSequence(entity.getSequence());
result.setSiteCoordinateId(entity.getSiteCoordinateId());
result.setSiteId(entity.getSiteId().getSiteId());
result.setUserName(entity.getCreatedBy());
return result;
}
}
@Override
public SiteCoordinate getEntityWithPlainValues(SiteCoordinateDTO dto) {
if(dto == null) return null;
SiteCoordinate newSiteCord = new SiteCoordinate();
newSiteCord.setLatitude(dto.getLatitude());
newSiteCord.setLongitude(dto.getLongitude());
newSiteCord.setOriginalX(dto.getOriginalX());
newSiteCord.setOriginalY(dto.getOriginalY());
newSiteCord.setSequence(dto.getSequence());
newSiteCord.setSiteCoordinateId(dto.getSiteCoordinateId());
//No estoy segura si es correcta la inyección del EJB
//newSiteCord.setSiteId(siteEAOImpl.findById(Site.class,dto.getSiteId()));
newSiteCord.setVerbatimLatitude(dto.getVerbatimLatitude());
newSiteCord.setVerbatimLongitude(dto.getVerbatimLongitude());
return newSiteCord;
}
@Override
public SiteCoordinate updateEntityWithPlainValues(SiteCoordinateDTO dto, SiteCoordinate e) {
if(dto == null) return null;
e.setLatitude(dto.getLatitude());
e.setLongitude(dto.getLongitude());
e.setOriginalX(dto.getOriginalX());
e.setOriginalY(dto.getOriginalY());
e.setSequence(dto.getSequence());
e.setSiteCoordinateId(dto.getSiteCoordinateId());
//No estoy segura si es correcta la inyección del EJB
e.setSiteId(siteEAOImpl.findById(Site.class,dto.getSiteId()));
e.setVerbatimLatitude(dto.getVerbatimLatitude());
e.setVerbatimLongitude(dto.getVerbatimLongitude());
return e;
}
}
|
package com.ut.healthelink.model.custom;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
/**
* This is a logo for the table, goal is to make replacing a logo as portable as we can.
**/
@Entity
@Table(name="logoInfo")
public class LogoInfo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID", nullable = false)
private int id;
@Column(name="frontEndLogoName", nullable = true)
private String frontEndLogoName;
@Column(name="backEndLogoName", nullable = true)
private String backEndLogoName;
@Column(name="DATECreated", nullable = true)
private Date dateCreated = new Date();
@Column(name="DATEModified", nullable = true)
private Date dateModified = new Date();
@Transient
private String backEndLocalPath;
@Transient
private String frontEndLocalPath;
@Transient
private CommonsMultipartFile frontEndFile;
@Transient
private CommonsMultipartFile backEndFile;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFrontEndLogoName() {
return frontEndLogoName;
}
public void setFrontEndLogoName(String frontEndLogoName) {
this.frontEndLogoName = frontEndLogoName;
}
public String getBackEndLogoName() {
return backEndLogoName;
}
public void setBackEndLogoName(String backEndLogoName) {
this.backEndLogoName = backEndLogoName;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateModified() {
return dateModified;
}
public void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
public String getBackEndLocalPath() {
return backEndLocalPath;
}
public void setBackEndLocalPath(String backEndLocalPath) {
this.backEndLocalPath = backEndLocalPath;
}
public String getFrontEndLocalPath() {
return frontEndLocalPath;
}
public void setFrontEndLocalPath(String frontEndLocalPath) {
this.frontEndLocalPath = frontEndLocalPath;
}
public CommonsMultipartFile getFrontEndFile() {
return frontEndFile;
}
public void setFrontEndFile(CommonsMultipartFile frontEndFile) {
this.frontEndFile = frontEndFile;
}
public CommonsMultipartFile getBackEndFile() {
return backEndFile;
}
public void setBackEndFile(CommonsMultipartFile backEndFile) {
this.backEndFile = backEndFile;
}
}
|
package ds.circularlinkedlist;
public class CircularLinkedList {
private Node first;
private Node last;
public CircularLinkedList() {
first = null;
last = null;
}
public void insertFirst(int data) {
Node newNode = new Node();
newNode.data = data;
newNode.next = first;
if(isEmpty()){
last = newNode;
}
first = newNode;
}
private Boolean isEmpty() {
return first == null;
}
public void insertLast(int data) {
Node newNode = new Node();
newNode.data = data;
if(isEmpty()){
first = newNode;
} else {
last.next = newNode;
last = newNode;
}
}
public int deleteFirst() {
int temp = first.data;
if(first.next == null) {
last = null;
}
first = first.next;
return temp;
}
public void displayList() {
Node currentNode = first;
while(currentNode!=null) {
System.out.print(currentNode.data+"->");
currentNode = currentNode.next;
}
}
}
|
package com.loneless.second_task;
import com.loneless.second_task.entity.Sentence;
import com.loneless.second_task.entity.Text;
import com.loneless.second_task.entity.Word;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Text text=new Text();
Scanner reader=new Scanner(System.in);
while (true){
System.out.println("Введите\n1 для дополнения текста\n2 для вывода текста\n3 для вывода заголовка текста" +
"\n-1 для выхода");
switch (reader.nextLine()) {
case "-1":
return;
case "1":
System.out.println("Введите строку/слово для добавления");
Sentence sentence = new Sentence();
String[] words = reader.nextLine().split(" ");
for (String word :
words) {
sentence.supplementation(new Word(word));
}
text.supplementation(sentence);
break;
case "2":
System.out.println(text.receiveIdea());
break;
case "3":
System.out.println("Заголовок: "+ text.getHeader());
break;
default:
System.out.println("Не верный ввод");
}
}
}
}
|
package com.example.howmanydaysi.alarm;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.example.howmanydaysi.activity.EventsExecutionActivity;
import com.example.howmanydaysi.R;
import com.example.howmanydaysi.preferences.Preference;
public class AlarmService extends BroadcastReceiver {
// при уведомленни происходит переход на это окно
// Идентификатор канала
private static String CHANNEL_ID = "Channel";
private boolean melody = false, vibrate = false;
private static NotificationManagerCompat notificationManager;
public static int id = 1;
public static void CloseAlarm(){
if (null != notificationManager) {
notificationManager.cancel(id);
}
}
public static void CloseAlarm(Context context){
notificationManager = NotificationManagerCompat.from(context);
CloseAlarm();
}
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences preferences = Preference.getInstance(context);
Preference.setAppPreference(preferences,Preference.APP_PREFERENCES_NAME_REMIND_TODAY,true);
if (Preference.getAppPreference(preferences,Preference.APP_PRECEFENCES_NAME_EVENT_COUNT,0)==0) return;
Preference.setAppPreference(preferences,Preference.APP_PREFERENCES_NAME_ALARM_ACTIVATED, true);
vibrate = Preference.getAppPreference(preferences,Preference.APP_PREFERENCES_NAME_VIBRATE, false);
melody = Preference.getAppPreference(preferences,Preference.APP_PREFERENCES_NAME_MELODY, false);
Intent notificationIntent = new Intent(context, EventsExecutionActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context,
1, notificationIntent,
0);
//создание уведомления
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.icon_calendar)
.setContentTitle(context.getString(R.string.alarm_title))
.setContentIntent(contentIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.alarm_text)))
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_calendar))
.setColor(Color.GRAY)
.setOngoing(true)
.setAutoCancel(false);
Notification notification = builder.build();
if (melody)
notification.defaults |= Notification.DEFAULT_SOUND;
if (vibrate)
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager =
NotificationManagerCompat.from(context);
notificationManager.notify(id, notification);
}
}
|
package com.damianogiusti.cleanandroid.ui.home;
import com.damianogiusti.cleanandroid.mvp.View;
import com.damianogiusti.cleanandroid.viewmodel.ProvinceViewModel;
import java.util.List;
/**
* Created by Damiano Giusti on 03/05/17.
*/
public interface MainView extends View {
void showMessage(String message);
void showLoading();
void hideLoading();
void showList(List<ProvinceViewModel> list);
void showError(String errorMessage);
}
|
package com.example.mmr.medic;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.example.mmr.R;
import com.example.mmr.VolleySingleton;
import com.example.mmr.patient.NoteListAdapter;
import com.example.mmr.patient.Notes;
import com.example.mmr.patient.OnlineMedListAdapter;
import com.example.mmr.patient.OnlineMeds;
import com.example.mmr.shared.SharedModel;
import java.util.Vector;
public class MedicNoteList extends AppCompatActivity {
RecyclerView recyclerView;
private RequestQueue queue;
TextView emplty;
private String cin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//make it fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_medic_note_list);
if (getIntent().hasExtra("cin"))
cin=getIntent().getStringExtra("cin");
recyclerView=findViewById(R.id.doc_note_list);
emplty=findViewById(R.id.empty_view_note_list);
recyclerView.setVisibility(View.GONE);
emplty.setVisibility(View.VISIBLE);
queue = VolleySingleton.getInstance(this).getRequestQueue();
new SharedModel(this,queue).getOnlineMedAndNote(cin, new SharedModel.LoadHomeInfoCallBack() {
@Override
public void onSuccess(Vector<Object> vector) {
Notes notes=(Notes) vector.get(1);
NoteListAdapter noteListAdapter = new NoteListAdapter(notes.getNotes());
// Attach the adapter to the recyclerview to populate items
recyclerView.setAdapter(noteListAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
if (notes.getNotes().isEmpty()) {
recyclerView.setVisibility(View.GONE);
emplty.setVisibility(View.VISIBLE);
}
else {
recyclerView.setVisibility(View.VISIBLE);
emplty.setVisibility(View.GONE);
}
}
@Override
public void onErr(String message) {
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_LONG).show();
}
});
}
}
|
package com.sapient.healthyreps.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.sapient.healthyreps.dao.UserRegisterDAO;
import com.sapient.healthyreps.entity.UserLogin;
import com.sapient.healthyreps.interfaces.IUserRegisterDAO;
@RestController
public class LoginController {
IUserRegisterDAO dao = new UserRegisterDAO();
@PostMapping("/api/login")
public Boolean userLogin(@RequestBody UserLogin user) {
String email = user.getUserEmail(), password = user.getPassword();
return dao.getUserByEmailAndPwd(email, password).size() == 1;
}
}
|
package com.vicutu.cache;
import java.util.Iterator;
public interface CacheManager
{
Cache get(String name);
Iterator<String> keySet();
void remove(String name);
void removeAll();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.