text
stringlengths 10
2.72M
|
|---|
package com.web.SlnmRltd;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class SrchBoxKeyEvnt {
@Test()
public void mouseAct() throws Exception{
System.setProperty("webdriver.chrome.driver", "D:\\BrowserDrivers\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.navigate().to("https://www.google.co.in");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("lst-ib")).sendKeys("kur");
Thread.sleep(1000);
driver.findElement(By.id("lst-ib")).sendKeys(Keys.ARROW_DOWN);
}
}
|
import java.util.ArrayList;
public class ProcessTransaction implements Constants {
protected ArrayList<Transactions> validList;
protected ArrayList<Transactions> invalidList;
protected int InvalidTransactionType;
public int getInvalidTransactionType() {
return InvalidTransactionType;
}
public void setInvalidTransactionType(int invalidTransactionType) {
InvalidTransactionType = invalidTransactionType;
}
public ArrayList<Transactions> getValidList() {
return validList;
}
public void setValidList(ArrayList<Transactions> validList) {
this.validList = validList;
}
public ArrayList<Transactions> getInvalidList() {
return invalidList;
}
public void setInvalidList(ArrayList<Transactions> invalidList) {
this.invalidList = invalidList;
}
public void evaluteTransaction(Transactions trans, int InvestorNumber, int CompanyNumber){
if(trans.getIsSelling())
{
if(mainPortfolio[InvestorNumber][CompanyNumber].getQuantity() != 0 )
{
if(trans.getQty() > 10 || trans.getQty() < 100 ||
mainPortfolio[InvestorNumber][CompanyNumber].getQuantity() < trans.getQty()){
if(trans.getPrice() > 10 || trans.getPrice() < 100 ||
mainPortfolio[InvestorNumber][CompanyNumber].getQuantity() < trans.getPrice()){
validList.add(trans);
}else{
setInvalidTransactionType(3);
invalidList.add(trans);
}
}else{
setInvalidTransactionType(2);
invalidList.add(trans);
}
}else{
setInvalidTransactionType(1);
invalidList.add(trans);
}
}else{
if(trans.getQty() > 10 ||
(mainPortfolio[InvestorNumber][CompanyNumber].getQuantity() + trans.getQty()) < 100){
if(trans.getPrice() > 10 || trans.getPrice() < 100 ||
mainPortfolio[InvestorNumber][CompanyNumber].getQuantity() < trans.getPrice()){
validList.add(trans);
}else{
setInvalidTransactionType(3);
invalidList.add(trans);
}
}else{
setInvalidTransactionType(2);
invalidList.add(trans);
}
}
}
}
|
package br.unipe.cc.mlpIII.gui;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.unipe.cc.mlpIII.pertinencia.Db;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class TelaLogin extends Application{
private TextField user;
private PasswordField pass;
private ResultSet usersInDataBase;
private Db db = new Db();
private Scene scene;
private Parent root;
private Stage telaLoginStage;
private Button login;
private boolean autorizado;
public TelaLogin(){
db.abrirConexao();
}
@Override
public void start(Stage primaryStage) {
this.telaLoginStage = primaryStage;
try {
root = FXMLLoader.load(getClass().getResource("TelaLogin.fxml"));
scene = new Scene(root);
this.telaLoginStage.setTitle("DELL SEGUROS");
this.telaLoginStage.getIcons().add(new Image("file:imagens\\seguro.png"));
this.telaLoginStage.setScene(scene);
this.telaLoginStage.show();
login = (Button) scene.lookup("#login");
user = (TextField) scene.lookup("#user");
pass = (PasswordField) scene.lookup("#pass");
login.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
login();
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
protected void login() {
boolean achou = false;
usersInDataBase = db.consulta("SELECT * FROM usuario WHERE id = '" + user.getText() + "' and senha = '" + pass.getText() + "'" );
try {
while(usersInDataBase.next()){
achou = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
if (achou) {
autorizado = true;
fecharTelaLogin();
} else
erroLogin();
}
public void fecharTelaLogin(){
db.fecharConexao();
telaLoginStage.hide();
}
public void erroLogin(){
Alert warning = new Alert(Alert.AlertType.WARNING);
warning.setTitle("Erro de login");
warning.setHeaderText("Usuário ou senha estão incorretos, tente novamente.");
warning.showAndWait();
}
public boolean isAutorizado() {
return autorizado;
}
public void setAutorizado(boolean autorizado) {
this.autorizado = autorizado;
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.deployer;
import vanadis.common.io.Files;
import vanadis.core.lang.ToString;
import vanadis.common.time.TimeSpan;
import vanadis.common.text.Printer;
import vanadis.ext.*;
import vanadis.osgi.Context;
import java.io.File;
@Module(moduleType = "deployer", launch = @AutoLaunch(name = "deployer"))
public final class DeployerModule extends AbstractModule implements ContextAware {
private static final TimeSpan PAUSE = TimeSpan.HALF_MINUTE;
static final String COMMAND = "v-deploy";
private ActiveDeployer activeDeployer;
@Override
public void activate() {
File home = new File(context().getHome());
this.activeDeployer = createDeployer(context(), home);
new Thread(activeDeployer, "Deploy").start();
}
@Expose
public Command getDeployCommand() {
return new GenericCommand(COMMAND, "run deploy cycle", context(), new TriggerCycle());
}
@Override
public void closed() {
if (activeDeployer != null) {
activeDeployer.stop();
}
}
private static ActiveDeployer createDeployer(Context context, File home) {
return new ActiveDeployer(new DeployImpl(context), PAUSE,
new DirectoryBundleExplorer(bundleDir(home), tmpDir(home), ".zip", ".jar"),
new DirectoryLaunchExplorer(serviceDir(home), ".xml"));
}
private static File tmpDir(File home) {
return Files.getDirectory(home, "var", "tmp");
}
private static File bundleDir(File home) {
return Files.getDirectory(home, "deploy", "bundle");
}
private static File serviceDir(File home) {
return Files.getDirectory(home, "deploy", "service");
}
@Override
public String toString() {
return ToString.of(this, activeDeployer);
}
private class TriggerCycle implements CommandExecution {
@Override
public void exec(String command, String[] args, Printer ps, Context context) {
activeDeployer.triggerCycle();
}
}
}
|
package com.example.heng.jredu.jredu;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import com.example.heng.jredu.R;
public class MainActivity_article extends Activity {
private WebView webView;
private LinearLayout loadStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_article);
webView = (WebView) findViewById(R.id.webview);
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
loadStatus = (LinearLayout) findViewById(R.id.load_status);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
loadStatus.setVisibility(View.GONE);
} else {
loadStatus.setVisibility(View.VISIBLE);
}
}
});
webView.loadUrl("http://www.cnblogs.com/jerehedu/");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
|
package com.z3pipe.z3location.controller;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import com.z3pipe.z3core.base.BaseSdFileReadWriter;
import com.z3pipe.z3location.config.PositionCollectionConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Created with IntelliJ IDEA.
* Description: ${TODO}
* Date: 2019-04-15
* Time: 12:08
* Copyright © 2018 ZiZhengzhuan. All rights reserved.
* https://www.z3pipe.com
*
* @author zhengzhuanzi
*/
public class TrackingConfigController extends BaseSdFileReadWriter {
/**
* 获得GPS定位配置信息
*
* @param context
* @return
*/
public static PositionCollectionConfig getPositionCollectionConfig(Context context) {
ObjectInputStream inputStream = null;
PositionCollectionConfig positionCollectionConfig = null;
try {
File file = new File(getConfigCachePath(context));
inputStream = new ObjectInputStream(new FileInputStream(file));
Object object = inputStream.readObject();
positionCollectionConfig = (PositionCollectionConfig) object;
return positionCollectionConfig;
} catch (Exception e) {
positionCollectionConfig = new PositionCollectionConfig();
} finally {
try {
inputStream.close();
} catch (Exception e2) {
}
}
return positionCollectionConfig;
}
/**
* 保存GPS定位配置
*
* @param context
* @param positionCollectionConfig
* @return
*/
public static void savePositionCollectionConfig(Context context, PositionCollectionConfig positionCollectionConfig) {
ObjectOutputStream objectOutputStream = null;
try {
File file = new File(getConfigCachePath(context));
objectOutputStream = new ObjectOutputStream(new FileOutputStream(file));
objectOutputStream.writeObject(positionCollectionConfig);
} catch (IOException e) {
} finally {
try {
objectOutputStream.close();
} catch (Exception e2) {
}
}
}
/**
* 获得配置信息缓存路径
*
* @param context
* @return
*/
private static String getConfigCachePath(Context context) {
String rootPath = "//Z3Pipe//tracking";
boolean hasSdCard = Environment.getExternalStorageState().equals("mounted");
String sdCardPath = Environment.getExternalStorageDirectory().getPath();
if (!hasSdCard) {
sdCardPath = Environment.getRootDirectory().getPath();
}
String dir = sdCardPath + rootPath + "//media//";
hasFileDir(dir);
return dir + "user.config.bin";
}
private static boolean hasFileDir(String var1) {
File file;
if (!(file = new File(var1)).exists()) {
file.mkdirs();
}
return file.exists();
}
}
|
package com.vilio.mps.push.dao;
import com.vilio.mps.push.pojo.Umeng;
import java.util.List;
import java.util.Map;
/**
* 类名: UmengDao<br>
* 功能:友盟Dao层<br>
* 版本: 1.0<br>
* 日期: 2017年6月27日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
*/
public interface UmengDao {
public int insertUmengBatch(List<Umeng> umengs);
public int updateUmengBatch(Map umengs);
}
|
package com.magicare.mutils.cache;
/**
* @author justin on 2015/12/11 15:58
* justin@magicare.me
* @version V1.0
*/
public class HttpCacheEntity {
private String key;
private long time;
private long life;
private String content;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public long getLife() {
return life;
}
public void setLife(long life) {
this.life = life;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
package com.project.service.taxi.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.project.service.taxi.stub_connector.TaxiCar;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class OrderResponseDTO {
private Long id;
private String info;
private BigDecimal price;
private String modelCar;
private String brandName;
private String startAddress;
private String endAddress;
@JsonFormat(pattern = "HH:mm:ss dd.MM.yyyy")
private LocalDateTime dateCreated;
private String[] services;
public OrderResponseDTO() {
}
public OrderResponseDTO(Long id, LocalDateTime dateCreated , TaxiCar taxiCar) {
this.id = id;
this.info = "Заказ: №" + id + " на сумму " + taxiCar.getPrice() + "р. оформлен!";
this.dateCreated = dateCreated;
this.price = taxiCar.getPrice();
this.modelCar = taxiCar.getModel();
this.brandName = taxiCar.getBrandName();
this.startAddress = taxiCar.getLocation();
this.endAddress = taxiCar.getDestination();
this.services = taxiCar.getServices();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getModelCar() {
return modelCar;
}
public void setModelCar(String modelCar) {
this.modelCar = modelCar;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getStartAddress() {
return startAddress;
}
public void setStartAddress(String startAddress) {
this.startAddress = startAddress;
}
public String getEndAddress() {
return endAddress;
}
public void setEndAddress(String endAddress) {
this.endAddress = endAddress;
}
public LocalDateTime getDateCreated() {
return dateCreated;
}
public void setDateCreated(LocalDateTime dateCreated) {
this.dateCreated = dateCreated;
}
public String[] getServices() {
return services;
}
public void setServices(String[] services) {
this.services = services;
}
}
|
package leet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
/**
* Created by kreddy on 5/8/18.
*/
public class MRU {
public static void main(String[] args) {
LinkedHashMap<String, String> lhm = new LinkedHashMap<>(4, 0.75f, true);
lhm.put("one", "one");
lhm.put("two", "two");
lhm.put("three", "three");
lhm.put("one", "four");
lhm.get("three");
for(Entry<String, String> e : lhm.entrySet()) {
System.out.println(e.getKey() + ":" + e.getValue());
}
}
}
|
package com.shah.urlshortener;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.shah.urlshortener.entity.Url;
import com.shah.urlshortener.repository.UrlRepository;
@SpringBootTest
class UrlShortenerApplicationTests {
@Autowired
private UrlRepository urlRepository;
@Test
void shortenUrl() {
Url url = new Url("tutorials", "https://www.youtube.com/watch?v=Geq60OVyBPg&t=1103s");
Url url2 = urlRepository.save(url);
boolean expected = urlRepository.existsById(url.getId());
assertThat(expected).isTrue();
urlRepository.deleteById(url2.getId());
}
@Test
void contextLoads() {
}
}
|
/* Copyright 2018, Senjo Org. Denis Rezvyakov aka Dinya Feony Senjo.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.senjo.basis;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
/** Простейший класс для замера и журналирования времени выполнения некоторого алгоритма.
* Пример использования:
* <pre>
* Ticker ticker = new Ticker();
* ...{code}...
* Log.trace("Code done " + ticker); // Выведет в журнал: "Code done (1,23ms)"</pre>
*
* @author Denis Rezvyakov aka Dinya Feony Senjo
* @version 2018, change 2018-10-12, release */
public final class Ticker {
private static DecimalFormat format = new DecimalFormat( "(#,##0.00ms)",
DecimalFormatSymbols.getInstance(Locale.ROOT) );
// Format создаёт алгоритм разбора не во время создания, а во время первого исполнения
static { format.format(1.23f); } // Исполняем фиктивный разбор сразу
private long tick;
public Ticker() { reset(); }
public void reset() { tick = System.nanoTime(); }
@Override public String toString() { return toString(tick); }
/** Формирует строку вида "(1,23ms)" с временем от указанного до текущего момента. */
public static String toString(long nanoStart) {
return format.format( (System.nanoTime() - nanoStart) / 1000000f ); }
/** Формирует строку вида "(1,23ms)" с промежутком времени указанным в аргументе. */
public static String toStringEx(long nano) {
return format.format( nano / 1000000f ); }
}
|
package model;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
public class UziTest {
Uzi u;
Player p;
@BeforeEach
public void setup() {
p = new Player();
u = new Uzi(p);
}
@Test
public void testConstructor() {
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
assertFalse(u.getIsBeingUsed());
assertEquals(p.getDir(), u.getDir());
assertEquals(WeaponType.UZI, u.getWeaponType());
}
@Test
public void testShoot() {
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
u.shoot();
assertEquals(u.MAX_AMMO_CAPACITY-1, u.getAmmo());
}
@Test
public void testShootOutOfAmmo() {
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
for (int i = 0; i < u.MAX_AMMO_CAPACITY ; i++) {
u.shoot();
}
assertEquals(0, u.getAmmo());
u.shoot();
assertEquals(0, u.getAmmo());
}
@Test
public void testReloadAlreadyFull() {
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
u.reload();
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
}
@Test
public void testReloadNotAlreadyFull() {
u.shoot();
assertEquals(u.MAX_AMMO_CAPACITY-1, u.getAmmo());
u.reload();
assertEquals(u.MAX_AMMO_CAPACITY, u.getAmmo());
}
}
|
package com.example.chris.eyespy;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.app.Fragment;
import android.Manifest;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class GPSPage extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = GPSPage.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 100;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
public static final int REQUEST_LOCATION = 99;
private TextView locationCoord;
private Button buttonGPS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpspage);
locationCoord = (TextView) findViewById(R.id.location);
buttonGPS = (Button) findViewById(R.id.button_gps);
if (checkPlayServices()) {
buildGoogleApiClient();
}
}
public void displayGPS(View view) {
displayLocation();
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
} else {
// permission has been granted, continue as usual
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation != null){
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
locationCoord.setText(latitude + ", " + longitude);
} else {
locationCoord.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
protected synchronized void buildGoogleApiClient(){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private boolean checkPlayServices(){
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS){
if(googleAPI.isUserResolvableError(result)){
googleAPI.getErrorDialog(this,result,PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else{
Log.i(TAG, "This device is not supported");
finish();
}
return false;
}
return true;
}
@Override
protected void onStart(){
super.onStart();
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
}
}
@Override
protected void onResume(){
super.onResume();
checkPlayServices();
}
@Override
public void onConnectionFailed(ConnectionResult result){
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0){
displayLocation();
}
@Override
public void onConnectionSuspended(int arg0){
mGoogleApiClient.connect();
}
}
|
package com.leyou.common.enums;
/**
* @Description TODO
* @Author whd
* @Date 2020/5/11 21:50
*/
public enum ExceptionEnum {
PRIVICE_CANNOT_BE_NULL(400,"价格不能为空"),
CATEGORY_NOT_FOUND(404,"商品分类没查到"),
BRAND_NOT_FOUND(404,"品牌没查到"),
BRAND_SAVE_ERROR(500,"品牌新增失败"),
FILE_UPLOAD_ERROR(500,"文件上传失败"),
INVALID_FILE_TYPE(400,"文件参数有误"),
;
private int code;
private String msg;
ExceptionEnum() {
}
ExceptionEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
|
package com.espendwise.manta.util.criteria;
import java.io.Serializable;
public class DistributorListViewCriteria implements Serializable {
private Long storeId;
private String distributorId;
private String distributorName;
private String distributorNameFilterType;
private Boolean activeOnly;
private Integer limit;
public DistributorListViewCriteria(Long storeId, Integer limit) {
this.storeId = storeId;
this.limit = limit;
}
public Long getStoreId() {
return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public String getDistributorId() {
return distributorId;
}
public void setDistributorId(String distributorId) {
this.distributorId = distributorId;
}
public Boolean getActiveOnly() {
return activeOnly;
}
public Boolean isActiveOnly() {
return activeOnly;
}
public void setActiveOnly(Boolean activeOnly) {
this.activeOnly = activeOnly;
}
public String getDistributorName() {
return distributorName;
}
public void setDistributorName(String distributorName) {
this.distributorName = distributorName;
}
public String getDistributorNameFilterType() {
return distributorNameFilterType;
}
public void setDistributorNameFilterType(String distributorNameFilterType) {
this.distributorNameFilterType = distributorNameFilterType;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
@Override
public String toString() {
return "DistributorListViewCriteria{" +
"storeId=" + storeId +
", distributorId='" + distributorId + '\'' +
", distributorName='" + distributorName + '\'' +
", activeOnly=" + activeOnly +
", limit=" + limit + '\'' +
'}';
}
}
|
/*
* Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
// !!!
// NOTE: this class is widely used. DO NOT depend on any other classes in any test library, or else
// you may see intermittent ClassNotFoundException as in JDK-8188828
// !!!
/**
* Copy a resource: file or directory recursively, using relative path(src and dst)
* which are applied to test source directory(src) and current directory(dst)
*/
public class FileInstaller {
public static final String TEST_SRC = System.getProperty("test.src", "").trim();
/**
* @param args source and destination
* @throws IOException if an I/O error occurs
*/
public static void main(String[] args) throws IOException {
if (args.length != 2) {
throw new IllegalArgumentException("Unexpected number of arguments for file copy");
}
Path src = Paths.get(TEST_SRC, args[0]).toAbsolutePath().normalize();
Path dst = Paths.get(args[1]).toAbsolutePath().normalize();
if (src.toFile().exists()) {
System.out.printf("copying %s to %s%n", src, dst);
if (src.toFile().isDirectory()) {
// can't use Files::copy for dirs, as 'dst' might exist already
Files.walkFileTree(src, new CopyFileVisitor(src, dst));
} else {
Path dstDir = dst.getParent();
if (!dstDir.toFile().exists()) {
Files.createDirectories(dstDir);
}
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
}
} else {
throw new IOException("Can't find source " + src);
}
}
private static class CopyFileVisitor extends SimpleFileVisitor<Path> {
private final Path copyFrom;
private final Path copyTo;
public CopyFileVisitor(Path copyFrom, Path copyTo) {
this.copyFrom = copyFrom;
this.copyTo = copyTo;
}
@Override
public FileVisitResult preVisitDirectory(Path file,
BasicFileAttributes attrs) throws IOException {
Path relativePath = copyFrom.relativize(file);
Path destination = copyTo.resolve(relativePath);
if (!destination.toFile().exists()) {
Files.createDirectories(destination);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
if (!file.toFile().isFile()) {
return FileVisitResult.CONTINUE;
}
Path relativePath = copyFrom.relativize(file);
Path destination = copyTo.resolve(relativePath);
Files.copy(file, destination, StandardCopyOption.COPY_ATTRIBUTES);
return FileVisitResult.CONTINUE;
}
}
}
|
package br.com.fiap.healthtrack;
import br.com.fiap.healthtrack.dao.RefeicaoSugestaoDAO;
public class TesteFase6Cap3 {
public static void main(String[] args) {
RefeicaoSugestaoDAO refeicaoSugestaoDAO = new RefeicaoSugestaoDAO();
refeicaoSugestaoDAO
.getAll()
.forEach( r -> System.out.println(r));
}
}
|
package github.observer;
import javax.swing.*;
public class TextObserver implements Observer {
private JTextField txtTemperature;
public TextObserver(JTextField txtTemperature) {
this.txtTemperature = txtTemperature;
}
@Override
public void update(Subject subject) {
WeatherForecast weatherForecast = (WeatherForecast) subject;
txtTemperature.setText(String.valueOf(weatherForecast.getTemperature()));
}
}
|
package com.kdp.wanandroidclient.ui.user;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;
import com.kdp.wanandroidclient.R;
import com.kdp.wanandroidclient.utils.AppUtils;
import com.kdp.wanandroidclient.utils.LightStatusbarUtils;
/**
* 关于我们
* author: 康栋普
* date: 2018/3/25
*/
public class AboutUsActivity extends AppCompatActivity {
private TextView mVersionView, mIntroduceView;
@Override
protected void onCreate(Bundle bundle) {
LightStatusbarUtils.setLightStatusBar(this,false);
super.onCreate(bundle);
setContentView(R.layout.activity_about_us);
CollapsingToolbarLayout mCollapsingToolbarLayout = findViewById(R.id.collapsingbarlayout);
Toolbar mToolbar = findViewById(R.id.toolbar);
mToolbar.setTitle(R.string.about_us);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//设置展开后的字体颜色
mCollapsingToolbarLayout.setExpandedTitleTextColor(ColorStateList.valueOf(ContextCompat.getColor(this,R.color.white)));
//设置收缩后的字体颜色
mCollapsingToolbarLayout.setCollapsedTitleTextColor(ColorStateList.valueOf(ContextCompat.getColor(this,R.color.white)));
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mVersionView = findViewById(R.id.version);
mIntroduceView = findViewById(R.id.introduce);
setVersion();
setIntroduce();
}
private void setIntroduce() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mIntroduceView.setText(Html.fromHtml(getString(R.string.about_us_introduce), Html.FROM_HTML_MODE_LEGACY));
} else {
mIntroduceView.setText(Html.fromHtml(getString(R.string.about_us_introduce)));
}
//设置跳转
mIntroduceView.setMovementMethod(LinkMovementMethod.getInstance());
}
//设置版本
private void setVersion() {
String mVersionFormat = getString(R.string.version_format);
String mVersionName = AppUtils.getVersionName(this);
String mAppName = getString(R.string.app_name);
String mVersionStr = String.format(mVersionFormat, mAppName, mVersionName);
mVersionView.setText(mVersionStr);
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import com.tencent.mm.model.bl;
import com.tencent.mm.plugin.messenger.foundation.a.a.h.b;
import com.tencent.mm.plugin.setting.a.f;
import com.tencent.mm.plugin.setting.a.g;
import com.tencent.mm.plugin.setting.a.i;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.b.a;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.p;
import com.tencent.mm.ui.s;
import com.tencent.mm.ui.widget.MMEditText;
public class EditSignatureUI extends MMActivity {
private p eXe = null;
private boolean hLL = false;
private c hLO = new 1(this);
private TextView mPC;
private MMEditText mPM;
private b mPN;
final bl mPO = bl.IC();
protected final int getLayoutId() {
return g.edit_signature;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
a.sFg.b(this.hLO);
initView();
}
public void onDestroy() {
super.onDestroy();
a.sFg.c(this.hLO);
}
protected final void initView() {
setMMTitle(i.settings_signature);
this.mPM = (MMEditText) findViewById(f.content);
this.mPC = (TextView) findViewById(f.wordcount);
this.mPM.setText(j.a(this, bi.oV((String) com.tencent.mm.kernel.g.Ei().DT().get(12291, null)), this.mPM.getTextSize()));
this.mPM.setSelection(this.mPM.getText().length());
this.mPC.setText(com.tencent.mm.ui.tools.g.be(60, this.mPM.getEditableText().toString()));
com.tencent.mm.ui.tools.a.c.d(this.mPM).fj(0, 60).a(null);
this.mPM.addTextChangedListener(new a(this, (byte) 0));
setBackBtn(new 2(this));
a(0, getString(i.app_save), new 3(this), s.b.tmX);
enableOptionMenu(false);
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i == 4) {
finish();
}
return super.onKeyDown(i, keyEvent);
}
}
|
package com.MCS_Software.app.mcs_driver;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PendingAdapter extends RecyclerView.Adapter <PendingAdapter.PendingViewHolder> {
Context mContext;
List<RequestedInfo> mNameDB;
private OnItemClickListener mListener;
public PendingAdapter(Context context, List<RequestedInfo> NameDB) {
mContext = context;
mNameDB = NameDB;
}
@NonNull
@Override
public PendingViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item_view, viewGroup, false);
return new PendingViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull PendingViewHolder pendingViewHolder, int i) {
pendingViewHolder.clientNames.setText(mNameDB.get(i).getName());
pendingViewHolder.date.setText(mNameDB.get(i).getTime());
pendingViewHolder.des.setText(mNameDB.get(i).getDestin());
pendingViewHolder.ori.setText(mNameDB.get(i).getOrigin());
}
@Override
public int getItemCount() {
return mNameDB.size();
}
public class PendingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView clientNames;
TextView date, ori, des;
public PendingViewHolder(@NonNull View itemView) {
super(itemView);
clientNames = itemView.findViewById(R.id.clientName);
date = itemView.findViewById(R.id.date);
ori = itemView.findViewById(R.id.originName);
des = itemView.findViewById(R.id.DestinName);
itemView.setOnClickListener(this);
// itemView.setOnCreateContextMenuListener(this);
}
// @Override
// public boolean onMenuItemClick(MenuItem item) {
// if (mListener != null){
// int position = getAdapterPosition();
//
// if (position != RecyclerView.NO_POSITION){
// switch (item.getItemId()){
// case 1:
// mListener.onJourneyInfoClick(position);
// return true;
//
// case 2:
// mListener.onDeleteClick(position);
// return true;
//
// case 3:
// mListener.onAmendClick(position);
// return true;
// case 4:
// mListener.onAcknowledgeClick(position);
//
//
// }
//
// }
// }
// return false;
// }
//
@Override
public void onClick(View v) {
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position);
}
}
}
//
// @Override
// public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//
// menu.setHeaderTitle("Select Action");
//
// MenuItem doWhatever = menu.add(Menu.NONE,1,1,"Journey Info");
// MenuItem delete = menu.add(Menu.NONE,2,2,"Cancel");
// MenuItem amend = menu.add(Menu.NONE,3,3,"Amend");
// MenuItem acknowledge = menu.add(Menu.NONE,4,4,"Acknowledge");
//
//
//
// doWhatever.setOnMenuItemClickListener(this);
// delete.setOnMenuItemClickListener(this);
// amend.setOnMenuItemClickListener(this);
// acknowledge.setOnMenuItemClickListener(this);
// }
// }
}
public interface OnItemClickListener{
void onItemClick (int position);
// void onJourneyInfoClick(int position);
//
// void onDeleteClick(int position);
//
// void onAmendClick(int position);
//
// void onAcknowledgeClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
}
|
package com.samples.sorting;
import java.util.Arrays;
import java.util.stream.Stream;
public class QuickSort {
private static int length;
private static int array[]= {22,43,12,56,33,44,61,1};
public static void main(String[] args) {
sort(array);
Stream.of(array).forEach(System.out::print);
}
public static void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
length = inputArr.length;
quickSort(0, length - 1);
}
private static void quickSort(int lowerIndex, int higherIndex) {
int i=lowerIndex;
int j=higherIndex;
int pivot=array[lowerIndex+(higherIndex-lowerIndex)/2];
while(i<j) {
/**
* In each iteration, we will identify a number from left side which
* is greater then the pivot value, and also we will identify a number
* from right side which is less then the pivot value. Once the search
* is done, then we exchange both numbers.
*/
while(array[i]<pivot) {
i++;
}
while(array[j]>pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private static void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
|
package com.puxtech.reuters.rfa.Filter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.puxtech.reuters.rfa.Common.Quote;
public class Filter {
private List<FilterStrategy> strategyList = new ArrayList<FilterStrategy>();
private BigDecimal prevPrice = new BigDecimal("0.0");
public Filter() {
super();
}
public void addStrategy(FilterStrategy strategy){
this.strategyList.add(strategy);
}
public void filte(Quote quote){
if(quote == null)
return;
// moniterLog.info("strategyList size=" + strategyList.size());
for(FilterStrategy filterStrategy : strategyList){
filterStrategy.setPrevPrice(prevPrice);
if(filterStrategy.isFilter(quote)){
quote.isFilter = true;
prevPrice = quote.newPrice;
return;
}
}
quote.isFilter = false;
prevPrice = quote.newPrice;
}
public int getFilteStrategyCount(){
return this.strategyList != null ? this.strategyList.size() : 0;
}
public List<FilterStrategy> getStrategyList() {
return strategyList;
}
public void resetBenchMark(){
for(FilterStrategy filterStrategy : strategyList){
filterStrategy.resetBenchMark();
}
}
}
|
package org.webmaple.worker.annotation;
import java.lang.annotation.*;
/**
* @author lyifee
* on 2021/1/25
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaplePipeline {
String site() default "";
}
|
/*
* Davis Odom
* 10/20/15
* Recursively sums the digits or a given long
*/
import java.util.Scanner;
public class Program {
public static void main(String[] args){
//get the number and call the method in a print statement
Scanner in = new Scanner(System.in);
System.out.print("Please enter a long to be summed: ");
System.out.print(sumDigits(in.nextLong()));
}
//sums the digits of a given long recursively
public static int sumDigits(long n){
//turn it into a string
String str = ""+n;
//if the string is longer than one char
if(str.length() > 1){
//add the first digit to the rest recursively
return Integer.parseInt(""+str.charAt(0)) + sumDigits(Long.parseLong(str.substring(1)));
}else{
//otherwise return the last digit
return (int) Long.parseLong(str);
}
}
}
|
/*
* The MIT License
*
* Copyright 2019 tibo.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package be.cylab.mark.datastore;
import be.cylab.mark.core.RawData;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import junit.framework.TestCase;
/**
*
* @author tibo
*/
public class JsonRPCTest extends TestCase {
public void testStringRequest() throws IOException, Throwable {
String query = "{\"id\":\"1353101991\",\"jsonrpc\":\"2.0\",\"method\":\"findRawData\",\"params\":[\"data.http\",{\"client\":\"1.2.3.4\",\"server\":\"www.google.be\"}]}";
System.out.println(query);
ObjectNode node = new ObjectMapper().readValue(query, ObjectNode.class);
System.out.println(node);
assertEquals(query, node.toString());
/*JsonRpcHttpClient client = new JsonRpcHttpClient(new URL("http://127.0.0.1:8000"));
try {
RawData[] data = client.invoke(node, RawData[].class, new HashMap<>());
fail("Should throw an exception");
} catch (java.net.ConnectException ex) {
return;
}
fail("Should throw an exception");*/
}
}
|
package com.gustavotavaresdomingues.cursoandroid.frasesdodia;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void gerarNovaFrase(View view) {
String[] frases = {
"Frase 1",
"Frase 2",
"Frase 3",
"Frase 4"
};
int n = new Random().nextInt(4); //0 1 2 3
TextView texto = findViewById(R.id.txtResultado);
texto.setText(frases[n]);
}
}
|
import org.junit.Test;
public class Main {
@Test
public void testHelloWrold() {
System.out.println("HelloWorld!");
System.out.println("共同修改后的!");
System.out.println("第一次修改zkr");
}
}
|
package com.smxknife.datastructure.redblacktree;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* @author smxknife
* 2019/11/21
*/
public class RBTreeTest {
private RBTree tree;
private NodeTraversalStrategy strategy;
private RBNode target;
@BeforeEach
public void init() {
// root
RBNode root = new RBNode(10);
// level 1
RBNode left1 = new RBNode(8);target = left1;
RBNode right1 = new RBNode(11);
root.setLeft(left1);
root.setRight(right1);
// level2
RBNode left12 = new RBNode(1);
RBNode right12 = new RBNode(9);
left1.setLeft(left12);
left1.setRight(right12);
strategy = new DeepNodeTraversalStrategy();
tree = new RBTree(root, strategy);
}
@Test
public void queryTest() {
RBNode query = tree.query(8);
System.out.println(query);
assert target == query;
}
}
|
package com.example.cine.model;
import java.io.Serializable;
public class Poster implements Serializable {
String href;
}
|
package collectionpackage;
import java.util.Comparator;
public class ComparatorSet implements Comparator {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/*
* @Override public int compare(Object o1, Object o2) { // TODO Auto-generated
* method stub Integer t1 = (Integer)o1; Integer t2 = (Integer)o2;
* //Autoboxing-automatic conversion in //collection if(t2>t1) return 1; else
* if(t1>t2) return -1; else return 0; }
*/
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
TreeSetObject t1 = (TreeSetObject)o1;
TreeSetObject t2 = (TreeSetObject)o2;
int Result=t1.Trainee.compareTo(t2.Trainee);
if(Result>0)
return 1;
else if(Result<0)
return -1;
else
return 0;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.01.28 at 02:11:12 PM CST
//
package org.mesa.xml.b2mml;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for QuantityValueType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="QuantityValueType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="QuantityString" type="{http://www.mesa.org/xml/B2MML-V0600}QuantityStringType"/>
* <element name="DataType" type="{http://www.mesa.org/xml/B2MML-V0600}DataTypeType" minOccurs="0"/>
* <element name="UnitOfMeasure" type="{http://www.mesa.org/xml/B2MML-V0600}UnitOfMeasureType" minOccurs="0"/>
* <element name="Key" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" minOccurs="0"/>
* <group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}Quantity" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QuantityValueType", propOrder = {
"quantityString",
"dataType",
"unitOfMeasure",
"key"
})
public class QuantityValueType {
@XmlElement(name = "QuantityString", required = true, nillable = true)
protected QuantityStringType quantityString;
@XmlElementRef(name = "DataType", namespace = "http://www.mesa.org/xml/B2MML-V0600", type = JAXBElement.class, required = false)
protected JAXBElement<DataTypeType> dataType;
@XmlElementRef(name = "UnitOfMeasure", namespace = "http://www.mesa.org/xml/B2MML-V0600", type = JAXBElement.class, required = false)
protected JAXBElement<UnitOfMeasureType> unitOfMeasure;
@XmlElement(name = "Key")
protected IdentifierType key;
/**
* Gets the value of the quantityString property.
*
* @return
* possible object is
* {@link QuantityStringType }
*
*/
public QuantityStringType getQuantityString() {
return quantityString;
}
/**
* Sets the value of the quantityString property.
*
* @param value
* allowed object is
* {@link QuantityStringType }
*
*/
public void setQuantityString(QuantityStringType value) {
this.quantityString = value;
}
/**
* Gets the value of the dataType property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link DataTypeType }{@code >}
*
*/
public JAXBElement<DataTypeType> getDataType() {
return dataType;
}
/**
* Sets the value of the dataType property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link DataTypeType }{@code >}
*
*/
public void setDataType(JAXBElement<DataTypeType> value) {
this.dataType = value;
}
/**
* Gets the value of the unitOfMeasure property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link UnitOfMeasureType }{@code >}
*
*/
public JAXBElement<UnitOfMeasureType> getUnitOfMeasure() {
return unitOfMeasure;
}
/**
* Sets the value of the unitOfMeasure property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link UnitOfMeasureType }{@code >}
*
*/
public void setUnitOfMeasure(JAXBElement<UnitOfMeasureType> value) {
this.unitOfMeasure = value;
}
/**
* Gets the value of the key property.
*
* @return
* possible object is
* {@link IdentifierType }
*
*/
public IdentifierType getKey() {
return key;
}
/**
* Sets the value of the key property.
*
* @param value
* allowed object is
* {@link IdentifierType }
*
*/
public void setKey(IdentifierType value) {
this.key = value;
}
}
|
package fr.lteconsulting;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewHelper
{
public static void displayWelcomeView( Utilisateur utilisateur, Date dateConnexion, HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException
{
request.setAttribute( "utilisateur", utilisateur );
request.setAttribute( "dateConnection", dateConnexion );
request.getRequestDispatcher( "/WEB-INF/welcome.jsp" )
.forward( request, response );
}
public static void displayLoginView( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
request.getRequestDispatcher( "/WEB-INF/loginForm.jsp" )
.forward( request, response );
}
}
|
package Exercicio01;
import java.util.Calendar;
import java.util.Date;
public class ProgramaPessoa {
public static void main(String[] args) {
Pessoa pessoa = new Pessoa("Henrique Oliveira", "03-08-2000", 1.9);
CalculoPesso calculo = new CalculoPesso();
calculo.calculaIdade(pessoa);
System.out.println(pessoa);
}
}
|
package edu.nju.logic.service;
import edu.nju.data.entity.Answer;
import edu.nju.data.entity.User;
import edu.nju.data.util.VoteType;
import edu.nju.logic.vo.AnswerVO;
import java.util.List;
/**
* 回答接口
* @author cuihao
*/
public interface AnswerService {
/**
* 将问题标注为满意回答
* @param user 当前登陆用户
* @param questionId 问题ID
* @param answerId 回答ID
* @return 是否有权限标注
*/
boolean markAsSolution(User user, long questionId, long answerId);
/**
* 保存回答
* @param questionId 回答的问题ID
* @param userId 回答该问题的用户id
* @param text 回答的内容
* @return 是否保存成功
*/
boolean saveAnswer(long questionId, long userId, String text, List wikiIds, List docIds);
/**
* 修改回答
* @param answerId 回答id
* @param text 修改后的内容
* @return 是否修改成功:现在只有true
*/
boolean editAnswer(long answerId, String text);
/**
* 删除回答
* @param answerId 回答id
* @param userId 用户id
* @return 是否有权限删除
*/
boolean deleteAnswer(long answerId, long userId);
Answer getAnswer(long answerId);
/**
* 点赞
* @param questionId 问题id
* @param answerId 答案id
* @param userId 用户id
* @param type 顶还是踩
* @return 投票后的总票数
*/
int vote(String questionId, String answerId, String userId, VoteType type);
}
|
package DPI.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import DPI.entity.Message;
@Mapper
@Component
public interface MessageDao {
void insertMessage(Message message);
List<Message> loadMessageByUser(@Param("sender") String sender,@Param("addressee") String addressee);
Message loadLastMessageByUser(@Param("sender") String sender,@Param("addressee") String addressee);
}
|
package leecode.other;
//这个和左神那个题目对比,这个四个方向都可以走,左神那个只能走两个方向
//理解 dp+dfs https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/solution/javashi-xian-shen-du-you-xian-chao-ji-jian-dan-yi-/
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.function.BinaryOperator;
public class 矩阵中的最长递增路径_329 {
public static int longestIncreasingPath(int[][] matrix) {
int m=matrix.length;//m行n列
if(m==0){
return 0;
}
int n=matrix[0].length;
int[][]step={{0,1},{0,-1},{1,0},{-1,0}};
boolean[][]visit=new boolean[m][n];
int max=1;
int[][]dp=new int[m][n];
for (int i = 0; i <m; i++) {//不要忘记这两个循环,而不是只是传个0,0就好了
for (int j = 0; j <n ; j++) {
max=Math.max(max,method(matrix,step,visit,i,j,dp));
}
}
return max;
}
public static int method(int[][]matrix,int[][]step,boolean[][]visit,
int startx,int starty,int[][]dp){//返回i,j为起点的最长递增路径长度
// if(startx==0||starty==0||startx==matrix.length-1||starty==matrix[0].length-1){
// return length+1;
// }
if(dp[startx][starty]!=0){
return dp[startx][starty];
}
visit[startx][starty]=true;
int temp=matrix[startx][starty];
int max=1;
for (int i = 0; i <4 ; i++) {
int newx=startx+step[i][0];
int newy=starty+step[i][1];
if(hefa(matrix,newx,newy)&&!visit[newx][newy]){
if(matrix[newx][newy]>temp){
max=Math.max(max,method(matrix,step,visit,newx,newy,dp)+1);//这里不要忘记加1
}
}
}
visit[startx][starty]=false;
dp[startx][starty]=max;
return max;
}
public static boolean hefa(int[][]matrix,int x,int y){
int m=matrix.length;
int n=matrix[0].length;
if(x>=0&&x<m&&y>=0&&y<n){
return true;
}
return false;
}
//dp+DFS记忆化搜索 https://www.jianshu.com/p/99d1e2ca99e8
public static int longestIncreasingPathwithdp(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int max = 0;
int row = matrix.length;
int col = matrix[0].length;
int[][] dp = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
// loop 是返回每个节点开始的最长递增路径,max求所有节点中的最大值
max = Math.max(max, loop(matrix, dp, i, j));
}
}
return max;
}
//使用数组dp记录每个节点开始的最长升序路径长度
static int[][]dir={{1,0},{-1,0},{0,-1},{0,1}};//一定要有一个0!!
private static int loop(int[][] matrix, int[][] dp, int i, int j) {
if(!bound(i,j,matrix)){//这个条件不写也可以,因为下面dfs前已经判断了
return 0;
}
if(dp[i][j]>0){
return dp[i][j];
}
int max=0;//记录四个方向中的最大值
for (int k = 0; k <4 ; k++) {
int x = i + dir[k][0];
int y = j + dir[k][1];
if (bound(x, y, matrix) && matrix[i][j] < matrix[x][y]) {//注意这个大小条件,递增才可以dfs!!
max=Math.max(max,loop(matrix,dp,x,y));
}
}
dp[i][j]=max+1;//max是四周的最大值,dp[i][j]要将max加上自己
return dp[i][j];
}
public static boolean bound(int x,int y, int[][]matrix){
return x>=0&&x<matrix.length&&y>=0&&y<matrix[0].length;
}
//拓扑排序
//https://leetcode-cn.com/problems/longest-increasing-path-in-a-matrix/solution/zhi-jie-tao-yong-tuo-bu-pai-xu-mo-ban-mei-you-ji-q/
public static int longestIncreasingPathwithsort(int[][] matrix) {
int[][]count = new int[matrix.length][matrix[0].length];//count存储入度,二维的,课程表那个是一维的
for (int i = 0; i <matrix.length ; i++) {
for (int j = 0; j <matrix[0].length ; j++) {
for (int[]d:dir) {
if(bound(i+d[0],j+d[1],matrix)&&matrix[i+d[0]][j+d[1]]<matrix[i][j]){//周围比它小,它入度加1
count[i][j]++;
}
}
}
}
//课程表需要构造 List<List<Integer>>adjacency 记录节点指向的所有边,这个不需要,就是4个方向
//队列放int[]标识每个点
Queue<int[]>queue=new ArrayDeque<>();
for (int i = 0; i <count.length ; i++) {
for (int j = 0; j <count[0].length ; j++) {
if(count[i][j]==0){
queue.add(new int[]{i,j});
}
}
}
int ans=0;//记录最长路径
while (!queue.isEmpty()){
ans++;
//这个需要一层一层的全部出队列!
//这个跟课程表I那个题不一样,需要一层一层的出列,而不是一个一个的出,因为课程表那个不关心队列长度
for (int size = queue.size(); size >0 ; size--) {//size是>0
int[]cur=queue.poll();
for(int[]d:dir){
if(bound(cur[0]+d[0],cur[1]+d[1],matrix)
&&matrix[cur[0]+d[0]][cur[1]+d[1]]>matrix[cur[0]][cur[1]]){
count[cur[0]+d[0]][cur[1]+d[1]]=count[cur[0]+d[0]][cur[1]+d[1]]-1;
if(count[cur[0]+d[0]][cur[1]+d[1]]==0){
queue.add(new int[]{cur[0]+d[0],cur[1]+d[1]});
}
}
}
}
}
return ans;
}
public static void main(String[] args) {
int[][]num={ {9,9,4},
{6,6,8},
{2,1,1}
};
System.out.println(longestIncreasingPath(num));
System.out.println(longestIncreasingPathwithdp(num));
}
}
|
package com.tencent.mm.sandbox.updater;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import com.tencent.mm.R;
import com.tencent.mm.bf.a;
import com.tencent.mm.pluginsdk.ui.tools.k;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.e.i;
import com.tencent.xweb.WebView;
import com.tencent.xweb.r;
import com.tencent.xweb.x5.sdk.f;
public final class d implements a {
private Intent intent;
private Notification owf;
private a sDY;
private int sDZ;
private boolean sEa;
private boolean sEb;
/* synthetic */ d(byte b) {
this();
}
static /* synthetic */ void a(d dVar) {
if (dVar.sEa) {
String bQ = bi.bQ(ad.getContext());
x.i("MicroMsg.TBSDownloadMgr", "topActivityName = %s", new Object[]{bQ});
if (bi.oW(bQ) || !bQ.equalsIgnoreCase("com.tencent.mm.plugin.webview.ui.tools.WebViewUI")) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(i.thA, "com.tencent.mm.booter.MMReceivers$ToolsProcessReceiver"));
intent.putExtra("tools_process_action_code_key", "com.tencent.mm.intent.ACTION_KILL_TOOLS_PROCESS");
ad.getContext().sendBroadcast(intent);
Context context = ad.getContext();
android.support.v4.app.z.d dVar2 = new android.support.v4.app.z.d(context);
NotificationManager notificationManager = (NotificationManager) context.getSystemService("notification");
dVar2.Y(a.cbg());
dVar2.b(context.getString(R.l.webview_tbs_install_success_title));
dVar2.c(context.getString(R.l.webview_tbs_install_success_content));
dVar2.j(2, false);
dVar2.u(true);
dVar2.pu = PendingIntent.getActivity(ad.getContext(), 0, new Intent(), 0);
dVar.owf = dVar2.build();
notificationManager.notify(dVar.sDZ, dVar.owf);
intent = new Intent();
intent.setComponent(new ComponentName(i.thA, "com.tencent.mm.booter.MMReceivers$ToolsProcessReceiver"));
intent.putExtra("tools_process_action_code_key", "com.tencent.mm.intent.ACTION_START_TOOLS_PROCESS");
ad.getContext().sendBroadcast(intent);
}
}
}
static {
r.a(ad.getContext(), new 1());
com.tencent.xweb.b.d.a(com.tencent.mm.plugin.cdndownloader.e.a.aAr());
}
public static d cgU() {
return b.sEd;
}
private d() {
this.sDY = null;
this.intent = new Intent();
this.owf = null;
this.sDZ = 999;
this.sEa = false;
this.sEb = false;
}
public final void la(boolean z) {
if (this.sDY == null) {
x.w("MicroMsg.TBSDownloadMgr", "TBS download not inited, ignore");
return;
}
Context context = ad.getContext();
boolean isDownloading = f.isDownloading();
boolean needDownload = f.needDownload(context, this.sEa | this.sEb);
boolean booleanExtra = this.intent.getBooleanExtra("intent_extra_download_ignore_network_type", false);
boolean isDownloadForeground = f.isDownloadForeground();
x.i("MicroMsg.TBSDownloadMgr", "setNetStatChanged, isWifi = %b, downloading = %b, needDownload = %b, ignoreNetworkType = %b", new Object[]{Boolean.valueOf(z), Boolean.valueOf(isDownloading), Boolean.valueOf(needDownload), Boolean.valueOf(booleanExtra)});
if ((z || booleanExtra) && !isDownloading && needDownload) {
cgV();
k.kB(3);
} else if (!z && !booleanExtra && isDownloading && !isDownloadForeground) {
f.stopDownload();
k.kB(4);
}
}
private void cgV() {
f.startDownload(ad.getContext());
SharedPreferences sharedPreferences = ad.getContext().getSharedPreferences("com.tencent.mm_webview_x5_preferences", 4);
if (sharedPreferences != null) {
x.i("MicroMsg.TBSDownloadMgr", "now start download,hasDownloadOverSea over sea = %b, is now oversea = %b", new Object[]{Boolean.valueOf(this.sEb), Boolean.valueOf(this.sEa)});
if (this.sEb || this.sEa) {
sharedPreferences.edit().putBoolean("tbs_download_oversea", true).commit();
}
}
}
public final boolean ao(Intent intent) {
this.intent = intent;
this.sEa = this.intent.getIntExtra("intent_extra_download_type", 1) == 2;
SharedPreferences sharedPreferences = ad.getContext().getSharedPreferences("com.tencent.mm_webview_x5_preferences", 4);
if (sharedPreferences != null) {
this.sEb = sharedPreferences.getBoolean("tbs_download_oversea", false);
}
x.i("MicroMsg.TBSDownloadMgr", "isOverSea = %b, hasDownloadOverSea = %b", new Object[]{Boolean.valueOf(this.sEa), Boolean.valueOf(this.sEb)});
if (f.isDownloading()) {
x.i("MicroMsg.TBSDownloadMgr", "TBS already downloading, ignore duplicated request");
return true;
}
Context context = ad.getContext();
int installedTbsCoreVersion = WebView.getInstalledTbsCoreVersion(context);
x.i("MicroMsg.TBSDownloadMgr", "TBS download, tbsCoreVersion = %d, needDownload = %b, isWifi = %b, ignoreNetworkType = %b", new Object[]{Integer.valueOf(installedTbsCoreVersion), Boolean.valueOf(f.needDownload(context, this.sEa | this.sEb)), Boolean.valueOf(ao.isWifi(context)), Boolean.valueOf(this.intent.getBooleanExtra("intent_extra_download_ignore_network_type", false))});
if ((!ao.isWifi(context) && !r5) || !r4) {
return false;
}
if (this.sDY == null) {
this.sDY = new a(this, (byte) 0);
com.tencent.xweb.x5.sdk.d.a(this.sDY);
k.kB(2);
}
cgV();
k.kB(3);
return true;
}
public final boolean isBusy() {
x.i("MicroMsg.TBSDownloadMgr", "isBusy isDownloading = %b, isInstalling = %b", new Object[]{Boolean.valueOf(f.isDownloading()), Boolean.valueOf(com.tencent.xweb.x5.sdk.d.getTBSInstalling())});
if (f.isDownloading() || r3) {
return true;
}
return false;
}
public final void onDestroy() {
x.i("MicroMsg.TBSDownloadMgr", "onDestroy");
}
}
|
package de.jmda.gradle;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
* Created by RWE on 03.08.2017.
*/
public class PingApp
{
private final static Logger LOGGER = LogManager.getLogger(PingApp.class);
public static void main(String[] args)
{
System.out.println("Hello from System.out");
LOGGER.debug("Hello from log4j logger");
PingService pingService = new PingService();
LOGGER.debug("ping: " + pingService.ping());
}
}
|
package extendedNodePositionList;
import net.datastructures.Position;
import net.datastructures.PositionList;
import net.datastructures.NodePositionList;
import net.datastructures.BoundaryViolationException;
/**
* This class extends the <code>NodePositionList</code> class with
* two new methods:
* <code>nth</code> (access the nth node of a list)
* and <code>fairMerge</code> (merge two lists into a new list).
* You may add new methods and variables if you so wish.
*/
public class ExtendedNodePositionList<E>
extends NodePositionList<E>
implements PositionList<E>
{
public ExtendedNodePositionList() {
// Don't change this definition
super();
}
/**
* Return the <code>n</code>th node in the position list,
* where the indices in the list are numbered 1,2,3,...
* If there are too few nodes in the list the exception
* <code>BoundaryViolationException</code> should be thrown.
* Examples using a list containing nodes with elements 1,2,5,4,5:<p>
* nth(1) should return the node containing 1<br>
* nth(3) should return the node containing 5<br>
* nth(6) should throw an exception BoundaryViolationException.
* <p>You may assume that n is a positive integer.
*/
public Position<E> nth(int n) throws BoundaryViolationException {
if (n>numElts)
throw new BoundaryViolationException("La posición pedida " +
"está fuera de rango");
else{
Position<E> resultado=this.first();
boolean encontrado=false;
for(int i=1;i<=numElts && !encontrado;i++){
if(n==i)
encontrado=true;
else
resultado=this.next(resultado);
}
return resultado;
}
}
/**
* Returns a <strong>new</strong> list containing a "fair" merge of
* the object list (accessible through <code>this</code>) and the argument
* <code>otherList</code>.
*
* The resulting list contains the elements in
* <code>this</code> alternating with elements from <code>otherList</code>,
* beginning with an element from <code>this</code>,
* and respecting the order of elements in <code>this</code>
* and <code>otherList</code>. <p>
* That is, the first element of resulting list
* is the first element of <code>this</code>, the second element
* is the first element of <code>otherList</code>, the third
* element is the second element of <code>this</code>, the fourth
* element is the second element of <code>otherList</code>, the
* fifth element is the third element of <code>this</code>, and so on.
*
* <p>Examples:
* given a list <code>l1</code> with the elements 1,2,3
* and another list <code>l2</code> with the elements -1,-2,-3,-4,-5
* then:<br>calling <code>l1.fairMerge(l2)</code> returns a
* new list 1,-1,2,-2,3,-3,-4,-5;<br>calling
* <code>l2.fairMerge(l1)</code> returns a new list
* -1,1,-2,2,-3,3,-4,-5.<p>
* Note that the argument lists should not
* be changed by calling <code>fairMerge</code>.
* Example:</br>
* if <code>l1</code> contains the element 1 and
* <code>l2</code> contains the element -2 then
* <code>l1.fairMerge(l2)</code> returns the new list 1,-2 and afterwards
* <code>l1</code> still contains the single element 1 and
* <code>l2</code> still contains the single element -2.
*<p>It can be assumed that otherList is not null.
*/
public ExtendedNodePositionList<E> fairMerge(PositionList<E> otherList) {
ExtendedNodePositionList<E> mergedList =
new ExtendedNodePositionList<E>();
ExtendedNodePositionList<E> list2=
(ExtendedNodePositionList<E>)otherList;
Position<E> p1=this.first();
Position<E> p2=otherList.first();
int size1=this.size();
int size2=otherList.size();
boolean turno=false;
for(int i=1;i<=this.numElts + otherList.size();i++){
try{
if(i==1)
mergedList.addFirst(this.nth(i).element());
else{
if()
mergedList.addAfter(mergedList.nth(i/2),list2.nth(i/2).element());
else
mergedList.addAfter(mergedList.nth(i%2+i/2),this.nth(i%2+i/2).element());
}
}
catch(BoundaryViolationException("")){
}
// Add new code below, but do return mergedList
return mergedList;
}
}
}
|
package com.cnk.travelogix.custom.zifwsb.invoice.create;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import com.cnk.travelogix.sapintegrations.dto.factory.DTOObjectFactory;
/**
* This object contains factory methods for each Java content interface and Java element interface generated in the
* com.cnk.client package.
* <p>
* An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content.
* The Java representation of XML content can consist of schema derived interfaces and classes representing the binding
* of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in
* this class.
*
*/
@XmlRegistry
public class ObjectFactory implements DTOObjectFactory
{
private final static QName ZIFWSINVOICECREATE_QNAME = new QName("urn:sap-com:document:sap:soap:functions:mc-style",
"ZIffmBillDocCreate");
private final static QName ZIFWSINVOICECREATE_RESPONSE_QNAME = new QName("urn:sap-com:document:sap:soap:functions:mc-style",
"ZIffmBillDocCreateResponse");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package:
* com.cnk.client
*
*/
public ObjectFactory()
{
}
/**
* Create an instance of {@link ZIffmBillDocCreate }
*
*/
public ZIffmBillDocCreate createZIffmBillDocCreate()
{
return new ZIffmBillDocCreate();
}
/**
* Create an instance of {@link ZttBilldoc }
*
*/
public ZttBilldoc createZttBilldoc()
{
return new ZttBilldoc();
}
/**
* Create an instance of {@link ZIffmBillDocCreateResponse }
*
*/
public ZIffmBillDocCreateResponse createZIffmBillDocCreateResponse()
{
return new ZIffmBillDocCreateResponse();
}
/**
* Create an instance of {@link ZifstStatusDoc }
*
*/
public ZifstStatusDoc createZifstStatusDoc()
{
return new ZifstStatusDoc();
}
/**
* Create an instance of {@link ZifstBilldoc }
*
*/
public ZifstBilldoc createZifstBilldoc()
{
return new ZifstBilldoc();
}
@XmlElementDecl(namespace = "urn:sap-com:document:sap:soap:functions:mc-style", name = "ZIffmBillDocCreate")
public JAXBElement<ZIffmBillDocCreate> createZIffmInvoice(final ZIffmBillDocCreate value)
{
return new JAXBElement<ZIffmBillDocCreate>(ZIFWSINVOICECREATE_QNAME, ZIffmBillDocCreate.class, null, value);
}
@XmlElementDecl(namespace = "urn:sap-com:document:sap:soap:functions:mc-style", name = "ZIffmBillDocCreateResponse")
public JAXBElement<ZIffmBillDocCreateResponse> createZIffmInvoiceSaveResponse(final ZIffmBillDocCreateResponse value)
{
return new JAXBElement<ZIffmBillDocCreateResponse>(ZIFWSINVOICECREATE_RESPONSE_QNAME, ZIffmBillDocCreateResponse.class,
null, value);
}
}
|
package com.sinata.rwxchina.component_home.entity;
/**
* @author HRR
* @datetime 2017/11/27
* @describe 首页品牌区实体类
* @modifyRecord
*/
public class BrandEntity {
/**
* goods_type : 10010
* name : 轮胎
* logo : /Uploads/App/goodstype/1.jpg
* describe : 轮子就是好呀
*/
private String goods_type;
private String name;
private String logo;
private String describe;
public String getGoods_type() {
return goods_type;
}
public void setGoods_type(String goods_type) {
this.goods_type = goods_type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
@Override
public String toString() {
return "BrandEntity{" +
"goods_type='" + goods_type + '\'' +
", name='" + name + '\'' +
", logo='" + logo + '\'' +
", describe='" + describe + '\'' +
'}';
}
}
|
package controllers;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import models.User;
import utils.OTP;
import utils.EmailSender;
public class ForgetPasswordOTPServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
HttpSession session = request.getSession();
String email = request.getParameter("email");
String otps = OTP.createOTP();
String message = "Your one time password(OTP) from PREZZIE LEGECY in is "+otps;
EmailSender.sendEmail(email,"welcome to prezzie legecy",message,"legecyprezzie@gmail.com","PrezzieLegecy@1");
session.setAttribute("ftp_otp",otps);
}
}
|
package pe.gob.trabajo.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* LISTA MAESTRA DE LOS MOTIVOS DE CESE
*/
@ApiModel(description = "LISTA MAESTRA DE LOS MOTIVOS DE CESE")
@Entity
@Table(name = "gltbc_motcese")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Document(indexName = "gltbc_motcese")
public class Motcese implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
@Column(name = "n_codmotces", nullable = false)
private Long id;
/**
* DESCRIPCION DEL MOTIVO DE CESE.
*/
@NotNull
@Size(max = 200)
@ApiModelProperty(value = "DESCRIPCION DEL MOTIVO DE CESE.", required = true)
@Column(name = "v_desmotces", length = 200, nullable = false)
private String vDesmotces;
/**
* CODIGO DEL USUARIO QUE REGISTRA.
*/
@NotNull
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE REGISTRA.", required = true)
@Column(name = "n_usuareg", nullable = false)
private Integer nUsuareg;
/**
* FECHA Y HORA DEL REGISTRO.
*/
@NotNull
@ApiModelProperty(value = "FECHA Y HORA DEL REGISTRO.", required = true)
@Column(name = "t_fecreg", nullable = false)
private Instant tFecreg;
/**
* ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO)
*/
@NotNull
@ApiModelProperty(value = "ESTADO ACTIVO DEL REGISTRO (1=ACTIVO, 0=INACTIVO)", required = true)
@Column(name = "n_flgactivo", nullable = false)
private Boolean nFlgactivo;
/**
* CODIGO DE LA SEDE DONDE SE REGISTRA.
*/
@NotNull
@ApiModelProperty(value = "CODIGO DE LA SEDE DONDE SE REGISTRA.", required = true)
@Column(name = "n_sedereg", nullable = false)
private Integer nSedereg;
/**
* CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.")
@Column(name = "n_usuaupd")
private Integer nUsuaupd;
/**
* CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DEL USUARIO QUE MODIFICA EL REGISTRO.")
@Column(name = "t_fecupd")
private Instant tFecupd;
/**
* CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO.
*/
@ApiModelProperty(value = "CODIGO DE LA SEDE DONDE SE MODIFICA EL REGISTRO.")
@Column(name = "n_sedeupd")
private Integer nSedeupd;
@OneToMany(mappedBy = "motcese")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Datlab> datlabs = new HashSet<>();
// jhipster-needle-entity-add-field - Jhipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getvDesmotces() {
return vDesmotces;
}
public Motcese vDesmotces(String vDesmotces) {
this.vDesmotces = vDesmotces;
return this;
}
public void setvDesmotces(String vDesmotces) {
this.vDesmotces = vDesmotces;
}
public Integer getnUsuareg() {
return nUsuareg;
}
public Motcese nUsuareg(Integer nUsuareg) {
this.nUsuareg = nUsuareg;
return this;
}
public void setnUsuareg(Integer nUsuareg) {
this.nUsuareg = nUsuareg;
}
public Instant gettFecreg() {
return tFecreg;
}
public Motcese tFecreg(Instant tFecreg) {
this.tFecreg = tFecreg;
return this;
}
public void settFecreg(Instant tFecreg) {
this.tFecreg = tFecreg;
}
public Boolean isnFlgactivo() {
return nFlgactivo;
}
public Motcese nFlgactivo(Boolean nFlgactivo) {
this.nFlgactivo = nFlgactivo;
return this;
}
public void setnFlgactivo(Boolean nFlgactivo) {
this.nFlgactivo = nFlgactivo;
}
public Integer getnSedereg() {
return nSedereg;
}
public Motcese nSedereg(Integer nSedereg) {
this.nSedereg = nSedereg;
return this;
}
public void setnSedereg(Integer nSedereg) {
this.nSedereg = nSedereg;
}
public Integer getnUsuaupd() {
return nUsuaupd;
}
public Motcese nUsuaupd(Integer nUsuaupd) {
this.nUsuaupd = nUsuaupd;
return this;
}
public void setnUsuaupd(Integer nUsuaupd) {
this.nUsuaupd = nUsuaupd;
}
public Instant gettFecupd() {
return tFecupd;
}
public Motcese tFecupd(Instant tFecupd) {
this.tFecupd = tFecupd;
return this;
}
public void settFecupd(Instant tFecupd) {
this.tFecupd = tFecupd;
}
public Integer getnSedeupd() {
return nSedeupd;
}
public Motcese nSedeupd(Integer nSedeupd) {
this.nSedeupd = nSedeupd;
return this;
}
public void setnSedeupd(Integer nSedeupd) {
this.nSedeupd = nSedeupd;
}
public Set<Datlab> getDatlabs() {
return datlabs;
}
public Motcese datlabs(Set<Datlab> datlabs) {
this.datlabs = datlabs;
return this;
}
public Motcese addDatlab(Datlab datlab) {
this.datlabs.add(datlab);
datlab.setMotcese(this);
return this;
}
public Motcese removeDatlab(Datlab datlab) {
this.datlabs.remove(datlab);
datlab.setMotcese(null);
return this;
}
public void setDatlabs(Set<Datlab> datlabs) {
this.datlabs = datlabs;
}
// jhipster-needle-entity-add-getters-setters - Jhipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Motcese motcese = (Motcese) o;
if (motcese.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), motcese.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Motcese{" +
"id=" + getId() +
", vDesmotces='" + getvDesmotces() + "'" +
", nUsuareg='" + getnUsuareg() + "'" +
", tFecreg='" + gettFecreg() + "'" +
", nFlgactivo='" + isnFlgactivo() + "'" +
", nSedereg='" + getnSedereg() + "'" +
", nUsuaupd='" + getnUsuaupd() + "'" +
", tFecupd='" + gettFecupd() + "'" +
", nSedeupd='" + getnSedeupd() + "'" +
"}";
}
}
|
import java.util.*;
import java.util.SortedSet;
import java.util.TreeSet;
import javafx.beans.property.SimpleStringProperty;
public class Board {
public SortedSet<Integer> whitePieces, blackPieces;
public int[] gameMatrix;
public int numberOfTurns;
public int noPiecesRemovedCount;
int[] numberTrios= {0,0}; // {white, black}
public SortedSet<Integer> whiteTriosPositions, blackTriosPositions;
public SimpleStringProperty turnProperty;
public SimpleStringProperty excludeProperty = new SimpleStringProperty("A IA é muito forte! Cuidado...");
public SimpleStringProperty winProperty = new SimpleStringProperty("Quem será que irá ganhar? ");
public SimpleStringProperty turnsProperty = new SimpleStringProperty();
public boolean isWhitePhase3;
public boolean isBlackPhase3;
public boolean isExcludeMode;
public boolean turn; // true = white, false = black
public final static int EMPTY = 3;
public final static int WHITE = 0;
public final static int BLACK = 1;
static final int[][] TRIOS = {
{0,1,2}, {3,4,5}, {6,7,8}, {9,10,11}, {12,13,14}, {15,16,17},{18,19,20}, {21,22,23},
{0,9,21},{3,10,18},{6,11,15}, {1,4,7}, {16,19,22}, {8,12,17}, {5,13,20}, {2,14,23}
} ;
public static final int[][] NEIGHBORHOOD =
{
{ 1, 9 }, { 0,2,4 }, { 1,14 },
{ 4,10 }, { 3,5,1,7 }, { 4,13 },
{ 7,11 }, { 6,8,4 }, { 7,12 },
{ 21,0,10 }, { 18,3,9,11 }, { 6,15,10 }, { 17,8,13 }, { 5,20,14,12 }, { 2,23,13 },
{ 11,16 }, { 15,17,19 }, { 12,16 },
{ 10,19 }, { 18,20,16,22 }, { 13,19 },
{ 9,22 }, { 23,21,19 }, { 14,22 }
};
public Board(){
gameMatrix = new int[24];
for (int i = 0; i < 24; i++) gameMatrix[i] = Board.EMPTY;
numberOfTurns = 0;
noPiecesRemovedCount = 0;
whitePieces = new TreeSet<>();
blackPieces = new TreeSet<>();
turn = true;
isExcludeMode = false;
turnProperty = new SimpleStringProperty("Turno: Brancas jogam");
turnsProperty.set("Rodadas sem remoção de peças: " + noPiecesRemovedCount);
whiteTriosPositions = blackTriosPositions = new TreeSet<>();
}
public Board(Board t){
gameMatrix = new int[24];
System.arraycopy(t.gameMatrix, 0, gameMatrix, 0, 24);
numberOfTurns = t.numberOfTurns;
noPiecesRemovedCount = t.noPiecesRemovedCount;
whitePieces = new TreeSet<>();
Iterator<Integer>it = t.whitePieces.iterator();
while (it.hasNext()){
int aux = it.next();
whitePieces.add(aux);
}
blackPieces = new TreeSet<>();
it = t.blackPieces.iterator();
while (it.hasNext()){
int aux = it.next();
blackPieces.add(aux);
}
turn = t.turn;
isExcludeMode = t.isExcludeMode;
turnProperty = t.turnProperty;
whiteTriosPositions = t.whiteTriosPositions;
blackTriosPositions = t.blackTriosPositions;
}
public int getOccupant(int position){
return gameMatrix[position];
}
public int getNumberOfTurns(){
return numberOfTurns;
}
public void incrementNumberOfTurns(){
numberOfTurns++;
}
public void decrementNumberOfTurns(){
numberOfTurns--;
}
public void incrementNoPieceRemovedCount(){
noPiecesRemovedCount++;
}
public void setIsWhitePhase3(boolean isPhase3){
isWhitePhase3 = isPhase3;
}
public void setIsBlackPhase3(boolean isPhase3){
isBlackPhase3 = isPhase3;
}
public boolean addPiece(int position, int player){
if ( gameMatrix[position] != Board.EMPTY ) return true;
gameMatrix[position] = player;
if (player == WHITE)
whitePieces.add(position);
else
blackPieces.add(position);
return false;
}
public boolean removePiece(int position, int player ){
gameMatrix[position] = Board.EMPTY;
if(player == WHITE)
blackPieces.remove(position);
else
whitePieces.remove(position);
return false;
}
public boolean checkAndRemove(int position, int player){
if (gameMatrix[position] == Board.EMPTY || gameMatrix[position] == player){
excludeProperty.set("Posição inválida! Escolha outra");
return false;
}else if(player == WHITE && numberTrios[1] != 0){
if(blackTriosPositions.contains(position)){
excludeProperty.set("A peça escolhida faz parte de um moinho e não pode ser retirada! Escolha outra");
return false;
}
}else if(player == BLACK && numberTrios[0] != 0){
if(whiteTriosPositions.contains(position)){
excludeProperty.set("A peça escolhida faz parte de um moinho e não pode ser retirada! Escolha outra");
return false;
}
}
return removePiece(position,player);
}
public boolean movePiece(int initialPosition , int finalPosition, boolean currentTurn ){
if(currentTurn){
if(getOccupant(initialPosition) != WHITE && getOccupant(finalPosition) != EMPTY ) return true;
gameMatrix[initialPosition] = Board.EMPTY;
whitePieces.remove(initialPosition);
gameMatrix[finalPosition] = Board.WHITE;
whitePieces.add(finalPosition);
}else{
if(getOccupant(initialPosition) != BLACK && getOccupant(finalPosition) != EMPTY ) return true;
gameMatrix[initialPosition] = Board.EMPTY;
blackPieces.remove(initialPosition);
gameMatrix[finalPosition] = Board.BLACK;
blackPieces.add(finalPosition);
}
return false;
}
public boolean undoMovement(int currentPosition ,int lastPosition, int player, int removedPosition, int noPiecesRemovedCountBefore){
if(numberOfTurns <= 18){ // Phase 1
if(!turn){ // Undo movement from white
whitePieces.remove(currentPosition);
if(removedPosition > -1 && removedPosition < 24)
if(addPiece(lastPosition, BLACK)) return true;
}else{
blackPieces.remove(currentPosition);
if(removedPosition > -1 && removedPosition < 24){
if(addPiece(lastPosition, WHITE)) return true;
}
}
}else{ // Phase 2 and 3
if(!turn){
if(movePiece(currentPosition, lastPosition, true)) return true;
if(removedPosition > -1 && removedPosition < 24){
if(addPiece(removedPosition, BLACK)) return true;
if(blackPieces.size() > 3) setIsBlackPhase3(false);
}
}else{
if(movePiece(currentPosition, lastPosition, false)) return true;
if(removedPosition > -1 && removedPosition < 24){
if(addPiece(removedPosition, WHITE)) return true;
if(whitePieces.size() > 3) setIsWhitePhase3(false);
}
}
}
turn = !turn;
noPiecesRemovedCount = noPiecesRemovedCountBefore;
decrementNumberOfTurns();
hasHappenedMorris(true);
return false;
}
public boolean hasHappenedMorris(boolean undo){
int morris = 0;
SortedSet<Integer> aux = new TreeSet<>();
if(turn){
Iterator<Integer> it = whiteTriosPositions.iterator();
while (it.hasNext()){
int pos = it.next();
aux.add(pos);
}
whiteTriosPositions.clear();
for(int i = 0,j=0; i< 16; i++){
if(whitePieces.contains(TRIOS[i][0]) && whitePieces.contains(TRIOS[i][1]) && whitePieces.contains(TRIOS[i][2])){
morris++;
whiteTriosPositions.add(TRIOS[i][0]);
whiteTriosPositions.add(TRIOS[i][1]);
whiteTriosPositions.add(TRIOS[i][2]);
}
}
if(morris > numberTrios[0]){
if(!undo){
isExcludeMode = true;
noPiecesRemovedCount = -1;
excludeProperty.set("Brancas podem remover uma peça preta já que fizeram um moinho");
}
numberTrios[0] = morris;
return true;
}else{
if(morris< numberTrios[0]){
numberTrios[0] = morris;
return false;
}
if(morris==numberTrios[0]){
if(!aux.equals(whiteTriosPositions) && !undo){
isExcludeMode = true;
noPiecesRemovedCount = -1;
excludeProperty.set("Brancas podem remover uma peça preta já que fizeram um moinho");
return true;
}
}
}
}else{
Iterator<Integer> it = blackTriosPositions.iterator();
while (it.hasNext()){
int pos = it.next();
aux.add(pos);
}
blackTriosPositions.clear();
for(int i = 0,j=0; i< 16; i++){
if(blackPieces.contains(TRIOS[i][0]) && blackPieces.contains(TRIOS[i][1]) && blackPieces.contains(TRIOS[i][2])){
morris++;
blackTriosPositions.add(TRIOS[i][0]);
blackTriosPositions.add(TRIOS[i][1]);
blackTriosPositions.add(TRIOS[i][2]);
}
}
if(morris > numberTrios[1]){
if(!undo){
isExcludeMode = true;
noPiecesRemovedCount = -1;
excludeProperty.set("Pretas podem remover uma peça preta já que fizeram um moinho");
}
numberTrios[1] = morris;
return true;
}else{
if(morris< numberTrios[1]){
numberTrios[1] = morris;
return false;
}
if(morris==numberTrios[1]){
if(!aux.equals(blackTriosPositions) && !undo){
isExcludeMode = true;
noPiecesRemovedCount = -1;
excludeProperty.set("Pretas podem remover uma peça preta já que fizeram um moinho");
return true;
}
}
}
}
return false;
}
public void changeTurn(){
turn = !turn;
if(turn)
turnProperty.set("Turno: Brancas jogam");
if(!turn)
turnProperty.set("Turno: Pretas jogam. Aperte o botão Joga IA, por favor");
incrementNumberOfTurns();
incrementNoPieceRemovedCount();
turnsProperty.set("Rodadas sem remoção de peças: " + noPiecesRemovedCount);
}
public boolean isOver(boolean isStuck){
System.out.println("Alguém foi travado: "+isStuck);
if(!isBlackPhase3 && turn && isStuck){
winProperty.set("Parabéns!! Você faz parte de um hall seleto de pessoas. Você travou a nossa IA, ela não tem mais jogadas a fazer.");
return true;
}
if(!isWhitePhase3 && !turn && isStuck){
winProperty.set("Nossa IA ganhou!!! Wohooooooo. Você foi travado. Não possui mais jogadas");
return true;
}
if(whitePieces.size() <= 2){
winProperty.set("Nossa IA ganhou!!! Wohooooooo. Você só possui 2 peças.");
return true;
}
if(blackPieces.size()<=2){
winProperty.set("Parabéns!! Você faz parte de um hall seleto de pessoas. Você fez com que nossa IA ficasse com 2 peças.");
return true;
}
if(noPiecesRemovedCount >= 35){
winProperty.set("Ocorreu um empate entre o player e a IA. Ocorreram 35 jogadas sem a remoção de uma peça.");
return true;
}
if(whitePieces.size()==3 && numberOfTurns > 18){
isWhitePhase3 = true;
return false;
}
if(blackPieces.size()==3 && numberOfTurns > 18){
isBlackPhase3 = true;
return false;
}
return false;
}
public void restart(){
gameMatrix = new int[24];
for (int i = 0; i < 24; i++) gameMatrix[i] = Board.EMPTY;
noPiecesRemovedCount = 0;
whitePieces.clear();
blackPieces.clear();
turn = true;
turnProperty = new SimpleStringProperty("Turno: Brancas jogam");
isExcludeMode = false;
turnsProperty.set("Rodadas sem remoção de peças: " + noPiecesRemovedCount);
numberOfTurns = 0;
isBlackPhase3 = isWhitePhase3 = false;
numberTrios[0] = numberTrios[1] = 0;
whiteTriosPositions.clear();
blackTriosPositions.clear();
excludeProperty.set("A IA é muito forte! Cuidado...");
winProperty.set("Quem será que irá ganhar? ");
}
@Override
public String toString(){
char[] s = new char[24];
for (int i = 0; i < 24; i++){
s[i] = (char)('0' + gameMatrix[i]);
}
return "" +
" "+s[ 0]+" --------- "+s[ 1]+" --------- "+s[ 2] + " 0 --------- 1 --------- 2"+ "\n" +
" | | |" + " | | |"+ "\n" +
" | "+s[ 3]+" ----- " +s[ 4]+" ----- " +s[ 5]+" |" + " | 3 ----- 4 ----- 5 |"+ "\n" +
" | | | | |" + " | | | | |"+ "\n" +
" | | "+s[ 6]+" - "+s[ 7]+" - "+s[ 8]+" | |" + " | | 6 - 7 - 8 | |"+ "\n" +
" | | | | | |" + " | | | | | |"+ "\n" +
" "+s[ 9]+" - "+s[10]+" - "+s[11]+" "+s[12]+" - "+s[13]+" - "+s[14] + " 9 - 10- 11 12- 13- 14"+ "\n" +
" | | | | | |" + " | | | | | |"+ "\n" +
" | | "+s[15]+" - "+s[16]+" - "+s[17]+" | |" + " | | 15- 16- 17 | |"+ "\n" +
" | | | | |" + " | | | | |"+ "\n" +
" | "+s[18]+" ----- "+s[19]+" ----- "+s[20]+" |" + " | 18----- 19----- 20 |"+ "\n" +
" | | |" + " | | |"+ "\n" +
" "+s[21]+" --------- "+s[22]+" --------- "+s[23] + " 21--------- 22--------- 23" ;
}
}
|
package kr.co.jboard2.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.co.jboard2.dao.ArticleDao;
import kr.co.jboard2.vo.ArticleVO;
public class CommentService implements CommonService {
@Override
public String requestProc(HttpServletRequest req, HttpServletResponse resp) {
String parent = req.getParameter("parent");
String uid = req.getParameter("uid");
String comment = req.getParameter("comment");
String regip = req.getRemoteAddr();
ArticleVO articleVo = new ArticleVO();
articleVo.setParent(parent);
articleVo.setContent(comment);
articleVo.setUid(uid);
articleVo.setRegip(regip);
ArticleDao dao = ArticleDao.getInstance();
dao.insertComment(articleVo);
// ´ñ±Û Ä«¿îÆ® +1
dao.updateCommentCount(parent, +1);
return "redirect:/Jboard2/view.do?seq="+parent;
}
}
|
execute(des,src,registers,memory) {
int desBitSize = registers.getBitSize(des);
int desHexSize = registers.getHexSize(des);
String desValue = registers.get(des);
String srcValue;
Calculator calculator = new Calculator(registers,memory);
if (src.isRegister()) {
srcValue = registers.get(src);
} else if (src.isMemory()) {
srcValue = memory.read(src,desBitSize);
}
if (desBitSize == 64 || desBitSize == 128) {
// g == greater than
String result = calculator.cutBySizeAndCompare(desValue, srcValue, desHexSize, 2, 'g');
registers.set(des, result);
}
}
|
/**
* Engine / Window
*/
package edu.self.engine;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* Window Class
*/
public class Window implements FocusListener {
/**
* Components
*/
private Engine engine;
private Debug debug;
private JFrame frame;
private JPanel panel;
/**
* Constructor
*/
public Window(Engine engine) {
this.engine = engine;
debug = new Debug(this.engine, this);
this.engine.config().defer("window.title", "Engine");
frame = null;
panel = null;
}
/**
* Accessors and Modifiers
*/
// Window Components
public JFrame frame() {
return frame;
}
public JPanel panel() {
return panel;
}
// Input and Actions Map
public InputMap inputs() {
return panel.getInputMap();
}
public ActionMap actions() {
return panel.getActionMap();
}
/**
* Controls
*/
// Invocation
public void start() {
frame = new JFrame(engine.config().get("window.title"));
panel = new JPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setEnabled(true);
panel.setFocusable(true);
panel.addFocusListener(this);
}
// Cleanup
public void stop() {
frame.setVisible(false);
frame.remove(panel);
frame.dispose();
}
/**
* FocusListener Interface
*/
public void focusGained(FocusEvent event) {
debug.info("Window focused");
}
public void focusLost(FocusEvent event) {
debug.info("Window blurred");
}
}
|
package xframe.example.pattern.proxy.dynamic;
public interface Subject {
public void run();
public void doOther();
}
|
package chatroom.model.message;
public class LoginMessage extends Message {
private String loginName;
private String password;
public LoginMessage(String loginName, String password){
type = 3;
this.loginName = loginName;
this.password = password;
}
public String getLoginName() {
return loginName;
}
public String getPassword() {
return password;
}
}
|
package org.xtext.example.mydsl.tests.kmmv;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.testing.InjectWith;
import org.eclipse.xtext.testing.extensions.InjectionExtension;
import org.eclipse.xtext.testing.util.ParseHelper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.xtext.example.mydsl.mml.MMLModel;
import org.xtext.example.mydsl.tests.MmlInjectorProvider;
import com.google.inject.Inject;
@ExtendWith(InjectionExtension.class)
@InjectWith(MmlInjectorProvider.class)
public class MmlParsingKMMVTest {
@Inject
ParseHelper<MMLModel> parseHelper;
@Test
public void loadModel() throws Exception {
MMLModel result = parseHelper.parse("datainput \"foo.csv\"\n"
+ "mlframework scikit-learn\n"
+ "algorithm DT\n"
+ "TrainingTest { percentageTraining 70 }\n"
+ "mean_absolute_error\n"
+ "");
Assertions.assertNotNull(result);
EList<Resource.Diagnostic> errors = result.eResource().getErrors();
Assertions.assertTrue(errors.isEmpty(), "Unexpected errors");
Assertions.assertEquals("foo.csv", result.getInput().getFilelocation());
}
@Test
public void loadThreeAlgos() throws Exception {
MMLModel result = parseHelper.parse("datainput \"boston.csv\"\n"
+ "mlframework scikit-learn\n"
+ "algorithm DT\n"
+ "mlframework scikit-learn\n"
+ "algorithm RF\n"
+ "mlframework scikit-learn\n"
+ "algorithm GradientBoostingRegressor\n"
+ "CrossValidation { numRepetitionCross 5 }\n"
+ "mean_absolute_percentage_error\n"
+ "");
Assertions.assertNotNull(result);
EList<Resource.Diagnostic> errors = result.eResource().getErrors();
Assertions.assertTrue(errors.isEmpty(), "Unexpected errors");
Assertions.assertEquals("boston.csv", result.getInput().getFilelocation());
}
@Test
public void loadMultiThreeAlgos() throws Exception {
MMLModel result = parseHelper.parse("datainput \"boston.csv\"\n"
+ "mlframework R\n"
+ "algorithm DT\n"
+ "mlframework R\n"
+ "algorithm RF\n"
+ "mlframework scikit-learn\n"
+ "algorithm GradientBoostingRegressor\n"
+ "CrossValidation { numRepetitionCross 5 }\n"
+ "mean_absolute_percentage_error\n"
+ "");
Assertions.assertNotNull(result);
EList<Resource.Diagnostic> errors = result.eResource().getErrors();
Assertions.assertTrue(errors.isEmpty(), "Unexpected errors");
Assertions.assertEquals("boston.csv", result.getInput().getFilelocation());
}
@Test
public void compileTests() throws Exception {
File folder = new File("");
for(int i = 1; i <= 12; ++i) {
try {
String data = new String(Files.readAllBytes(Paths.get(folder.getAbsoluteFile()+"/prg"+Integer.toString(i)+".mml")));
MMLModel model = parseHelper.parse(data);
List<String> commandLines = MmlCompiler.compile(model);
for(String command : commandLines) {
System.out.println(command);
String[] exec = {"bash", "-c", command};
Process p = Runtime.getRuntime().exec(exec);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
System.err.println(e.getCause());
}
System.out.println("");
}
}
}
|
package com.longlysmile.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.longlysmile.entity.AttackRecord;
import java.util.List;
import java.util.Map;
/**
* 攻击记录接口
* @author wujie
*/
public interface AttackRecordMapper extends BaseMapper<AttackRecord> {
List<Map<String,String>> statistics();
}
|
package com.gmail.merikbest2015.ecommerce.service.Impl;
import com.gmail.merikbest2015.ecommerce.domain.Perfume;
import com.gmail.merikbest2015.ecommerce.repos.PerfumeRepository;
import com.gmail.merikbest2015.ecommerce.service.PerfumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
/**
* The service layer class implements the accessor methods of {@link Perfume} objects
* in the {@link PerfumeService} interface database.
* The class is marked with the @Service annotation - an annotation announcing that this class
* is a service - a component of the service layer. Service is a subtype of @Component class.
* Using this annotation will automatically search for service beans.
*
* @author Miroslav Khotinskiy (merikbest2015@gmail.com)
* @version 1.0
* @see Perfume
* @see PerfumeService
* @see PerfumeRepository
*/
@Service
public class PerfumeServiceImpl implements PerfumeService {
/**
* Implementation of the {@link PerfumeRepository} interface
* for working with perfumes with a database.
*/
private final PerfumeRepository perfumeRepository;
/**
* Constructor for initializing the main variables of the order service.
* The @Autowired annotation will allow Spring to automatically initialize objects.
*
* @param perfumeRepository implementation of the {@link PerfumeRepository} interface
* for working with perfumes with a database.
*/
@Autowired
public PerfumeServiceImpl(PerfumeRepository perfumeRepository) {
this.perfumeRepository = perfumeRepository;
}
/**
* Return list of all perfumes.
*
* @return list of {@link Perfume}.
*/
@Override
public List<Perfume> findAll() {
return perfumeRepository.findAll();
}
/**
* Returns list of perfumes.
* A {@link Page} is a sublist of a list of objects.
*
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findAll(Pageable pageable) {
return perfumeRepository.findAll(pageable);
}
/**
* Returns list of perfumes in which the price is in the range between of starting price and ending price.
* A {@link Page} is a sublist of a list of objects.
*
* @param startingPrice The starting price of the product that the user enters.
* @param endingPrice The ending price of the product that the user enters.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPriceBetween(Integer startingPrice, Integer endingPrice, Pageable pageable) {
return perfumeRepository.findByPriceBetween(startingPrice, endingPrice, pageable);
}
/**
* Returns list of perfumes which has the same perfume manufacturer with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumer perfume manufacturer to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumer(String perfumer, Pageable pageable) {
return perfumeRepository.findByPerfumer(perfumer, pageable);
}
/**
* Returns list of perfumes which has the same gender with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumeGender perfume gender to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumeGender(String perfumeGender, Pageable pageable) {
return perfumeRepository.findByPerfumeGender(perfumeGender, pageable);
}
/**
* Returns list of perfumes which has the same genders with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumeGenders perfume genders to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumeGenderIn(List<String> perfumeGenders, Pageable pageable) {
return perfumeRepository.findByPerfumeGenderIn(perfumeGenders, pageable);
}
/**
* Returns list of perfumes which has the same perfume manufacturer or perfume title
* with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumer perfume manufacturer to return.
* @param perfumeTitle perfume title to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumerOrPerfumeTitle(String perfumer, String perfumeTitle, Pageable pageable) {
return perfumeRepository.findByPerfumerOrPerfumeTitle(perfumer, perfumeTitle, pageable);
}
/**
* Returns list of perfumes which has the same perfume manufacturers and genders
* with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumers perfume manufacturers to return.
* @param genders genders to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumerInAndPerfumeGenderIn(List<String> perfumers, List<String> genders, Pageable pageable) {
return perfumeRepository.findByPerfumerInAndPerfumeGenderIn(perfumers, genders, pageable);
}
/**
* Returns list of perfumes which has the same perfume manufacturers and genders
* with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumers perfume manufacturers to return.
* @param genders genders to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumerInOrPerfumeGenderIn(List<String> perfumers, List<String> genders, Pageable pageable) {
return perfumeRepository.findByPerfumerInOrPerfumeGenderIn(perfumers, genders, pageable);
}
/**
* Returns list of perfumes which has the same perfume manufacturers
* with the value of the input parameter.
* A {@link Page} is a sublist of a list of objects.
*
* @param perfumers perfume manufacturers to return.
* @param pageable object that specifies the information of the requested page.
* @return list of {@link Perfume}.
*/
@Override
public Page<Perfume> findByPerfumerIn(List<String> perfumers, Pageable pageable) {
return perfumeRepository.findByPerfumerIn(perfumers, pageable);
}
/**
* Returns minimum price of perfume.
*
* @return minimum price {@link Perfume}.
*/
@Override
public BigDecimal minPerfumePrice() {
return perfumeRepository.minPerfumePrice();
}
/**
* Returns maximum price of perfume from the database.
*
* @return maximum price {@link Perfume}.
*/
@Override
public BigDecimal maxPerfumePrice() {
return perfumeRepository.maxPerfumePrice();
}
/**
* Save updated perfume.
*
* @param perfumeTitle perfume title to update.
* @param perfumer perfume manufacturer to update.
* @param year the year the perfume was released to update.
* @param country manufacturer country to update.
* @param perfumeGender gender to update to update.
* @param fragranceTopNotes fragrance top notes to update.
* @param fragranceMiddleNotes fragrance middle notes to update.
* @param fragranceBaseNotes fragrance base notes to update.
* @param description perfume description to update.
* @param filename perfume image to update.
* @param price perfume price to update.
* @param volume perfume volume to update.
* @param type type of fragrance to update.
* @param id the unique code of the perfume to update.
*/
@Override
public void saveProductInfoById(String perfumeTitle, String perfumer, Integer year, String country,
String perfumeGender, String fragranceTopNotes, String fragranceMiddleNotes,
String fragranceBaseNotes, String description, String filename,
Integer price, String volume, String type, Long id
) {
perfumeRepository.saveProductInfoById(perfumeTitle, perfumer, year, country, perfumeGender, fragranceTopNotes,
fragranceMiddleNotes, fragranceBaseNotes, description, filename, price, volume, type, id);
}
/**
* Save perfume info.
*
* @param perfume perfume object to return.
* @return The {@link Perfume} class object which will be saved in the database.
*/
@Override
public Perfume save(Perfume perfume) {
return perfumeRepository.save(perfume);
}
}
|
package com.cg.eis.service;
import java.util.*;
import com.cg.eis.bean.*;
public class Service implements EmployeeService{
Scanner sc=new Scanner(System.in);
Employee e=new Employee();
public void getEmployDetails() {
System.out.println("Enter Details:");
System.out.println("Enter id:");e.setId(sc.nextInt());
System.out.println("Enter salary:");e.setSalary(sc.nextInt());
System.out.println("Enter Designation:");e.setDesignation(sc.next());
System.out.println("Enter Name:");e.setName(sc.next());
}
public void InsType() {
System.out.println("=======Insurance Scheme for Employee=======");
if(e.getSalary()<10000)
e.setinsuranceScheme("Tier 1");
else
e.setinsuranceScheme("Tier 2");
System.out.println(e.getinsuranceScheme());
}
public void Display() {
System.out.println("=====Details======");
System.out.println("Name: "+e.getName());
System.out.println("Id: "+e.getId());
System.out.println("Salary: "+e.getSalary());
System.out.println("Desig: "+e.getDesignation());
System.out.println("INsSch: "+e.getinsuranceScheme());
}
}
|
/**
*
*/
package com.cnk.travelogix.common.facades.product.sort.impl;
import com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider;
/**
* @author i313879
*
*/
public class SortedToModelEntry
{
private String code;
private String name;
private boolean isDesc;
private CnkFacetValueProvider sortedValueProvider;
/**
* @return the code
*/
public String getCode()
{
return code;
}
/**
* @param code
* the code to set
*/
public void setCode(final String code)
{
this.code = code;
}
/**
* @return the name
*/
public String getName()
{
return name;
}
/**
* @param name
* the name to set
*/
public void setName(final String name)
{
this.name = name;
}
/**
* @return the isDesc
*/
public boolean isDesc()
{
return isDesc;
}
/**
* @param isDesc
* the isDesc to set
*/
public void setDesc(final boolean isDesc)
{
this.isDesc = isDesc;
}
/**
* @return the sortedValueProvider
*/
public CnkFacetValueProvider getSortedValueProvider()
{
return sortedValueProvider;
}
/**
* @param sortedValueProvider
* the sortedValueProvider to set
*/
public void setSortedValueProvider(final CnkFacetValueProvider sortedValueProvider)
{
this.sortedValueProvider = sortedValueProvider;
}
}
|
package com.example.mjunior.fiapimoveis;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import com.example.mjunior.fiapimoveis.dao.ImovelDAO;
import com.example.mjunior.fiapimoveis.modelo.Imovel;
public class FormActivity extends AppCompatActivity {
private FormularioHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
helper = new FormularioHelper(this);
Intent intent = getIntent();
Imovel imovel = (Imovel) intent.getSerializableExtra("imovel");
if (imovel != null){
helper.preencheFormulario(imovel);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_formulario, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_formulario_ok:
Imovel imovel = helper.pegaImovel();
ImovelDAO imovelDAO = new ImovelDAO(this);
if(imovel.getId() != null){
imovelDAO.altera(imovel);
}else{
imovelDAO.insere(imovel);
}
imovelDAO.close();
Toast.makeText(FormActivity.this, "Imóvel salvo!", Toast.LENGTH_SHORT).show();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.gustavoaz7.whatsapp.helper;
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
public class Preferences {
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private final String FILE_NAME = "WHATSAPP_PREFERENCES";
private int MODE = 0;
private String NAME = "name";
private String PHONE = "phone";
private String TOKEN = "token";
public Preferences(Context contextParam) {
context = contextParam;
preferences = context.getSharedPreferences(FILE_NAME, MODE);
editor = preferences.edit();
}
public void saveUserPreferences(String name, String phone, String token) {
editor.putString(NAME, name);
editor.putString(PHONE, phone);
editor.putString(TOKEN, token);
editor.commit();
}
public HashMap<String, String> getUserPreferences() {
HashMap<String, String> userPreferences = new HashMap<>();
userPreferences.put(NAME, preferences.getString(NAME, null));
userPreferences.put(PHONE, preferences.getString(PHONE, null));
userPreferences.put(TOKEN, preferences.getString(TOKEN, null));
return userPreferences;
}
}
|
package banking;
import org.sqlite.SQLiteDataSource;
import java.sql.*;
import java.util.Scanner;
public class BankSystem {
private static BankCard[] accounts = new BankCard[1000];
static Scanner scanner = new Scanner(System.in);
public static int amount;
public static int currentCard;
public static int currentTransfer;
protected static String dbURL;
protected static SQLiteDataSource dataSource= new SQLiteDataSource();
public BankSystem(String dbName) {
amount = 0;
this.dbURL = "jdbc:sqlite:" + dbName;
dataSource.setUrl(dbURL);
synchronizeDBWithBank();
createDataBase();
}
public static void synchronizeDBWithBank() {
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (Statement statement = con.createStatement()){
try (ResultSet cardTable = statement.executeQuery("SELECT * FROM card")) {
while (cardTable.next()) {
// Retrieve column values
int id = cardTable.getInt("id");
String number = cardTable.getString("number");
String pin = cardTable.getString("pin");
int ballance = cardTable.getInt("balance");
while (pin.length() != 4) {
pin = "0" + pin;
}
//System.out.println("Adding card to array with (" + number + "," + pin+ ", " + ballance + ")");
createNewCardWithParameters(number, pin,ballance);
/*System.out.println("Amount = " + amount);
showCard(amount);*/
//getArr();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void showCard(int i) {
System.out.println(accounts[i - 1].toString());
}
public static void createNewCardWithParameters(String number, String pin, int ballance) {
accounts[amount] = new BankCard(number, pin, ballance);
amount++;
//System.out.println("Amount" + amount);
}
public static void createNewCard() {
accounts[amount] = new BankCard();
addToDB(accounts[amount]);
System.out.print("Your card has been created\n" + accounts[amount].toString());
amount++;
//System.out.println("Amount" + amount);
}
public static void showMenuForLogged() {
System.out.println("1. Balance");
System.out.println("2. Add income");
System.out.println("3. Do transfer");
System.out.println("4. Close account");
System.out.println("5. Log out");
System.out.println("0. Exit");
}
//Log in bankSystem
public static void logIn() {
System.out.println("Enter your card number:");
String cardNumber = scanner.nextLine();
System.out.println("Enter your PIN:");
String PIN = scanner.nextLine();
if (checkCards(cardNumber, PIN)) {
System.out.println("You have successfully logged in!");
showMenuForLogged();
int choice = Integer.parseInt(scanner.nextLine());
while (true) {
switch (choice) {
case 1:
System.out.println("Ballance: " + accounts[currentCard].getBallance());
break;
case 2:
addIncome();
break;
case 3:
System.out.println("Transfer");
System.out.println("Enter card number:");
String userInput = scanner.nextLine();
while (userInput.isEmpty()) {
userInput = scanner.nextLine();
}
doTransfer(userInput);
break;
case 4:
closeAccount();
return;
case 5:
System.out.println("You have successfully logged out!");
return;
case 0:
getDB();
//getArr();
System.out.println("Bye");
System.exit(0);
default:
break;
}
showMenuForLogged();
choice = Integer.parseInt(scanner.nextLine());
}
} else {
System.out.println("Wrong card number or PIN!");
}
}
protected static void addIncome() {
System.out.println("Enter income:");
int additionIncome = Integer.parseInt(scanner.nextLine());
accounts[currentCard].addIncome(additionIncome);
addIncomeToDB(additionIncome);
System.out.println("Income was added!");
}
protected static void doTransfer(String transferCard) {
if (transferCard.length() != 16) {
System.out.println("Not enought symb");
return;
}
char[] transArr = transferCard.toCharArray();
String first15 = charArrToString(transArr);
char lastChar = transArr[transArr.length - 1];
//Luch alg
if (accounts[currentCard].luchAlgoritm(first15) != lastChar) {
System.out.println("Probably you made a mistake in the card number. Please try again!");
return;
}
if (transferCard.equals(accounts[currentCard].getCardNumber())) {
System.out.println("You can't transfer money to the same account!");
return;
}
if (!checkCardsTransfer(transferCard)) {
System.out.println("Such a card does not exist.");
return;
} else {
System.out.println("Enter how much money you want to transfer:");
int trasferMoney = Integer.parseInt(scanner.nextLine());
if (accounts[currentCard].getBallance() < trasferMoney) {
System.out.println("Not enough money!");
return;
}
accounts[currentCard].addIncome(-trasferMoney);
accounts[currentTransfer].addIncome(trasferMoney);
transInDB(trasferMoney);
}
}
public static String charArrToString(char[] arr) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < arr.length - 1; i++) {
str.append(arr[i]);
}
return str.toString();
}
//checking card
protected static boolean checkCards(String cardNumber, String PIN) {
int cur = 0;
for (int i = 0; i < amount; i++) {
if (accounts[i].checkCardNumber(cardNumber) && accounts[i].checkCardPassword(PIN)) {
currentCard = i;
return true;
}
}
return false;
}
//checking card
protected static boolean checkCardsTransfer(String cardNumber) {
int cur = 0;
for (int i = 0; i < amount; i++) {
if (accounts[i].checkCardNumber(cardNumber)) {
currentTransfer = i;
return true;
}
}
return false;
}
//Creating table card in DB
public static void createDataBase() {
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (Statement statement = con.createStatement()){
// Statement execution
statement.executeUpdate("CREATE TABLE IF NOT EXISTS card (" +
"id INTEGER PRIMARY KEY," +
"number TEXT NOT NULL," +
"pin TEXT NOT NULL," +
"balance INTEGER DEFAULT 0)");
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//Adding the card to DB
public static void addToDB(BankCard card) {
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (Statement statement = con.createStatement()) {
// Statement execution
int i = statement.executeUpdate("INSERT INTO card (number, pin, balance) VALUES " + card.stringForDB());
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void getArr() {
for (int i = 0; i < accounts.length; i++) {
if (accounts[i] != null) {
System.out.println(accounts[i].toString());
}
}
}
//Show DB content
public static void getDB() {
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (Statement statement = con.createStatement()){
try (ResultSet cardTable = statement.executeQuery("SELECT * FROM card")) {
while (cardTable.next()) {
// Retrieve column values
int id = cardTable.getInt("id");
String number = cardTable.getString("number");
String pin = cardTable.getString("pin");
int balance = cardTable.getInt("balance");
while (pin.length() != 4) {
pin = "0" + pin;
}
System.out.printf("id %d%n", id);
System.out.printf("number: %s%n", number);
System.out.printf("pin: %s%n", pin);
System.out.printf("balance: %s%n", balance);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//edit balance card
protected static void addIncomeToDB(int additionalIncome) {
String updateOrigin = "UPDATE card SET balance = balance + ? WHERE id = ?";
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (PreparedStatement preparedStatement = con.prepareStatement(updateOrigin)) {
preparedStatement.setInt(1, additionalIncome);
preparedStatement.setInt(2, currentCard + 1);
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//delete account from DB
protected static void closeAccount() {
String updateOrigin = "DELETE FROM card WHERE number = ?";
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (PreparedStatement preparedStatement = con.prepareStatement(updateOrigin)) {
preparedStatement.setString(1, accounts[currentCard].getCardNumber());
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("The account has been closed!");
}
//delete account from DB
protected static void deleteDB() {
String updateOrigin = "DELETE FROM card";
try (Connection con = DriverManager.getConnection(dbURL)) {
// Statement creation
try (PreparedStatement preparedStatement = con.prepareStatement(updateOrigin)) {
preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("The account has been closed!");
}
protected static void transInDB(int sum) {
String updateOrigin = "UPDATE card SET balance = balance - ? WHERE id = ?";
String updateTransfer = "UPDATE card SET balance = balance + ? WHERE id = ?";
try (Connection con = DriverManager.getConnection(dbURL)) {
// Disable auto-commit mode
con.setAutoCommit(false);
try {
PreparedStatement originStatement = con.prepareStatement(updateOrigin);
PreparedStatement transferStatement = con.prepareStatement(updateTransfer);
originStatement.setInt(1, sum);
originStatement.setInt(2, currentCard + 1);
originStatement.executeUpdate();
transferStatement.setInt(1, sum);
transferStatement.setInt(2, currentTransfer + 1);
transferStatement.executeUpdate();
con.commit();
con.setAutoCommit(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package exceptions;
/**
* thrown when the selected cell is not movable<br>
*
* <hr>
* Date created: Jun 6, 2010<br>
* Date last modified: Jun 6, 2010<br>
* <hr>
* @author Glen Watson
*/
public class SelectedCellCantMoveException extends CellException
{
private static final long serialVersionUID = 1L;
public static final String MESSAGE = "That cell can not move";
/**
* constructor <br>
*
* <hr>
* Date created: Jun 6, 2010 <br>
* Date last modified: Jun 6, 2010 <br>
*
* <hr>
* @param cellX - the x-coord of the selected cell
* @param cellY - the y-coord of the selected cell
*/
public SelectedCellCantMoveException(int cellX, int cellY)
{
super(cellX, cellY, MESSAGE);
}
/**
* default constructor <br>
*
* <hr>
* Date created: Jun 6, 2010 <br>
* Date last modified: Jun 6, 2010 <br>
*
* <hr>
*/
public SelectedCellCantMoveException()
{
super(MESSAGE);
}
}
|
package com.cybx.salesorder.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.cybx.salesorder.dao.SalesorderDao;
import com.cybx.salesorder.model.Salesorder;
import com.cybx.system.bean.BeanPropertyUtilsExtend;
@Repository(value = "salesorderDao")
public class SalesorderDaoImpl implements SalesorderDao {
private final static String NAMESPACE = "com.cybx.salesorder.model.Salesorder.";
@Resource
private SqlSession sqlSession = null;
@Override
public int insert(Salesorder order) {
Map<String, Object> params = new HashMap<String, Object>();
Map<String, Object> orderMap = BeanPropertyUtilsExtend.describe(order); // 去除空的属性,返回map
params.put("order", orderMap); // 传入的参数类型需为HashMap
return sqlSession.insert(NAMESPACE + "insert", params);
}
@Override
public List<Salesorder> getSalesorder(String status) {
return sqlSession.selectList(NAMESPACE + "getSalesorder", status);
}
}
|
package cdn.shared.message.types;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import cdn.shared.message.IMessage;
public class DeregisterResponseMessage implements IMessage {
public StatusCode status;
public String additionalInfo;
public DeregisterResponseMessage(byte[] bytes) {
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
try {
DataInputStream s = new DataInputStream(stream);
status = StatusCode.fromOrdinal(s.readInt());
additionalInfo = s.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public DeregisterResponseMessage(StatusCode status, String additionalInfo) {
this.status = status;
this.additionalInfo = additionalInfo;
}
@Override
public MessageType getType() {
return MessageType.DEREGISTER_RESPONSE;
}
@Override
public byte[] getWireFormat() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
DataOutputStream s = new DataOutputStream(stream);
s.writeInt(getType().ordinal());
s.writeInt(status.ordinal());
s.writeUTF(additionalInfo);
s.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream.toByteArray();
}
}
|
package com.alteredtastes;
import graphql.ExecutionResult;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.StaticDataFetcher;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import static graphql.schema.idl.RuntimeWiring.newRuntimeWiring;
@Path("/graphql")
public class GraphQLService {
@POST
@Path("/")
public Response GraphQLService(@Context Request request) {
String schema = "type Query{hello: String}";
SchemaParser schemaParser = new SchemaParser();
TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse("schema.graphqls");
RuntimeWiring runtimeWiring = newRuntimeWiring()
.type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world")))
.build();
SchemaGenerator schemaGenerator = new SchemaGenerator();
GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
ExecutionResult executionResult = build.execute("{hello}");
System.out.println(executionResult.getData().toString());
return Response.ok()
.entity(executionResult.getData().toString())
.build();
// Prints: {hello=world}
}
}
|
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FibonacciController {
@Autowired
private FibonacciService fibonacciService;
@RequestMapping("/fibonnaci/{n}")
public ResponseEntity<?> calFibonacci(@PathVariable int n) {
if (n < 0) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("invalid interger" + n);
}
int[] fib = fibonacciService.fibonacci(n);
return new ResponseEntity<int[]>(fib, HttpStatus.OK);
}
}
|
package uk.co.mobsoc.MobsGames;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.block.ContainerBlock;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.InventoryHolder;
import uk.co.mobsoc.MobsGames.Data.BlockData;
import uk.co.mobsoc.MobsGames.Game.AbstractGame;
/**
* This Class is responsible for logging all Game related block and inventory changes, so that games may revert the arena afterwards
* @author triggerhapp
*
*/
public class RevertingListener implements Listener {
/**
* Adds broken blocks to the list of blocks that return to initial state
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onBlockBreak(BlockBreakEvent event){
if(event.isCancelled()){ return; }
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant(event.getPlayer())){
BlockData bd = new BlockData(event.getBlock());
MobsGames.getGame().addRevert(bd);
}
}
/**
* Adds Placed blocks to the list of blocks that return to initial state
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onPlacePlace(BlockPlaceEvent event){
if(event.isCancelled()){ return; }
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant(event.getPlayer())){
BlockData bd = new BlockData(event.getBlock());
bd.data = event.getBlockReplacedState().getRawData();
bd.id = event.getBlockReplacedState().getTypeId();
MobsGames.getGame().addRevert(bd);
}
}
/**
* Add Exploded blocks to the list of blocks that return to initial state.
* This might be a bit buggy, since it does not check (Because it is not logically possible) if the explosion is related to the game or not.
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onExplosion(EntityExplodeEvent event){
AbstractGame game = MobsGames.getGame();
if(game!=null){
for(Block block : event.blockList()){
game.addRevert(new BlockData(block));
}
}
}
/**
* Add Liquid that flows into the list of blocks that return to initial state.
* This might be a bit buggy, since it does not check (due to excessive CPU usage) if the liquid is related to the game or not.
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onLiquidFlow(BlockFromToEvent event){
AbstractGame game = MobsGames.getGame();
if(game!=null){
game.addRevert(new BlockData(event.getToBlock()));
}
}
/**
* Add Liquid that is taken to the list of blocks to return to initial state
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onBucketFill(PlayerBucketFillEvent event){
if(event.isCancelled()){ return; }
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant(event.getPlayer())){
BlockData bd = new BlockData(event.getBlockClicked().getRelative(event.getBlockFace()));
game.addRevert(bd);
}
}
/**
* Add Liquid that is placed to the list of blocks to return to initial state
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onBucketEmpty(PlayerBucketEmptyEvent event){
if(event.isCancelled()){ return; }
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant(event.getPlayer())){
BlockData bd = new BlockData(event.getBlockClicked().getRelative(event.getBlockFace()));
game.addRevert(bd);
}
}
/**
* Add Levers to the list of blocks to return to initial state
* @param event
*/
@EventHandler(priority=EventPriority.MONITOR)
public void onInteractBlock(PlayerInteractEvent event){
if(event.isCancelled()){ return; }
if(event.hasBlock()){
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant(event.getPlayer())){
if(event.getClickedBlock().getType() == Material.LEVER){
BlockData bd = new BlockData(event.getClickedBlock());
game.addRevert(bd);
}
}
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority=EventPriority.MONITOR)
public void onInventoryOpen(InventoryOpenEvent event){
if(event.isCancelled()){ return; }
AbstractGame game = MobsGames.getGame();
if(game==null){ return; }
if(game.isParticipant((Player) event.getPlayer())){
InventoryHolder iH = event.getInventory().getHolder();
// To Hell with depreciating a perfectly good class.
if(iH instanceof ContainerBlock){
game.addRevert(iH);
}
}
}
}
|
/**
* Created by likz on 2023/2/20
*
* @author likz
*/
public class Knapsack {
public static int maxValue(int[] w, int[] v, int bag){
if(w == null || v == null || w.length != v.length || w.length < 1){
return 0;
}
return process(w, v, 0, bag);
}
private static int process(int[] w, int[] v, int index, int rest) {
if (rest < 0){
return -1;
}
if (index == w.length){
return 0;
}
int p1 = process(w, v, index + 1, rest);
int p2 = 0;
int next = process(w, v, index + 1, rest - w[index]);
if (next != -1){
p2 += v[index] + next;
}
return Math.max(p1, p2);
}
private static int dp(int[] w, int[] v, int bag) {
if(w == null || v == null || w.length != v.length || w.length < 1){
return 0;
}
int N = w.length;
int[][] dp = new int[N + 1][bag + 1];
for(int index = N - 1; index >= 0; index--){
for (int rest = 0; rest <= bag; rest++){
int p1 = dp[index + 1][rest];
int p2 = 0;
int next = rest - w[index] < 0 ? -1 : dp[index + 1][rest - w[index]];
if (next != -1) {
p2 = v[index] + next;
}
dp[index][rest] = Math.max(p1, p2);
}
}
return dp[0][bag];
}
private static int maxValue2(int[] w, int[] v, int bag) {
if(w == null || v == null || w.length != v.length || w.length < 1){
return 0;
}
int n = w.length;
int[][] dp = new int[n + 1][bag + 1];
for(int index = n - 1; index >= 0; index--) {
for (int rest = bag; rest >= 0; rest--){
int p1 = dp[index+1][rest];
int p2 = rest - w[index] < 0 ? -1 : dp[index + 1][rest - w[index]] + v[index];
dp[index][rest] = Math.max(p1, p2);
}
}
return dp[0][bag];
}
public static void main(String[] args) {
int[] weights = { 3, 2, 4, 7, 3, 1, 7 };
int[] values = { 5, 6, 3, 19, 12, 4, 2 };
int bag = 15;
System.out.println(maxValue(weights, values, bag));
System.out.println(maxValue2(weights, values, bag));
System.out.println(dp(weights, values, bag));
}
}
|
package com.bdb.conexion;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class Connect {
public Connect() {
con = null;
}
private String getConnectionUrl() {
return "jdbc:jtds:sqlserver://RRHH/nexus_prue";
}
public Connection getConnection() {
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection(getConnectionUrl(), "sa", "euli3755");
if(con != null)
System.out.println("Connection Successful!");
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}
public void displayDbProperties() {
DatabaseMetaData dm = null;
ResultSet rs = null;
try {
con = getConnection();
if(con != null) {
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: " + dm.getDriverName());
System.out.println("\tDriver Version: " + dm.getDriverVersion());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: " + dm.getDatabaseProductName());
System.out.println("\tDatabase Version: " + dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
for(rs = dm.getCatalogs(); rs.next(); System.out.println("\tcatalog: " + rs.getString(1)));
rs.close();
rs = null;
closeConnection();
} else {
System.out.println("Error: No active Connection");
}
}
catch(Exception e) {
e.printStackTrace();
}
dm = null;
}
private void closeConnection() {
try {
if(con != null)
con.close();
con = null;
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
Connect myDbTest = new Connect();
myDbTest.displayDbProperties();
}
private Connection con;
// private final String driver = "net.sourceforge.jtds.jdbc.Driver";
// private final String url = "jdbc:jtds:sqlserver://";
// private final String serverName = "localhost/";
// private final String portNumber = "1433";
// private final String databaseName = "slort";
// private final String userName = "slort";
// private final String password = "secret";
// private final String selectMethod = "cursor";
}
|
package guru.springframework.sfgpetclinic.services.jpa;
import java.util.HashSet;
import java.util.Set;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import guru.springframework.sfgpetclinic.model.Vet;
import guru.springframework.sfgpetclinic.repositories.VetRepository;
import guru.springframework.sfgpetclinic.services.VetService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@Profile("jpa")
public class VetServiceJpa implements VetService {
private final VetRepository vetRepository;
public VetServiceJpa(VetRepository vetRepository) {
this.vetRepository = vetRepository;
}
@Override
public Vet findById(Long id) {
log.debug("[VetServiceJpa] - findById method has been called");
return this.vetRepository.findById(id).orElse(null);
}
@Override
public Set<Vet> findAll() {
log.debug("[VetServiceJpa] - findAll method has been called");
Set<Vet> vetSet = new HashSet<>();
this.vetRepository.findAll().forEach(vetSet::add);
return vetSet;
}
@Override
public Vet save(Vet t) {
log.debug("[VetServiceJpa] - save method has been called");
return this.vetRepository.save(t);
}
@Override
public void delete(Vet t) {
log.debug("[VetServiceJpa] - delete method has been called");
this.vetRepository.delete(t);
}
@Override
public void deleteById(Long id) {
log.debug("[VetServiceJpa] - deleteById method has been called");
this.vetRepository.deleteById(id);
}
}
|
package com.java.dev.s01.example01.pruebas;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.java.dev.s01.example01.entities.Persona;
import com.java.dev.s01.example01.util.HibernateUtil;
public class PersonaTest {
public static void main(String[] args) {
Persona p1 = new Persona();
p1.setPersPaternal("Valencia");
p1.setPersMaternal("LLamoca");
p1.setPersName("Danyer");
Persona p2 = new Persona();
p2.setPersPaternal("Valencia");
p2.setPersMaternal("Castro");
p2.setPersName("Oscar");
Persona p3 = new Persona();
p3.setPersPaternal("Aldea");
p3.setPersMaternal("Pezo");
p3.setPersName("Juan");
Persona p4 = new Persona();
p4.setPersPaternal("Vasquez");
p4.setPersMaternal("Cardenas");
p4.setPersName("Axel");
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
System.out.println(transaction);
session.save(p1);
session.save(p2);
session.save(p3);
session.save(p4);
transaction.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
}
try (Session session = HibernateUtil.getSession()) {
//List<Persona> pers = session.createQuery("from Persona", Persona.class).list();
List<Persona> listP = session.createQuery("FROM Persona WHERE persId > 20").getResultList();
listP.forEach(s -> System.out.println(s.getPersId() +" - "+ s.getPersName()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.rockooapps.carrentals;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Rakesh on 7/12/2016.
*/
public class Registration_userDb extends SQLiteOpenHelper {
private SQLiteDatabase db;
Registration_userDb DB = null;
private static final String DATABASE_NAME = "Registration";
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_TABLE_NAME = "Registrationform";
public Registration_userDb(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//Creates table Registration form
String query = "CREATE TABLE Registrationform (_id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, phone INTEGER, username TEXT, password TEXT )";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DELETE TABLE Registrationform ");
onCreate(db);
}
public void entervalues(String name, String phone, String username, String password) {
//enters value into the database when called
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("firstname", name);
cv.put("phone", phone);
cv.put("username", username);
cv.put("password", password);
db.insert("Registrationform", null, cv);
}
public ArrayList<HashMap<String,String>> get_all_names() {
//gets value from database when called
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = this.getReadableDatabase();
String sql = " SELECT * FROM Registrationform";
Cursor c = db.rawQuery(sql, null);
if (c.moveToFirst()){
do {
HashMap<String,String> map = new HashMap<String, String>();
map.put("getID",c.getString(0));
map.put("getName", c.getString(1));
map.put("getNumber", c.getString(2));
list.add(map);
}while (c.moveToNext());
}
return list;
}
}
|
package com.base.crm.users.service;
import java.util.List;
import com.base.crm.users.entity.UserInfo;
public interface UserService {
int deleteByPrimaryKey(Long uId);
int insertSelective(UserInfo record);
UserInfo selectByPrimaryKey(Long uId);
int updateByPrimaryKeySelective(UserInfo record);
UserInfo selectByUserPhone(Long phone);
Long selectPageTotalCount(UserInfo userInfo);
List<UserInfo> selectPageByObjectForList(UserInfo userInfo);
List<UserInfo> selectAllForMap();
}
|
package com.redhat.examples.iot.sensor;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.redhat.examples.iot.model.Measure;
@Component(SensorType.VIBRATION)
@Scope("prototype")
public class VibrationSensor implements Sensor {
@Value("${sensor.vibration.enabled}")
private boolean enabled;
@Value("${sensor.vibration.frequency}")
public int frequency;
@Value("${sensor.vibration.start}")
private int start;
@Value("${sensor.vibration.maxIteration}")
private int maxIteration;
@Value("${sensor.vibration.minIteration}")
private int minIteration;
@Value("${sensor.vibration.minRange}")
private int minRange;
@Value("${sensor.vibration.maxRange}")
private int maxRange;
@Value("${sensor.vibration.peakInterval}")
private int peakInterval;
public double currentValue;
public double sumitValue;
public int count = 1;
public int direction = 1;
@PostConstruct
@Override
public void initAndReset() {
currentValue = start;
}
@Override
public int getFrequency() {
return frequency;
}
@Override
public String getType() {
return SensorType.VIBRATION;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public Measure calculateCurrentMeasure(Measure measure) {
/*
if(count > 0) {
// Calculate random value from range
double randValue = ThreadLocalRandom.current().nextDouble(minIteration, (maxIteration+1));
currentValue = currentValue + randValue;
if(currentValue < minRange || currentValue > maxRange) {
initAndReset();
}
}
*/
double randValue = ThreadLocalRandom.current().nextDouble(minIteration, (maxIteration+1));
if(currentValue > maxRange) {
direction = -1;
}
if(currentValue < minRange) {
direction = 1;
}
currentValue = currentValue + randValue * direction;
if( (count % peakInterval) == 0) {
sumitValue = currentValue * 2.5;
} else {
sumitValue = currentValue;
}
measure.setType(getType());
measure.setPayload(String.valueOf(sumitValue));
++count;
return measure;
}
}
|
package com.vietmedia365.voaapp.event;
import com.vietmedia365.voaapp.model.Story;
/**
* Created by pat109 on 9/28/2014.
*/
public class LoadStoryDetailEvent {
private Story story;
private String storyId;
public LoadStoryDetailEvent(String storyId, Story story){
this.storyId = storyId;
this.story = story;
}
public Story getStory() {
return story;
}
public void setStory(Story story) {
this.story = story;
}
public String getStoryId() {
return storyId;
}
public void setStoryId(String storyId) {
this.storyId = storyId;
}
}
|
package com.plter.ballwithgravity;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.ImageView;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private float speedX = 0, speedY = 0;
private ImageView iv;
private FrameLayout rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = (FrameLayout) findViewById(R.id.rootView);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
iv = (ImageView) findViewById(R.id.iv);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
iv.setX(iv.getX() + speedX);
iv.setY(iv.getY() + speedY);
speedX -= event.values[0] / 500;
speedY += event.values[1] / 500;
if (iv.getX() < 0) {
speedX = Math.abs(speedX);
}
if (iv.getX() > rootView.getWidth() - iv.getWidth()) {
speedX = -Math.abs(speedX);
}
if (iv.getY() < 0) {
speedY = Math.abs(speedY);
}
if (iv.getY() > rootView.getHeight() - iv.getHeight()) {
speedY = -Math.abs(speedY);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
|
package com.javakc.ssm.modules.system.user.dao;
import com.javakc.ssm.base.dao.BaseDao;
import com.javakc.ssm.base.dao.MyBatisDao;
import com.javakc.ssm.modules.system.user.entity.UserEntity;
import java.util.Map;
/**
* 基础用户信息模块数据层实现
* @author javakc
* @version 0.1
*/
@MyBatisDao
public interface UserDao extends BaseDao<UserEntity>{
public int insert(UserEntity entity);
public void insertRelation(Map<String, Object> data);
public void deleteRelation(String userId);
public String login(String loginName);
public UserEntity findByName(String loginName);
}
|
/**
* MicroEmulator
* Copyright (C) 2006-2007 Bartek Teodorczyk <barteo@barteo.net>
* Copyright (C) 2006-2007 Vlad Skarzhevskyy
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @version $Id: ClassPreprocessor.java 1140 2007-03-30 00:10:36Z vlads $
*/
package org.microemu.app.classloader;
import java.io.IOException;
import java.io.InputStream;
import org.microemu.log.Logger;
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import ucl.cs.testingEmulator.core.MultiClassAdapter;
import ucl.cs.testingEmulator.time.TimeClassAdapter;
/**
* @author -Michele Sama- aka -RAX-
*
* University College London Dept. of Computer Science Gower Street London WC1E
* 6BT United Kingdom
*
* Email: M.Sama (at) cs.ucl.ac.uk
*
* Group: Software Systems Engineering
*
*
* This class instruments all loaded class with a MultiClassAdapter
*/
public class ClassPreprocessor {
public static byte[] instrument(final InputStream classInputStream, InstrumentationConfig config) {
try {
ClassReader cr = new ClassReader(classInputStream);
//ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
ClassWriter cw = new ClassWriter(0);
//ClassAdapter ca = ClassPreprocessor.generateClassAdapter(cw, config);
//cr.accept(ca, 0);
//Adds Microemulator Threads and console trap
//cr.accept(new ChangeCallsClassVisitor(cw, config), 0);
//Time support
//cr.accept(new TimeClassAdapter(cw), 0);
cr.accept(cw, 0);
byte[] b=cw.toByteArray();
//Adds Microemulator Threads and console trap
cr = new ClassReader(b,0,b.length);
//cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cw = new ClassWriter(0);
cr.accept(new ChangeCallsClassVisitor(cw, config), 0);
b = cw.toByteArray();
//Time
cr = new ClassReader(b,0,b.length);
//cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cw = new ClassWriter(0);
cr.accept(new TimeClassAdapter(cw), 0);
b = cw.toByteArray();
return b;
} catch (IOException e) {
Logger.error("Error loading MIDlet class", e);
return null;
}
}
protected static byte[] instrument(byte[] b, InstrumentationConfig config, ClassVisitor cv)
{
ClassReader cr = new ClassReader(b,0,b.length);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
cr.accept(cv, 0);
return cw.toByteArray();
}
/*
protected static ClassAdapter generateClassAdapter(ClassWriter cw, InstrumentationConfig config)
{
MultiClassAdapter multiClassAdapter=new MultiClassAdapter(cw);
//Adds Microemulator Threads and console trap
multiClassAdapter.addElement(new ChangeCallsClassVisitor(cw, config));
//Time support
//multiClassAdapter.addElement(new TimeClassAdapter(cw));
return multiClassAdapter;
}*/
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pl.panryba.mc.duels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
/**
*
* @author PanRyba.pl
*/
class DuelListener implements Listener {
private final PluginApi api;
public DuelListener(PluginApi api) {
this.api = api;
}
@EventHandler
protected void onPlayerRespawn(PlayerRespawnEvent event) {
Player player = event.getPlayer();
api.playerRespawned(player);
}
@EventHandler
protected void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
if(player == null) {
return;
}
boolean cancelDrop = api.playerDied(player, event.getDrops());
if(cancelDrop) {
event.getDrops().clear();
event.setDroppedExp(0);
}
}
@EventHandler
protected void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
if(player == null) {
return;
}
api.playerQuit(player);
}
@EventHandler
protected void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
if(player == null) {
return;
}
api.onPlayerMove(player, event.getTo());
}
}
|
package com.jasoftsolutions.mikhuna.model;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
/**
* Created by pc07 on 20/10/2014.
*/
public class RestaurantDishCategory extends AbstractModel {
private Long restaurantServerId;
private String name;
private String description;
private Integer position;
private Long dishesLastUpdate;
private ArrayList<RestaurantDish> restaurantDishes;
@SerializedName("s")
private Integer state;
public RestaurantDishCategory() {}
public RestaurantDishCategory(String name) {
this.name = name;
}
public RestaurantDishCategory(Long serverId, Long restaurantServerId, String name) {
this.setServerId(serverId);
this.restaurantServerId = restaurantServerId;
this.name = name;
}
public RestaurantDishCategory(Long restaurantServerId, String name, Integer position, Long dishesLastUpdate) {
this.restaurantServerId = restaurantServerId;
this.name = name;
this.position = position;
this.dishesLastUpdate = dishesLastUpdate;
}
public Long getRestaurantServerId() {
return restaurantServerId;
}
public void setRestaurantServerId(Long restaurantServerId) {
this.restaurantServerId = restaurantServerId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public Long getDishesLastUpdate() {
return dishesLastUpdate;
}
public void setDishesLastUpdate(Long dishesLastUpdate) {
this.dishesLastUpdate = dishesLastUpdate;
}
public ArrayList<RestaurantDish> getRestaurantDishes() { return restaurantDishes; }
public void setRestaurantDishes(ArrayList<RestaurantDish> restaurantDishes) {
this.restaurantDishes = restaurantDishes;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
@Override
public String toString() {
return name;
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_controller;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.GeneralTransaction;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service.TransactionService;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.exception.ResourceNotFoundException;
@RestController
@RequestMapping("/app/general-transaction")
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = { RequestMethod.POST, RequestMethod.GET, RequestMethod.PUT,
RequestMethod.DELETE })
public class TransactionController {
@Autowired
private TransactionService transactionService;
@GetMapping("/all")
public List<GeneralTransaction> getAllTransactionInformation() {
return transactionService.findAllTransactionInformation();
}
@GetMapping("/transaction/{transactionId}")
public ResponseEntity<GeneralTransaction> GetTransactionInformationByID(@PathVariable Long transactionid) throws ResourceNotFoundException {
return transactionService.findTransactionInformationByID(transactionid);
}
@PostMapping("/add-transaction-information")
public GeneralTransaction addTransaction(@Valid @RequestBody GeneralTransaction transaction) throws ResourceNotFoundException {
return transactionService.addTransactionInformation(transaction);
}
@CrossOrigin
@PutMapping("/transaction/{transactionId}")
public ResponseEntity<GeneralTransaction> updateTransactionInformationController(@PathVariable Long transactionId,
@Valid @RequestBody GeneralTransaction transactionDetails) {
return transactionService.updateTransactionInformation(transactionId, transactionDetails);
}
@CrossOrigin
@DeleteMapping("/transaction/{transactionId}")
public Map<String,Boolean> deleteTransactionInformation(@PathVariable Long transactionId) {
return transactionService.deleteTransactionInformation(transactionId);
}
@CrossOrigin
@GetMapping("/general-transaction-count")
public long getCountOfGeneralTransaction() {
return transactionService.findCountOfGeneralTransaction();
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.devtools_bridge.tests;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import org.chromium.components.devtools_bridge.ui.GCDRegistrationFragment;
import org.chromium.components.devtools_bridge.ui.RemoteInstanceListFragment;
/**
* Activity for testing devtools bridge.
*/
public class DebugActivity extends Activity {
private static final int LAYOUT_ID = 1000;
private static final String DOC_HREF =
"https://docs.google.com/a/chromium.org/document/d/"
+ "188V6TWV8ivbjAPIp6aqwffWrY78xN2an5REajZHpunk/edit?usp=sharing";
private LinearLayout mLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLayout = new LinearLayout(this);
mLayout.setId(LAYOUT_ID);
mLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText(Html.fromHtml(
"See <a href=\"" + DOC_HREF + "\">testing instructions</a>."));
textView.setMovementMethod(LinkMovementMethod.getInstance());
mLayout.addView(textView);
addActionButton("Start LocalSessionBridge", DebugService.START_SESSION_BRIDGE_ACTION);
addActionButton("Start DevToolsBridgeServer", DebugService.START_SERVER_ACTION);
addActionButton("Stop", DebugService.STOP_ACTION);
LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
getFragmentManager()
.beginTransaction()
.add(LAYOUT_ID, new TestGCDRegistrationFragment())
.add(LAYOUT_ID, new RemoteInstanceListFragmentImpl())
.commit();
setContentView(mLayout, layoutParam);
}
private void addActionButton(String text, String action) {
Button button = new Button(this);
button.setText(text);
button.setOnClickListener(new SendActionOnClickListener(action));
mLayout.addView(button);
}
private class SendActionOnClickListener implements View.OnClickListener {
private final String mAction;
SendActionOnClickListener(String action) {
mAction = action;
}
@Override
public void onClick(View v) {
Intent intent = new Intent(DebugActivity.this, DebugService.class);
intent.setAction(mAction);
startService(intent);
}
}
private static class TestGCDRegistrationFragment
extends GCDRegistrationFragment implements View.OnClickListener {
private Button mButton;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mButton = new Button(getActivity());
mButton.setOnClickListener(this);
updateText();
return mButton;
}
public void updateText() {
mButton.setText(isRegistered()
? "Unregister (registered for " + getOwner() + ")"
: "Register in GCD");
}
@Override
protected void onRegistrationStatusChange() {
updateText();
}
@Override
protected String generateDisplayName() {
return Build.MODEL + " Test app";
}
@Override
public void onClick(View v) {
if (!isRegistered()) {
register();
} else {
unregister();
}
}
}
private final class RemoteInstanceListFragmentImpl extends RemoteInstanceListFragment {
@Override
protected void connect(String oAuthToken, String remoteInstanceId) {
startService(new Intent(DebugActivity.this, DebugService.class)
.setAction(DebugService.START_GCD_CLIENT_ACTION)
.putExtra(DebugService.EXTRA_OAUTH_TOKEN, oAuthToken)
.putExtra(DebugService.EXTRA_REMOTE_INSTANCE_ID, remoteInstanceId));
}
}
}
|
package com.nationsky.vote.component;
public class ResultCode {
/**
* 成功
*/
public static final int SUCCESS = 0;
/**
* 未知异常
*/
public static final int ERROR = 1000;
/**
* 未知url
*/
public static final int UNKNOWN_URL = 1001;
/**
* 请求体不合法
*/
public static final int REQUEST_ERROR = 1002;
/**
* 方法不存在
*/
public static final int METHOD_NOTFOUND = 1003;
/**
* 跳出流程
*/
public static final int JUMP_FLOW = 10000;
/**
* 方法版本不正确,请检查!
*/
public static final int RC_1004 = 1004;
/**
* 机构编码不存在!
*/
public static final int RC_1006 = 1006;
/**
* 系统数据库操作异常
*/
public static final int DBERROR = 10001;
/**
* 系统调度异常
*/
public static final int QUARTZERROR = 10002;
/**
* fdfs异常
*/
public static final int FDFS_ERROR = 10003;
/**
* 失败响应码,1
*/
public static final int RC_FAIL = -1;
/**
* VOTE-签名不正确
*/
public static final int RC_4001 = 4001;
/**
* VOTE-appkey不正确或无权限
*/
public static final int RC_4002 = 4002;
/**
* VOTE-token超时
*/
public static final int RC_4003 = 4003;
/**
* VOTE-应用消息(代办)-推送id不存在
*/
public static final int RC_4004 = 4004;
/**
* VOTE-节点未注册
*/
public static final int RC_4005 = 4005;
/**
* VOTE-AdminAuth 鉴权失败
*/
public static final int RC_4006 = 4006;
/**
* VOTE-发送者不存在
*/
public static final int RC_4007 = 4007;
/**
* VOTE-所有接收者都不存在
*/
public static final int RC_4008 = 4008;
/**
* VOTE-投票信息不存在
*/
public static final int RC_5001 = 5001;
/**
* VOTE-投票选项不存在
*/
public static final int RC_5002 = 5002;
/**
* VOTE-投票已过期
*/
public static final int RC_5003 = 5003;
/**
* VOTE-投票必须实名
*/
public static final int RC_5004 = 5004;
/**
* VOTE-投票不可以多选
*/
public static final int RC_5005 = 5005;
/**
* VOTE-投票项数超限
*/
public static final int RC_5006 = 5006;
/**
* VOTE-无权限终止投票
*/
public static final int RC_5007 = 5007;
/**
* VOTE-无权限删除投票
*/
public static final int RC_5008 = 5008;
/**
* VOTE-已投票,不可重复投票
*/
public static final int RC_5009 = 5009;
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* Wip generated by hbm2java
*/
public class Wip implements java.io.Serializable {
private WipId id;
public Wip() {
}
public Wip(WipId id) {
this.id = id;
}
public WipId getId() {
return this.id;
}
public void setId(WipId id) {
this.id = id;
}
}
|
/*
* ---------------------------------------------------------------------------------------------------------------------
* Brigham Young University - Project MEDIA StillFace DataCenter
* ---------------------------------------------------------------------------------------------------------------------
* The contents of this file contribute to the ProjectMEDIA DataCenter for managing and analyzing data obtained from the
* results of StillFace observational experiments.
*
* This code is free, open-source software. You may distribute or modify the code, but Brigham Young University or any
* parties involved in the development and production of this code as downloaded from the remote repository are not
* responsible for any repercussions that come as a result of the modifications.
*/
package com.byu.pmedia.model;
import com.googlecode.cqengine.attribute.Attribute;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import static com.googlecode.cqengine.query.QueryFactory.attribute;
/**
* StillFaceData
* Internal data structure for holding information from a data entry in the database
*
* @author Braden Hitchcock
*/
public class StillFaceData {
/*
* These variables are for the JavaFX Table object in the GUI. The table cells are populated using a CellFactory,
* and in order to do this we need to have special variable types
*/
private SimpleIntegerProperty dataID = new SimpleIntegerProperty();
private SimpleIntegerProperty importID = new SimpleIntegerProperty();
private SimpleIntegerProperty time = new SimpleIntegerProperty();
private SimpleIntegerProperty duration = new SimpleIntegerProperty();
private SimpleObjectProperty<StillFaceCode> code = new SimpleObjectProperty<>();
private SimpleStringProperty comment = new SimpleStringProperty();
/*
* The following variables are defined for use with the CQEngine IndexedCollections. This allows us to
* create extremely fast indexing capabilities and cache data in memory for use. Data is only cached if
* the model.cache configuration option is set to 'true'
*/
public static final Attribute<StillFaceData, Integer> DATA_ID =
attribute("dataID", StillFaceData::getDataID);
public static final Attribute<StillFaceData, Integer> IMPORT_ID =
attribute("importID", StillFaceData::getImportID);
public static final Attribute<StillFaceData, Integer> TIME =
attribute("time", StillFaceData::getTime);
public static final Attribute<StillFaceData, Integer> DURATION =
attribute("duration", StillFaceData::getDuration);
public static final Attribute<StillFaceData, StillFaceCode> CODE =
attribute("code", StillFaceData::getCode);
public static final Attribute<StillFaceData, String> COMMENT =
attribute("comment", StillFaceData::getComment);
public StillFaceData(int importID, int time, int duration, StillFaceCode code, String comment){
this.importID = new SimpleIntegerProperty(importID);
this.setTime(time);
this.setDuration(duration);
this.setCode(code);
this.setComment(comment);
}
public StillFaceData(int dataID, int importID, int time, int duration, StillFaceCode code, String comment){
this.dataID = new SimpleIntegerProperty(dataID);
this.importID = new SimpleIntegerProperty(importID);
this.setTime(time);
this.setDuration(duration);
this.setCode(code);
this.setComment(comment);
}
public int getTime() {
return time.get();
}
public void setTime(int time) {
this.time.set(time);
}
public int getDuration() {
return duration.get();
}
public void setDuration(int duration) {
this.duration.set(duration);
}
public StillFaceCode getCode() {
return code.get();
}
public void setCode(StillFaceCode code){
this.code.set(code);
}
public String getComment() { return comment.get(); }
public void setComment(String comment) {
this.comment.set(comment);
}
public int getDataID() {
return dataID.get();
}
public void setImportID(int importID) { this.importID.set(importID); }
public int getImportID() {
return importID.get();
}
@Override
public int hashCode(){
int result = code.hashCode();
result = result * 24 + dataID.get();
result = result >> (time.get() % 4);
result = result * 13 + time.get();
result += comment.get().hashCode();
return result;
}
}
|
/*
* 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 mainlibrary;
import java.awt.Color;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import static mainlibrary.LibrarianSuccess.ThisLogined;
/**
*
* @author bikash
*/
public class BookForm extends javax.swing.JFrame {
/**
* Creates new form BookForm
*/
public BookForm() {
initComponents();
jPanel1.setBackground(Color.BLACK);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
BookName = new javax.swing.JTextField();
Author = new javax.swing.JTextField();
Publisher = new javax.swing.JTextField();
Genre = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
Shelf = new javax.swing.JTextField();
Row = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(700, 500));
jLabel1.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 51, 51));
jLabel3.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 51, 51));
jLabel4.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 51, 51));
jLabel6.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 51, 51));
jLabel7.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 51, 51));
jLabel2.setFont(new java.awt.Font("Raleway Medium", 1, 16)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 51, 51));
jPanel1.setBackground(new java.awt.Color(0, 0, 0));
BookName.setText("Book Name");
BookName.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
BookNameFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
BookNameFocusLost(evt);
}
});
BookName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BookNameActionPerformed(evt);
}
});
Author.setText("Author");
Author.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
AuthorFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
AuthorFocusLost(evt);
}
});
Author.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
AuthorActionPerformed(evt);
}
});
Publisher.setText("Publisher");
Publisher.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
PublisherFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
PublisherFocusLost(evt);
}
});
Publisher.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PublisherActionPerformed(evt);
}
});
Genre.setText("Genre");
Genre.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
GenreFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
GenreFocusLost(evt);
}
});
Genre.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
GenreActionPerformed(evt);
}
});
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Raleway Medium", 0, 14)); // NOI18N
jButton1.setText("Add Media");
jButton1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
Shelf.setText("Shelf");
Shelf.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
ShelfFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
ShelfFocusLost(evt);
}
});
Shelf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ShelfActionPerformed(evt);
}
});
Row.setText("Row");
Row.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
RowFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
RowFocusLost(evt);
}
});
Row.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RowActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(255, 255, 255));
jButton2.setText("<-");
jButton2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel10.setIcon(new javax.swing.ImageIcon("C:\\Users\\Student\\Downloads\\admin.jpg")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(116, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel9)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addGap(103, 103, 103))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(164, 164, 164)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel9)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jLabel8.setBackground(new java.awt.Color(0, 0, 0));
jLabel8.setFont(new java.awt.Font("Raleway Medium", 0, 24)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Add Media");
jTextField1.setText("quantity");
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextField1FocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField1FocusLost(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(80, 80, 80)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Shelf, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Row, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(59, 59, 59)
.addComponent(jButton1))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Publisher, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
.addComponent(Author, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
.addComponent(BookName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE))
.addComponent(Genre, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(106, 106, 106)
.addComponent(jLabel8)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 70, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton2)
.addGap(15, 15, 15)
.addComponent(jLabel8)
.addGap(30, 30, 30)
.addComponent(BookName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(Author, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)
.addComponent(Publisher, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(35, 35, 35)
.addComponent(Genre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(Shelf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(1, 1, 1)))
.addComponent(Row, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(80, 80, 80)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(jLabel4))
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(jLabel6))
.addGroup(layout.createSequentialGroup()
.addGap(100, 100, 100)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(130, 130, 130)
.addComponent(jLabel7)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(150, 150, 150)
.addComponent(jLabel1)
.addGap(60, 60, 60)
.addComponent(jLabel4)
.addGap(210, 210, 210)
.addComponent(jLabel6))
.addGroup(layout.createSequentialGroup()
.addGap(260, 260, 260)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(310, 310, 310)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(470, 470, 470)
.addComponent(jLabel7)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BookNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BookNameActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_BookNameActionPerformed
private void PublisherActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PublisherActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_PublisherActionPerformed
private void AuthorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AuthorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_AuthorActionPerformed
private void RowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RowActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_RowActionPerformed
private void ShelfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShelfActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ShelfActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
this.dispose();
ThisLogined.setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String BookN = BookName.getText();
String AuthorN = Author.getText();
String PublisherN = Publisher.getText();
String ShelfN = Shelf.getText();
String RowN = Row.getText();
String GenreN = Genre.getText();
String QN=jTextField1.getText();
if(BookDao.PublisherValidate(PublisherN))
{
}else{
if(BookDao.AddPublisher(PublisherN)!=0)
{
; // JOptionPane.showMessageDialog(BookForm.this, "Sorry, Publisher can't be added!","Publisher Error!", JOptionPane.ERROR_MESSAGE);
}
}
if(BookDao.SaveBook(BookN,GenreN,AuthorN,PublisherN,ShelfN,RowN)!=0)
{
JOptionPane.showMessageDialog(BookForm.this, "The Book is added!","Book Added!", JOptionPane.ERROR_MESSAGE);
BookName.setText("");
Author.setText("");
Publisher.setText("");
Shelf.setText("");
Row.setText("");
Genre.setText("");
jTextField1.setText("");
}
else
JOptionPane.showMessageDialog(BookForm.this, "The Book is not added!","Adding Book Error!", JOptionPane.ERROR_MESSAGE);
}//GEN-LAST:event_jButton1ActionPerformed
private void GenreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GenreActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_GenreActionPerformed
private void BookNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_BookNameFocusGained
// TODO add your handling code here:
if(BookName.getText().equals("Book Name")){
BookName.setText("");
}
BookName.setForeground(Color.black);
}//GEN-LAST:event_BookNameFocusGained
private void BookNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_BookNameFocusLost
// TODO add your handling code here:
if(BookName.getText().equals("")){
BookName.setText("Book Name");
}
BookName.setForeground(new Color(0,0,0));
}//GEN-LAST:event_BookNameFocusLost
private void AuthorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AuthorFocusGained
if(Author.getText().equals("Author")){
Author.setText("");
}
Author.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_AuthorFocusGained
private void AuthorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AuthorFocusLost
if(Author.getText().equals("")){
Author.setText("Author");
}
Author.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_AuthorFocusLost
private void PublisherFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PublisherFocusGained
if(Publisher.getText().equals("Publisher")){
Publisher.setText("");
}
Publisher.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_PublisherFocusGained
private void PublisherFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_PublisherFocusLost
if(Publisher.getText().equals("")){
Publisher.setText("Publisher");
}
Publisher.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_PublisherFocusLost
private void GenreFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_GenreFocusGained
if(Genre.getText().equals("Genre")){
Genre.setText("");
}
Genre.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_GenreFocusGained
private void GenreFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_GenreFocusLost
if(Genre.getText().equals("")){
Genre.setText("Genre");
}
Genre.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_GenreFocusLost
private void ShelfFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ShelfFocusGained
if(Shelf.getText().equals("Shelf")){
Shelf.setText("");
}
Shelf.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_ShelfFocusGained
private void ShelfFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ShelfFocusLost
if(Shelf.getText().equals("")){
Shelf.setText("Shelf");
}
Shelf.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_ShelfFocusLost
private void RowFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_RowFocusGained
if(Row.getText().equals("Row")){
Row.setText("");
}
Row.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_RowFocusGained
private void RowFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_RowFocusLost
if(Row.getText().equals("")){
Row.setText("Row");
}
Row.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_RowFocusLost
private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained
if(jTextField1.getText().equals("quantity")){
jTextField1.setText("");
}
jTextField1.setForeground(Color.black); // TODO add your handling code here:
}//GEN-LAST:event_jTextField1FocusGained
private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost
if(jTextField1.getText().equals("")){
jTextField1.setText("quantity");
}
jTextField1.setForeground(new Color(0,0,0)); // TODO add your handling code here:
}//GEN-LAST:event_jTextField1FocusLost
/**
* @param args the command line arguments
*/
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(BookForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BookForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BookForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BookForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new BookForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Author;
private javax.swing.JTextField BookName;
private javax.swing.JTextField Genre;
private javax.swing.JTextField Publisher;
private javax.swing.JTextField Row;
private javax.swing.JTextField Shelf;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
package com.yougou.merchant.api.supplier.vo;
import java.io.Serializable;
public class TaobaoImage implements Serializable{
/**
* 生成的序列号
*/
private static final long serialVersionUID = 5950798725264101551L;
/**
* 全参数构造方法
* @param numIid
* @param oldImageURL
* @param newImageURL
* @param thumbnailImageURL
*/
public TaobaoImage(Long numIid, String oldImageURL, String newImageURL,
String thumbnailImageURL) {
super();
this.numIid = numIid;
this.oldImageURL = oldImageURL;
this.newImageURL = newImageURL;
this.thumbnailImageURL = thumbnailImageURL;
}
/** 淘宝商品id */
private Long numIid;
/** 原图片URL */
private String oldImageURL;
/** 新图片URL */
private String newImageURL;
/** 缩略图URL */
private String thumbnailImageURL;
public Long getNumIid() {
return numIid;
}
public void setNumIid(Long numIid) {
this.numIid = numIid;
}
public String getOldImageURL() {
return oldImageURL;
}
public void setOldImageURL(String oldImageURL) {
this.oldImageURL = oldImageURL;
}
public String getNewImageURL() {
return newImageURL;
}
public void setNewImageURL(String newImageURL) {
this.newImageURL = newImageURL;
}
public String getThumbnailImageURL() {
return thumbnailImageURL;
}
public void setThumbnailImageURL(String thumbnailImageURL) {
this.thumbnailImageURL = thumbnailImageURL;
}
@Override
public String toString() {
return "TaobaoImage [numIid=" + numIid + ", oldImageURL=" + oldImageURL
+ ", newImageURL=" + newImageURL + ", thumbnailImageURL="
+ thumbnailImageURL + "]";
}
}
|
public class Kasutus{
public static void main(String[] args){
Book b1 = new Book("J.K Rowling, ","Harry Potter and the Sorcere's Stone, ", "fantasy");
Book b2 = new Book("J.K Rowling, ", "Harry Potter and the Prisoner of Azkaban, ", "fantasy");
Book b3 = new Book("J.R.R Tolkieni, ","Lord of the Rings, ","fantasy");
Book[] Books = new Book[3];
Books[0] = b1;
Books[1] = b2;
Books[2] = b3;
for (Book b: Books){
System.out.println(b.authorName + b.book + b.genre);
}
b2.changeBook("Harry Potter and the Goblet of Fire, ");
System.out.println("\n\n");
for (Book b: Books){
System.out.println(b.authorName + b.book + b.genre);
}
}
}
|
package com.zhao.id;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.core.strategy.keygen.SnowflakeShardingKeyGenerator;
import org.apache.shardingsphere.spi.keygen.ShardingKeyGenerator;
import java.util.Properties;
@Slf4j
public class MyShardingId implements ShardingKeyGenerator {
private SnowflakeShardingKeyGenerator shardingKeyGenerator = new SnowflakeShardingKeyGenerator();
@Override
public Comparable<?> generateKey() {
log.info("执行了自定义的id生成器");
return shardingKeyGenerator.generateKey();
}
@Override
public String getType() {
return "zhao-sharding-key";
}
@Override
public Properties getProperties() {
return null;
}
@Override
public void setProperties(Properties properties) {
}
}
|
package com.pa.miniEip.model;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import java.util.List;
public class Question {
@Id
private ObjectId id;
private String name;
private QuestionType type;
private List<Option> options;
public Question() {
this.id = new ObjectId();
}
public String getId() {
return id.toHexString();
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public QuestionType getType() {
return type;
}
public void setType(QuestionType type) {
this.type = type;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
|
package edu.xpu.hcp.manage.admin.service;
import edu.xpu.hcp.manage.admin.model.SysUser;
import edu.xpu.hcp.manage.core.service.CurdService;
import java.util.List;
public interface ISysUserService extends CurdService<SysUser>{
/**
* 查找所有用户
*/
List<SysUser> findAll();
}
|
package com.tencent.mm.plugin.appbrand.jsapi.file;
import com.tencent.mm.plugin.appbrand.appstorage.j;
import com.tencent.mm.plugin.appbrand.appstorage.k;
import com.tencent.mm.plugin.appbrand.jsapi.file.f.a;
import com.tencent.mm.plugin.appbrand.l;
import java.io.File;
import java.util.Locale;
import org.json.JSONObject;
final class as extends d {
as() {
}
final a a(l lVar, String str, JSONObject jSONObject) {
String format = String.format(Locale.US, "fail no such file or directory, rename \"%s\" -> \"%s\"", new Object[]{str, jSONObject.optString("newPath")});
String format2 = String.format(Locale.US, "fail permission denied, rename \"%s\" -> \"%s\"", new Object[]{str, r0});
File rb = lVar.fdO.fcw.rb(str);
if (rb == null || !rb.exists()) {
return new a(format, new Object[0]);
}
if (k.z(rb)) {
return new a("fail \"%s\" not a regular file", new Object[]{str});
}
j a = lVar.fdO.fcw.a(r0, rb, true);
switch (1.fQo[a.ordinal()]) {
case 1:
return new a(format2, new Object[0]);
case 2:
return new a(format, new Object[0]);
case 3:
return new a("fail sdcard not mounted", new Object[0]);
case 4:
return new a("ok", new Object[0]);
default:
return new a("fail " + a.name(), new Object[0]);
}
}
protected final String q(JSONObject jSONObject) {
return jSONObject.optString("oldPath");
}
}
|
package com.gmail.khanhit100896.foody.food;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
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.Volley;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.gmail.khanhit100896.foody.R;
import com.gmail.khanhit100896.foody.config.Config;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class FoodActivity extends AppCompatActivity {
/*
* Khai báo biến cần thiết
*/
protected String getURL = Config.getConfig().getPathGetAllFood();
protected RecyclerView recyclerFood;
protected List<Food> foodList;
protected FoodRecyclerViewAdapter adapter;
protected Toolbar app_bar_food;
protected AppBarLayout appBarLayout;
/*
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
/*
* Ánh xạ và khởi tạo view, các biến đã khai báo
*/
this.app_bar_food = findViewById(R.id.app_bar_food);
this.recyclerFood = findViewById(R.id.recycler_food);
this.foodList = new ArrayList<>();
this.app_bar_food.setTitle("Danh sách các món ăn");
setSupportActionBar(this.app_bar_food);
this.appBarLayout = findViewById(R.id.appBarLayout);
/*
*/
// Gọi hàm lấy tất cả các món ăn
getAllFood(this.getURL);
// Bắt sự kiện ẩn appBarLayout khi scroll up
// this.recyclerFood.addOnScrollListener(new RecyclerView.OnScrollListener() {
// @Override
// public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// super.onScrollStateChanged(recyclerView, newState);
// }
//
// @Override
// public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
// if (dy > 0 && appBarLayout.isShown()) {
// appBarLayout.setVisibility(View.GONE);
// } else if (dy < 0 ) {
// appBarLayout.setVisibility(View.VISIBLE);
// }
// }
// });
}
/*
* Hàm lấy tất cả các món ăn từ CSDL và hiển thị theo dạng lưới
*/
private void getAllFood(String getURL) {
RequestQueue requestQueue = Volley.newRequestQueue(Objects.requireNonNull(getApplicationContext()));
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getURL, null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
foodList.clear();
SkeletonScreen skeletonScreen;
skeletonScreen = Skeleton.bind(recyclerFood)
.adapter(adapter)
.load(R.layout.layout_default_item_skeleton)
.show();
for (int i=0;i<response.length();i++){
try {
JSONObject object = response.getJSONObject(i);
Food food = new Food(
object.getInt("ID"),
object.getString("FoodCode"),
object.getString("FoodName"),
object.getString("FoodAddress"),
object.getString("FoodPrice"),
object.getString("ImageAddress"),
object.getString("ResCode"),
object.getString("KindCode")
);
foodList.add(food);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*
* Đổ dữ liệu đồ ăn vặt lên RecyclerView
*/
adapter = new FoodRecyclerViewAdapter(getApplicationContext(),foodList);
recyclerFood.setLayoutManager(new GridLayoutManager(getApplicationContext(),2));
recyclerFood.setAdapter(adapter);
/*
*/
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonArrayRequest);
}
/*
* Hàm khởi tạo menu
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView search = (SearchView) item.getActionView();
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(getApplicationContext(),query,Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
}
|
// In an array list, elements can be added and removed.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class DayThree {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
//This syntax creates an array list object
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("Isabel");
stringList.add("Bella");
stringList.add("Honey");
System.out.println("#1 Printing the arrayList before and after swap:");
System.out.println(stringList);
// #1 Swap two items in an array list that are string
Collections.swap(stringList, 0, 1);
System.out.println(stringList);
// #2 Write a program to clone an array list to another array list using clone() of arraylist.
ArrayList<String> otherStrings = new ArrayList<String>();
otherStrings.add("");
otherStrings.add("");
otherStrings.add("");
Collections.copy(otherStrings, stringList);
System.out.println("\n#2 Printing the cloned array: ");
System.out.println(otherStrings);
// #3 Iterate a linked list in reverse order
LinkedList<Integer> int_list = new LinkedList<Integer>();
int_list.add(2);
int_list.add(4);
int_list.add(6);
// The descendingIterator method returns an iterator over the elements
// in this LinkedList "int_list" in reverse sequential order.
Iterator x = int_list.descendingIterator();
System.out.println("\n#3 Printing the linked list in reverse order: ");
while(x.hasNext()) {
System.out.print(x.next() + " ");
}
// #4 Insert the specified element at the end of a linked list using offerLast().
int_list.offerLast(8);
System.out.println("\n\n#4 New int_list after using the offerLast():");
System.out.println(int_list);
// #5 Search an element in an arrayList
int index1 = stringList.indexOf("Bella");
int index2 = stringList.indexOf("Watermelon");
System.out.println("\n#5 Searching for existing elements in an ArrayList:");
if (index1 == -1) {
System.out.println("The element Bella is not in the ArrayList");
}
else {
System.out.println("The element Bella is in the ArrayList");
}
if (index2 == -1) {
System.out.println("The element Watermelon is not in the ArrayList");
}
else {
System.out.println("The element Watermelon is in the ArrayList");
}
// #6 Write a program to join two array lists
System.out.println("\n#6 Joining two ArrayLists:");
ArrayList<String> newList = new ArrayList<String>();
newList.add("Cherry");
newList.add("Pumpkin");
newList.add("Cinnamon");
// Joining with a existing Array List created above
stringList.addAll(newList);
System.out.println(stringList);
// COMPARABLE
// #7 Compare the ranking of Player where Player class has ranking, name and age as attributes using comparable interface.
ArrayList<Day3Player> playerList = new ArrayList<Day3Player>();
playerList.add(new Day3Player("Isabel",1,29));
playerList.add(new Day3Player("Sylvia",2,33));
System.out.println("\n#7 Comparing the rank of two players using COMPARABLE:");
Collections.sort(playerList); // We are sorting based on the ranking
for(Day3Player st:playerList){
System.out.println(st.getName()+" "+st.getRanking()+" "+st.getAge());
}
// COMPARATOR
// #8 Compare the Player based on age and ranking using Comparator interface.
Collections.sort(playerList, new Day3AgeCompare());
System.out.println("\n#8a Comparing the AGE of two players using COMPARATOR:");
for(Day3Player player: playerList) {
System.out.println(player.name +" "+ player.age);
}
Collections.sort(playerList, new Day3RankCompare());
System.out.println("\n#8b Comparing the RANK of two players using COMPARATOR:");
for(Day3Player player: playerList) {
System.out.println(player.name +" "+ player.ranking);
}
// 9.Open a text file, read the file one line at a time. Read each line as a String and print the total number of characters.
System.out.println("\n#9 Reading from a file");
// Try catch in case that the file is not found.
try {
File myObj = new File("src/textFile");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
File myObj = new File("src/textFile");
FileInputStream fileStream = new FileInputStream(myObj);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
int characterCount = 0;
String line;
while((line = reader.readLine()) != null){
characterCount += line.length();
}
System.out.println("Total number of characters = " + characterCount);
// #10 Write a lambda expression to generate the square of a number.
System.out.println("\n#10 Lambda expression to generate the square of a number: ");
Day3Lambda squared = (int a) -> {
System.out.println("Squared numbers: " + a*a);
};
squared.printSqaured(5);
}
}
|
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "CalculatorServlet", urlPatterns = "/calculate")
public class CalculatorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
float firstOperand = Integer.parseInt(request.getParameter("first-operand"));
request.setAttribute("firstOperand",firstOperand);
float secondOperand = Integer.parseInt(request.getParameter("second-operand"));
request.setAttribute("secondOperand",secondOperand);
char operator = request.getParameter("operator").charAt(0);
float result = Calculation.calculate(firstOperand,secondOperand,operator);
request.setAttribute("result",result);
request.getRequestDispatcher("/result.jsp").forward(request,response);
}
// protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
// }
}
|
package com.blackjack.domain;
import java.util.ArrayList;
public class TestUtil {
public static ArrayList<Card> generateCardsWithGivenOrder(ArrayList<Card> orderCards) {
ArrayList<Card> cardList = new ArrayList<>(Suit.values().length * Rank.values().length);
for (Card card : orderCards) {
cardList.add(card);
}
for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
Card card = new Card(suit, rank);
if (!cardList.contains(card)) {
cardList.add(card);
}
}
}
return cardList;
}
/* public static void main(String[] args) {
System.out.println(generateCardsWithGivenOrder(new Card[0]).length);
}*/
}
|
package br.com.walmart.krusty.web.exception;
import javax.ejb.ApplicationException;
@ApplicationException
public class InvalidPasswordException extends KrustyWebException {
private static final long serialVersionUID = -1605634317012241385L;
public InvalidPasswordException() {
super();
}
public InvalidPasswordException(final String message) {
super(message);
}
public InvalidPasswordException(final Throwable t) {
super(t);
}
public InvalidPasswordException(final String message, final Throwable t) {
super(message, t);
}
}
|
package com.rishi.baldawa.iq;
import com.rishi.baldawa.iq.model.ListNode;
import org.junit.Test;
import static com.rishi.baldawa.iq.model.ListNodeDataFactory.l;
import static org.junit.Assert.*;
public class SwapNodesInPairsTest {
@Test
public void swapPairs() throws Exception {
ListNode input = l(1, 2, 3, 4);
ListNode expected = l(2, 1, 4, 3);
assertEquals(new SwapNodesInPairs().swapPairs(input), expected);
}
@Test
public void swapPairsOddArray() throws Exception {
ListNode input = l(1, 2, 3, 4, 5);
ListNode expected = l(2, 1, 4, 3, 5);
assertEquals(new SwapNodesInPairs().swapPairs(input), expected);
}
@Test
public void swapPairsOneElement() throws Exception {
ListNode input = l(1);
ListNode expected = l(1);
assertEquals(new SwapNodesInPairs().swapPairs(input), expected);
}
@Test
public void swapPairsEmpty() throws Exception {
ListNode input = null;
ListNode expected = null;
assertEquals(new SwapNodesInPairs().swapPairs(input), expected);
}
}
|
package com.jjw.sparkCore.transformations;
import java.util.Arrays;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;
import com.google.common.base.Optional;
public class Operator_join {
public static void main(String[] args) {
SparkConf conf = new SparkConf();
conf.setMaster("local").setAppName("join");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaPairRDD<Integer, Integer> nameRDD = sc.parallelizePairs(Arrays.asList(
new Tuple2<Integer, Integer>(0, 101),
new Tuple2<Integer, Integer>(1, 102),
new Tuple2<Integer, Integer>(2, 103),
new Tuple2<Integer, Integer>(3, 104)
));
JavaPairRDD<Integer, Integer> scoreRDD = sc.parallelizePairs(Arrays.asList(
new Tuple2<Integer, Integer>(1, 100),
new Tuple2<Integer, Integer>(2, 200),
new Tuple2<Integer, Integer>(3, 300),
new Tuple2<Integer, Integer>(4, 400)
));
scoreRDD.foreach(x -> {
System.out.println(x);
});
JavaPairRDD join = nameRDD.join(scoreRDD);
join.foreach(x -> {
System.out.println(x);
});
System.out.println("join.partitions().size()--------"+join.partitions().size());
// join.foreach(new VoidFunction<Tuple2<Integer,Tuple2<String,Integer>>>() {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void call(Tuple2<Integer, Tuple2<String, Integer>> t)
// throws Exception {
// System.out.println(t);
// }
// });
//
// JavaPairRDD<Integer, Tuple2<String, Optional<Integer>>> leftOuterJoin = nameRDD.leftOuterJoin(scoreRDD);
// System.out.println("leftOuterJoin.partitions().size()--------"+leftOuterJoin.partitions().size());
// leftOuterJoin.foreach(new VoidFunction<Tuple2<Integer,Tuple2<String,Optional<Integer>>>>() {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void call(
// Tuple2<Integer, Tuple2<String, Optional<Integer>>> t)
// throws Exception {
// System.out.println(t);
// }
// });
// JavaPairRDD<Integer, Tuple2<Optional<String>, Integer>> rightOuterJoin = nameRDD.rightOuterJoin(scoreRDD);
// System.out.println("rightOuterJoin.partitions().size()--------"+rightOuterJoin.partitions().size());
// rightOuterJoin.foreach(new VoidFunction<Tuple2<Integer,Tuple2<Optional<String>,Integer>>>() {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void call(Tuple2<Integer, Tuple2<Optional<String>, Integer>> t)
// throws Exception {
// System.out.println(t);
// }
// });
// JavaPairRDD<Integer, Tuple2<Optional<String>, Optional<Integer>>> fullOuterJoin = nameRDD.fullOuterJoin(scoreRDD);
// System.out.println("fullOuterJoin.partitions().size()--------"+fullOuterJoin.partitions().size());
//
// fullOuterJoin.foreach(new VoidFunction<Tuple2<Integer,Tuple2<Optional<String>,Optional<Integer>>>>() {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public void call(
// Tuple2<Integer, Tuple2<Optional<String>, Optional<Integer>>> t)
// throws Exception {
// System.out.println(t);
// }
// });
}
}
|
package ru.smartsarov.election;
import static ru.smartsarov.election.Constants.CIKRF_UIK_INFO_URL;
import static ru.smartsarov.election.Constants.DUBNA_DB_NAME;
import static ru.smartsarov.election.Constants.DUBNA_TIK;
import static ru.smartsarov.election.Constants.DUBNA_UIKS;
import static ru.smartsarov.election.Constants.MOSCOW_REGION;
import static ru.smartsarov.election.Constants.NIZHNY_NOVGOROD_REGION;
import static ru.smartsarov.election.Constants.SAROV_DB_NAME;
import static ru.smartsarov.election.Constants.SAROV_TIK;
import static ru.smartsarov.election.Constants.SAROV_UIKS;
import static ru.smartsarov.election.Constants.UIK_BAD_NUMBER_MESSAGE;
import static ru.smartsarov.election.Constants.UIK_VYBORY_IZBIRKOM_RU_MOSCOW_REGION;
import static ru.smartsarov.election.Constants.UIK_VYBORY_IZBIRKOM_RU_NNOV;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import ru.smartsarov.election.db.SQLiteDB;
import ru.smartsarov.election.db.Uik;
import ru.smartsarov.election.db.UikMember;
@Path("/")
@Produces(MediaType.APPLICATION_JSON + ";charset=UTF-8")
public class Election {
// TODO доработать под конкретный УИК
@GET
@Path("/{region}/{uik}")
public Response uikInfo(@PathParam("region") int region, @PathParam("uik") int uikNumber) {
int[] uikNumbers = {uikNumber};
return Response.status(Response.Status.OK).entity(uiksToJsonString(region, uikNumbers)).build();
}
// TODO распараллелить этот метод
@GET
@Path("/{city}/uiks")
public Response getUiks(@PathParam("city") String city) {
String resp = null;
String dbName = null;
/*List<Uik> uiks = SQLiteDB.getEntityManager().createNamedQuery("Uik.findAll", Uik.class).getResultList();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
//gson.serializeNulls();
String uiksString = gson.toJson(uiks, new TypeToken<List<Uik>>(){}.getType());*/
try {
switch (city) {
case "sarov":
dbName = SAROV_DB_NAME;
break;
case "dubna":
dbName = DUBNA_DB_NAME;
break;
default:
resp = "Указан неверный город";
return Response.status(Response.Status.OK).entity(resp).build();
}
resp = SQLiteDB.getUiksFromDB(dbName);
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
@GET
@Path("/{city}/uiks2db")
public Response uiks2db(@PathParam("city") String city) {
String resp = null;
String cityUiks = null;
String cityTik = null;
int region;
String vybboryIzbirkomUrl = null;
String dbName = null;
switch (city) {
case "sarov":
cityUiks = SAROV_UIKS;
cityTik = SAROV_TIK;
region = NIZHNY_NOVGOROD_REGION;
vybboryIzbirkomUrl = UIK_VYBORY_IZBIRKOM_RU_NNOV;
dbName = SAROV_DB_NAME;
break;
case "dubna":
cityUiks = DUBNA_UIKS;
cityTik = DUBNA_TIK;
region = MOSCOW_REGION;
vybboryIzbirkomUrl = UIK_VYBORY_IZBIRKOM_RU_MOSCOW_REGION;
dbName = DUBNA_DB_NAME;
break;
default:
resp = "Указан неверный город";
return Response.status(Response.Status.OK).entity(resp).build();
}
// TODO ТИК, адрес из uikAddress
// УИКи, адрес из votingRoomAddress
try {
String json = Jsoup.connect(cityUiks).ignoreContentType(true).get().text();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
StringBuilder sb = new StringBuilder();
List<UikMember> uikMembers = new ArrayList<>();
// 1. Получаем id и title с vybory.izbirkom.ru/region
List<Uik> uiks = gson.fromJson(json, new TypeToken<List<Uik>>(){}.getType());
List<ru.smartsarov.election.db.GeoAddress> geoAddresses = new ArrayList<>(uiks.size());
// // ТИК
// String jsonTik = Jsoup.connect(cityTik).ignoreContentType(true).get().text();
// Uik tik = gson.fromJson(jsonTik, Uik.class);
// uiks.add(0, tik);
int[] uikNumbers = new int[uiks.size()];
// 2. Делаем post-запрос на http://www.cikrf.ru/services/lk_address/?do=result_uik
for (int i = 0; i < uiks.size(); i++) {
String title = uiks.get(i).getTitle();
uikNumbers[i] = Integer.valueOf(title.substring(title.indexOf("№") + 1));
uiks.get(i).setUikNumber(uikNumbers[i]);
uiks.get(i).setCikUikHtml(Jsoup.connect(CIKRF_UIK_INFO_URL)
.data("uik", String.valueOf(uikNumbers[i]))
.data("subject", String.valueOf(region))
.post().toString());
uiks.get(i).setRequestUikNumber(String.valueOf(uikNumbers[i]));
String vyboryIzbirkomUikUrl = vybboryIzbirkomUrl + uiks.get(i).getVyboryIzbirkomUikId();
uiks.get(i).setVyboryIzbirkomUikUrl(vyboryIzbirkomUikUrl);
uiks.get(i).setVyboryIzbirkomUikHtml(Jsoup.connect(vyboryIzbirkomUikUrl).get().select(".center-colm").outerHtml());
parseCikUikHtml(uiks.get(i));
parseVyboryIzbirkomUikHtml(uiks.get(i), i + 1, uikMembers);
// TODO переделать ru.smartsarov.geocoder.GeoAddress
// Собираем данные geocoder'а
String address = uiks.get(i).getUikAddress();
address = address.substring(0, address.lastIndexOf(","));
ru.smartsarov.geocoder.GeoAddress geo = ru.smartsarov.geocoder.Geocoder.geoAddress(address, 1).get(0);
geoAddresses.add(new ru.smartsarov.election.db.GeoAddress(i + 1, geo.getRequestAddress(), geo.getFullAddress(), geo.getLat(), geo.getLng()));
uiks.get(i).setGeoAddressId(i + 1);
sb.append("insert into geo_address(request_address,full_address,lat,lng) values('" + geoAddresses.get(i).getRequestAddress().replace("'", "''") + "','" + geoAddresses.get(i).getFullAddress().replace("'", "''") + "'," + String.valueOf(geoAddresses.get(i).getLat()) + "," + String.valueOf(geoAddresses.get(i).getLng())).append(");");
sb.append("insert into uik(uik_number,tik_number,request_uik_number,uik_address,uik_phone,voting_room_address,voting_room_phone,geo_address_id,email,title,expiry_date,cik_uik_html,vybory_izbirkom_uik_id,vybory_izbirkom_uik_url,vybory_izbirkom_uik_html)"
+ " values(" + String.valueOf(uiks.get(i).getUikNumber()) + ",'" +
uiks.get(i).getTikNumber().replace("'", "''") + "','" +
uiks.get(i).getRequestUikNumber().replace("'", "''") + "','" +
uiks.get(i).getUikAddress().replace("'", "''") + "','" +
uiks.get(i).getUikPhone().replace("'", "''") + "','" +
uiks.get(i).getVotingRoomAddress().replace("'", "''") + "','" +
uiks.get(i).getVotingRoomPhone().replace("'", "''") + "'," +
String.valueOf(uiks.get(i).getGeoAddressId()) + "," +
(uiks.get(i).getEmail() == null ? "null" : ("'" + uiks.get(i).getEmail().replace("'", "''") + "'")) + ",'" +
uiks.get(i).getTitle().replace("'", "''") + "'," +
(uiks.get(i).getExpiryDate() == null ? "null" : ("'" + uiks.get(i).getExpiryDate().replace("'", "''") + "'")) + ",'" +
uiks.get(i).getCikUikHtml().replace("'", "''") + "','" +
uiks.get(i).getVyboryIzbirkomUikId().replace("'", "''") + "','" +
uiks.get(i).getVyboryIzbirkomUikUrl().replace("'", "''") + "','" +
uiks.get(i).getVyboryIzbirkomUikHtml().replace("'", "''") + "')").append(";");
}
// 4. Собираем sql-batch. Добавляем: UikMember
for (UikMember u : uikMembers) {
sb.append("insert into uik_member(uik_id,full_name,position,appointment) values(" + String.valueOf(u.getUikId()) + ",'" + u.getFullName() + "','" + u.getPosition() + "','" + u.getAppointment()).append("');");
}
// Записываем в таблицу uik_html
//List<String> sql = Arrays.asList(sb.toString().split(";"));
resp = String.valueOf(SQLiteDB.execute(dbName, sb.toString()));
} catch (IOException | ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
resp = e.getMessage();
e.printStackTrace();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
private List<Uik> getUiks(int region, int[] uikNumber) {
List<Uik> uiks = new ArrayList<>(uikNumber.length);
for (int i = 0; i < uikNumber.length; i++) {
Uik uik = new Uik();
try {
Document doc = Jsoup.connect(CIKRF_UIK_INFO_URL)
.data("uik", String.valueOf(uikNumber[i]))
.data("subject", String.valueOf(region))
.post();
uik.setRequestUikNumber(String.valueOf(uikNumber[i]));
if (!doc.select(".dotted p:eq(0)").text().equals(UIK_BAD_NUMBER_MESSAGE)) {
String[] p = { doc.select(".dotted p:eq(1)").text(), doc.select(".dotted p:eq(2)").text(), doc.select(".dotted p:eq(3)").text(), doc.select(".dotted p:eq(4)").text(), doc.select(".dotted p:eq(5)").text() };
uik.setUikNumber(Integer.valueOf(p[0].substring(p[0].indexOf("№") + 1, p[0].indexOf(" ", p[0].indexOf("№")))));
uik.setTikNumber(p[0].substring(p[0].length() - 3, p[0].length()));
uik.setUikAddress(getPTag(p[1]));
uik.setUikPhone(getPTag(p[2]));
uik.setVotingRoomAddress(getPTag(p[3]));
uik.setVotingRoomPhone(getPTag(p[4]));
/*GeoAddress geoAddress = Geocoder.geoAddress(uik.getUikAddress(), 1).get(0);
uik.setLat(geoAddress.getLat());
uik.setLng(geoAddress.getLng());
//uik.getGeoAddressId()*/
}
uiks.add(uik);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return uiks;
}
private String uiksToJsonString(int region, int[] uikNumbers) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
//gson.serializeNulls();
String uiksString = gson.toJson(getUiks(region, uikNumbers), new TypeToken<List<Uik>>(){}.getType());
return uiksString;
}
private void parseCikUikHtml(Uik uik) {
Document doc = Jsoup.parse(uik.getCikUikHtml());
if (!doc.select(".dotted p:eq(0)").text().equals(UIK_BAD_NUMBER_MESSAGE)) {
String[] p = { doc.select(".dotted p:eq(1)").text(), doc.select(".dotted p:eq(2)").text(), doc.select(".dotted p:eq(3)").text(), doc.select(".dotted p:eq(4)").text(), doc.select(".dotted p:eq(5)").text() };
uik.setTikNumber(p[0].substring(p[0].length() - 3, p[0].length()));
uik.setUikAddress(getPTag(p[1]));
uik.setUikPhone(getPTag(p[2]));
uik.setVotingRoomAddress(getPTag(p[3]));
uik.setVotingRoomPhone(getPTag(p[4]));
}
}
private void parseVyboryIzbirkomUikHtml(Uik uik, int uikId, List<UikMember> uikMembers) {
Document doc = Jsoup.parse(uik.getVyboryIzbirkomUikHtml());
String email = doc.select("p:eq(6)").text();
uik.setEmail((email.endsWith(":") ? null : email.substring(email.lastIndexOf(" ") + 1)));
String ed = doc.select("p:eq(7)").text();
uik.setExpiryDate(ed.substring(ed.lastIndexOf(" ") + 1));
// uik_members
//doc.select(".table.margtab p:eq(4)").text();
Element table = doc.select("table").get(0); //select the third table.
Elements rows = table.select("tr");
for (int i = 1; i < rows.size(); i++) { //first row is the col names, so skip it.
Element row = rows.get(i);
Elements cols = row.select("td");
uikMembers.add(new UikMember(uikId, cols.get(1).text(), cols.get(2).text(), cols.get(3).text()));
}
// TODO получить geoaddress с сайта VyboryIzbirkom
}
private String getPTag(String p) {
return p.substring(p.indexOf(":") + 2, p.length());
}
}
|
package com.isystk.sample.web.front.controller.api.v1.common;
import com.isystk.sample.common.dto.CodeValueDto;
import com.isystk.sample.common.dto.CodeValueGroupDto;
import com.isystk.sample.common.values.Prefecture;
import com.isystk.sample.common.values.Sex;
import com.isystk.sample.domain.repository.MPostTagRepository;
import com.isystk.sample.web.base.controller.api.AbstractRestController;
import com.isystk.sample.web.base.controller.api.resource.Resource;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.isystk.sample.common.Const.MESSAGE_SUCCESS;
import static com.isystk.sample.common.FrontUrl.API_V1_COMMON_CONST;
@RestController
@RequestMapping(path = API_V1_COMMON_CONST, produces = MediaType.APPLICATION_JSON_VALUE)
public class ConstRestController extends AbstractRestController {
@Autowired
MPostTagRepository mPostTagRepository;
@Override
public String getFunctionName() {
return "API_COMMON_CONST";
}
/**
* 定数取得します。
*
* @return
*/
@GetMapping
public Resource index() {
Resource resource = resourceFactory.create();
List<CodeValueGroupDto> list = Lists.newArrayList();
list.add(new CodeValueGroupDto("sex", Arrays.stream(Sex.values())
.map((values) -> {
CodeValueDto dto = new CodeValueDto();
dto.setText(values.getText());
dto.setCode(values.getCode());
return dto;
}
).collect(Collectors.toList())));
list.add(new CodeValueGroupDto("prefecture", Arrays.stream(Prefecture.values())
.map((values) -> {
CodeValueDto dto = new CodeValueDto();
dto.setText(values.getText());
dto.setCode(values.getCode());
return dto;
}
).collect(Collectors.toList())));
list.add(new CodeValueGroupDto("postTag", mPostTagRepository.findAllSelectList()));
resource.setData(list);
resource.setMessage(getMessage(MESSAGE_SUCCESS));
return resource;
}
}
|
package com.example.HelloConsul;
import javax.annotation.Generated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
//@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
//@EnableConfigurationProperties
@SpringBootApplication
@Generated({"Immutables.generator", "Registration.RegCheck"})
public class HelloConsulApplication {
//com.orbitz.consul.model.agent.ImmutableRegCheck i=new ImmutableRegCheck(null,null,null,null,null,null,null,null,null,null);
public static void main(String[] args) {
SpringApplication.run(HelloConsulApplication.class, args);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.