text stringlengths 10 2.72M |
|---|
/*
* 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 managedBeans;
import Helper.mailsend;
import facades.ProductFacade;
import facades.UserFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.http.HttpSession;
import models.Members;
import models.ProductOffer;
import models.Role;
import models.Users;
import models.Wishlist;
import org.mindrot.jbcrypt.BCrypt;
/**
*
* @author
*/
@ManagedBean
@SessionScoped
public class UserManagedBean implements Serializable {
@EJB
UserFacade userFacade;
private List<Users> usersList;
public List<Users> getUsersList() {
return usersList;
}
public void setUsersList(List<Users> usersList) {
this.usersList = this.userFacade.getAllUser();
}
private Users user;
private Users userRegister;
private String passwordValid;
public String getPasswordValid() {
return passwordValid;
}
public void setPasswordValid(String passwordValid) {
this.passwordValid = passwordValid;
}
public Users getUserRegister() {
return userRegister;
}
public void setUserRegister(Users userRegister) {
this.userRegister = userRegister;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
public UserFacade getUserFacade() {
return userFacade;
}
public void setUserFacade(UserFacade userFacade) {
this.userFacade = userFacade;
}
@PostConstruct
public void init() {
this.user = new Users();
this.userRegister = new Users();
this.usersList = this.userFacade.getAllUser();
}
@ManagedProperty(value = "#{wishListManagedBean}")
private WishListManagedBean wishListManagedBean;
public WishListManagedBean getWishListManagedBean() {
return wishListManagedBean;
}
public void setWishListManagedBean(WishListManagedBean wishListManagedBean) {
this.wishListManagedBean = wishListManagedBean;
}
public String login() {
//-- Password Validation
Users userTemp = this.userFacade.matchUser(this.user);
if (userTemp != null) {
this.user = userTemp;
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("user", userTemp);
if (this.user.getRoleId().getRole().trim().equals("client")) {
wishListManagedBean.setClient(this.userFacade.findClient(userTemp.getId()));
wishListManagedBean.setWishList(null);
return "index.xhtml";
} else if (this.user.getRoleId().getRole().trim().equals("member")) {
wishListManagedBean.setClient(null);
wishListManagedBean.setWishList(new ArrayList<Wishlist>());
return "/panel/panelMember/memberPanel.xhtml/login?faces-redirect=true";
} else if (this.user.getRoleId().getRole().trim().equals("admin")) {
wishListManagedBean.setClient(null);
wishListManagedBean.setWishList(new ArrayList<Wishlist>());
return "/panel/panelAdmin/adminPanel.xhtml/login?faces-redirect=true";
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Login Failed. Please try again..."));
}
return "";
}
private int role;
public int getRole() {
return role;
}
public void setRole(int role) {
this.role = role;
}
public String registerUser() throws AddressException, MessagingException {
if (this.userRegister.getPassword().equals(this.passwordValid)) {
//-- Set the rule
Role role = new Role();
role.setId(this.role);
role.setRole((this.role == 3) ? "client" : "member");
this.userRegister.setRoleId(role);
this.userRegister.setPassword(BCrypt.hashpw(this.passwordValid, BCrypt.gensalt()));
Users userTemp = this.userRegister;
//-- Email Message
String messageTemp = "Thank you for the registration on Cooperation site!\n "
+ "Your username : " + userTemp.getEmail() + "\n"
+ "Your Password : " + userTemp.getPassword();
if (userTemp != null) {
if (this.role == 3) {
boolean result = this.userFacade.registerUser(userTemp, "client");
if (!result) {
return "";
}
// mailsend mail = new mailsend();
// mail.sendmail(userTemp.getEmail(), messageTemp);
} else if (this.role == 2) {
boolean result = this.userFacade.registerUser(userTemp, "member");
if (!result) {
return "";
}
// mailsend mail = new mailsend();
// mail.sendmail(userTemp.getEmail(), messageTemp);
}
return "login.xhtml";
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Register Failed. Please try again..."));
}
return "";
}
public List<Members> fetchAllUnverifiedMembers() {
List<Members> usersTemp = this.userFacade.getAllMembers();
List<Members> membersTemp = new ArrayList<Members>();
for (Members users : usersTemp) {
if (users.getVerifiedByAdmin() == (short) 0) {
membersTemp.add(users);
}
}
return membersTemp;
}
public void memberVerify(Members member) {
member.setVerifiedByAdmin((short) 1);
this.userFacade.updateMember(member);
}
@EJB
ProductFacade productFacade;
public Members findMemberOwner(int productId) {
List<ProductOffer> productOffers = this.productFacade.getProductListOffer();
for (ProductOffer offer : productOffers) {
if (offer.getProductId().getId().equals(productId)) {
if (offer.getMemberId().getVerifiedByAdmin() == (short) 1) {
return offer.getMemberId();
}
}
}
return null;
}
public ProductFacade getProductFacade() {
return productFacade;
}
public void setProductFacade(ProductFacade productFacade) {
this.productFacade = productFacade;
}
public double memberProfit() {
double profit = 0;
Members member = this.userFacade.findMember(this.user.getId());
profit = member.getProfit();
return profit;
}
//NEW
public String forgotPassword(String email) throws AddressException, MessagingException {
Users user = userFacade.recoverPass(email);
if (user != null) {
String newpassword = UUID.randomUUID().toString();
user.setPassword(BCrypt.hashpw(newpassword, BCrypt.gensalt()));
System.out.println(newpassword);
if (userFacade.updateUser(user) == true) {
String messageTemp = "Your new password is " + newpassword;
mailsend mail = new mailsend();
mail.sendmail(user.getEmail(), messageTemp);
return "login.xhtml";
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Something went wrong. Please try again..."));
return "";
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Wrong email. Please try again..."));
return "";
}
}
}
|
package com.tencent.mm.plugin.appbrand.f;
import com.tencent.mm.plugin.fts.a.a;
public final class c extends a {
protected final void BR() {
if (BS()) {
t(-104, 2);
}
}
protected final String getTableName() {
return "WeApp";
}
public final String getName() {
return "FTS5WeAppStorage";
}
public final int getType() {
return 512;
}
public final int getPriority() {
return 512;
}
protected final boolean BS() {
return !cE(-104, 2);
}
}
|
package com.example.forwork;
public class Feedback {
private String commenter;
private String category;
private String comment;
private String date;
public Feedback(String commenter, String category, String comment, String date) {
setCommenter(commenter);
setCategory(category);
setComment(comment);
setDate(date);
}
public String getCommenter() {
return commenter;
}
public void setCommenter(String commenter) {
this.commenter = commenter;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
|
package ru.vssoft.backend.payload.response;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class LoginResponse {
private Long id;
private String token;
private String refreshToken;
private String username;
private List<String> roles;
public LoginResponse(String token, String refreshToken, Long id, String username, List<String> roles) {
this.id = id;
this.token = token;
this.refreshToken = refreshToken;
this.roles = roles;
this.username = username;
}
}
|
package cn.livejun.common.widget;
/**
* 基本的反馈组件
* Created by H.K on 2016/3/17 0017.
*/
public class BaseFeedBack {
}
|
package com.pfchoice.springboot.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import com.pfchoice.springboot.model.ICDMeasure;
public interface ICDMeasureService {
ICDMeasure findById(Integer id);
ICDMeasure findByCode(String code);
void saveICDMeasure(ICDMeasure icdMeasure);
void updateICDMeasure(ICDMeasure icdMeasure);
void deleteICDMeasureById(Integer id);
void deleteAllICDMeasures();
List<ICDMeasure> findAllICDMeasures();
Page<ICDMeasure> findAllICDMeasuresByPage(Specification<ICDMeasure> spec, Pageable pageable);
boolean isICDMeasureExist(ICDMeasure icdMeasure);
} |
package ak;
import java.util.*;
public class first {
public static void main(String...args){
int i = 0,x=0,d;
String s;
char r;
Scanner arun=new Scanner(System.in);
s=arun.nextLine();
char[] ch=s.toCharArray();
int c=ch.length;
if(c%2==0){
for(i=0;i<ch.length;i+=2){
if(ch[i]>=65&&ch[i]<=90){
d=ch[i]-64;
r=(char)(d+63);
System.out.println((char) r);
d=ch[i+1]-64;
r=(char)(d+65);
System.out.println((char)r);
}
}
}
else{
for(i=0;i<c-1;i+=2){
if(ch[i]>=65&&ch[i]<=90){
d=ch[i]-64;
r=(char)(d+63);
System.out.println((char) r);
d=ch[i+1]-64;
r=(char)(d+65);
System.out.println((char)r);
}
}
d=ch[i]-64;
r=(char)(d+63);
System.out.println((char) r);
}
}
}
|
/*******************************************************************************
* Copyright 2020 Grégoire Martinetti
*
* 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 org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.impls;
import java.util.stream.Stream;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonValue;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializableObjectBuilder;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.serialization.SerializerProvider;
import org.gmart.lang.java.JavaPrimitives;
public class JsonSerializerProvider implements SerializerProvider<JsonValue> {
public static class JsonSerializableObjectBuilder implements SerializableObjectBuilder<JsonValue> {
private final JsonObjectBuilder objectBuilder;
public JsonSerializableObjectBuilder() {
super();
this.objectBuilder = Json.createObjectBuilder();
}
@Override
public void addProperty(String name, JsonValue value) {
objectBuilder.add(name, value);
}
@Override
public JsonObject build() {
return objectBuilder.build();
}
}
@Override
public SerializableObjectBuilder<JsonValue> makeObjectSerializer() {
return new JsonSerializableObjectBuilder();
}
@Override
public JsonValue makeSerializablePrimitive(Object toSerialize, int primitiveIndex) {
return JavaPrimitives.modelValueToJsonValue_converters.get(primitiveIndex).apply(toSerialize);
}
@Override
public JsonValue makeSerializableString(String str) {
return Json.createValue(str);
}
// @Override
// public JsonValue makeSerializableAnyValue(Object toSerialize) {
// return null;
// }
@Override
public JsonValue makeSerializableList(Stream<JsonValue> toSerialize) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
toSerialize.forEach(elem -> arrayBuilder.add(elem));
return arrayBuilder.build();
}
}
|
package com.powercoder.evaluation.dao;
import com.powercoder.evaluation.entity.BusinessConsulting;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author :Done
* @date :Created in 2020/3/18 23:10
* @description:公司预约产品演示的数据层
*/
@Mapper
public interface BusinessConsultingMapper {
int insertDetail(BusinessConsulting businessConsulting);
List<BusinessConsulting> selectByCond(
int companySizeId, int prodId, String businessName, int offset, int limit);
int findRows(int companySizeId, int prodId, String businessName);
}
|
package com.lubarov.daniel.data.table.sequential;
import com.lubarov.daniel.data.collection.Collection;
import com.lubarov.daniel.data.dictionary.KeyValuePair;
import com.lubarov.daniel.data.dictionary.functions.GetKeyFunction;
import com.lubarov.daniel.data.dictionary.functions.GetValueFunction;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.sequence.ImmutableArray;
import com.lubarov.daniel.data.sequence.ImmutableSequence;
import com.lubarov.daniel.data.set.ImmutableHashSet;
import com.lubarov.daniel.data.set.Set;
import com.lubarov.daniel.data.source.Source;
/**
* An immutable table backed by a simple array of key-value pairs.
*/
public final class ImmutableArrayTable<K, V>
extends AbstractImmutableSequentialTable<K, V> {
private final ImmutableSequence<KeyValuePair<K, V>> keyValuePairs;
private ImmutableArrayTable(ImmutableSequence<KeyValuePair<K, V>> keyValuePairs) {
this.keyValuePairs = keyValuePairs;
}
public static <K, V> ImmutableArrayTable<K, V> create() {
return new ImmutableArrayTable<>(ImmutableArray.create());
}
public static <K, V> ImmutableArrayTable<K, V> copyOf(
Iterable<KeyValuePair<K, V>> iterable) {
return new ImmutableArrayTable<>(ImmutableArray.copyOf(iterable));
}
@Override
public Set<K> getKeys() {
return ImmutableHashSet.copyOf(keyValuePairs.map(new GetKeyFunction<>()));
}
@Override
public boolean containsKey(K key) {
return !getValues(key).isEmpty();
}
@Override
public Collection<V> getValues(K key) {
Option<? extends Collection<KeyValuePair<K, V>>> optValues = keyValuePairs
.groupBy(new GetKeyFunction<>()).tryGetValue(key);
if (optValues.isEmpty())
return ImmutableArray.create();
return optValues.getOrThrow().map(new GetValueFunction<>());
}
@Override
public KeyValuePair<K, V> get(int index) {
return keyValuePairs.get(index);
}
@Override
public Source<KeyValuePair<K, V>> getEnumerator() {
return keyValuePairs.getEnumerator();
}
@Override
public int getSize() {
return keyValuePairs.getSize();
}
}
|
package dk.aau.controllers.sygehus;
import dk.aau.App;
import dk.aau.models.patient.GenerelinfoHandler;
import dk.aau.models.patient.Patientinformation;
import dk.aau.models.database.DatabaseManipulator;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
public class SearchPatientCtrl {
private App mainApp;
private String selectedDirection;
@FXML
private TextField CPRnummerTextField;
@FXML
void handleEnterBtn(ActionEvent event) {
/*
if (!CPRnummerTextField.getText().isEmpty()){
try{
long i = Long.parseLong(CPRnummerTextField.getText().trim());
if (CPRnummerTextField.getText().length() == 10){
GenerelinfoHandler generelinfoClinicalSuiteDB = new GenerelinfoHandler("ClinicalSuiteDB");
DatabaseManipulator.executeQueryWithResultSet(generelinfoClinicalSuiteDB, "SELECT * FROM `ClinicalSuiteDBGenerelInformation` WHERE `CPR-nummer` ='"+ CPRnummerTextField.getText() +"'");
GenerelinfoHandler generelinfoTemporyDB = new GenerelinfoHandler("TemporyDB");
DatabaseManipulator.executeQueryWithResultSet(generelinfoTemporyDB, "SELECT * FROM `TemporyDBGenerelInformation` WHERE `CPR-nummer` ='"+ CPRnummerTextField.getText() +"'");
if(generelinfoClinicalSuiteDB.getSizeOfGenerelinfoListe() !=0) {
System.out.println("size of CS DB " + generelinfoClinicalSuiteDB.getSizeOfGenerelinfoListe()); // <<-------
if(selectedDirection.equals("opret")){
if(generelinfoTemporyDB.getSizeOfGenerelinfoListe() == 0) {
System.out.println("size of T DB " + generelinfoTemporyDB.getSizeOfGenerelinfoListe()); // <<-------
Patientinformation patient = new Patient();
patient.setGenerelinfoClinicalSuiteDB(generelinfoClinicalSuiteDB.getGenerelinfoListe(0));
mainApp.showShowCreateEdit(patient, selectedDirection);
}else showAlertBox("Indtastet patient CPR nummer har allerede faaet tilsendt praebooking skema");
}else if(selectedDirection.equals("tilgaa")){
if(generelinfoTemporyDB.getSizeOfGenerelinfoListe() != 0) {
if(generelinfoTemporyDB.getGenerelinfoListe(0).getSkemaUdfyld().equals("true")){
Patient patient = new Patient();
patient.setGenerelinfoClinicalSuiteDB(generelinfoClinicalSuiteDB.getGenerelinfoListe(0));
patient.setGenerelInfoTemporyDB(generelinfoTemporyDB.getGenerelinfoListe(0));
mainApp.showShowCreateEdit(patient, selectedDirection);
} else showAlertBox("Patient har ikke svaret på praebooking-skema endnu");
}else showAlertBox("Intet praebooking-skema er sendt til patient CPR nummer");
}
}else showAlertBox("Indtastet CPR nummer eksistere ikke i Databasen");
}else {
showAlertBox("Indtastede CPR input har forkert laengde");
}
}catch (NumberFormatException nfe){
showAlertBox("Indtastet CPR input maa ikke indeholde bogstaver");
}
}else showAlertBox("Intet CPR nummer indtastet");
*/
}
public void showAlertBox(String str){
Alert alert = new Alert(AlertType.WARNING);
alert.initOwner(mainApp.getPrimaryStage());
alert.setTitle("ERROR");
alert.setHeaderText(str);
alert.setContentText("Prøv venligst igen, hvis det ikke virker, ring 64987897");
alert.showAndWait();
}
@FXML
void handlerTilbageBnt(ActionEvent event) {
mainApp.ShowScheme();
}
public void setReference(App mainApp, String selectedDirection){
this.mainApp = mainApp;
this.selectedDirection = selectedDirection;
}
}
|
package com.yunhe.billmanagement.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
* 客户应收欠款表(ymy)
* </p>
*
* @author 杨明月
* @since 2019-01-02
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("fund_client_debt")
public class FundClientDebt implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
/**
* 客户编号
*/
@TableField(value = "fcd_num_list")
private String fcdNumList;
/**
* 客户名称
*/
@TableField(value = "fcd_name")
private String fcdName;
/**
* 联系人
*/
@TableField(value = "fcd_linkman")
private String fcdLinkman;
/**
* 联系电话
*/
@TableField(value = "fcd_telephone")
private String fcdTelephone;
/**
* 期初欠款
*/
@TableField(value = "fcd_begin_debt")
private Double fcdBeginDebt;
/**
* 增加应收欠款
*/
@TableField(value = "fcd_add_debt")
private Double fcdAddDebt;
/**
* 收回欠款
*/
@TableField(value = "fcd_back_debt")
private Double fcdBackDebt;
/**
* 优惠
*/
@TableField(value = "fcd_discount")
private Double fcdDiscount;
/**
* 核销欠款
*/
@TableField(value = "fcd_offset_deb")
private Double fcdOffsetDeb;
/**
* 应收欠款
*/
@TableField(value = "fcd_receivable")
private Double fcdReceivable;
public FundClientDebt() {
}
}
|
package com.GFT.casadeshow.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.GFT.casadeshow.model.User;
public interface Users extends JpaRepository<User, Long> {
}
|
package cn.tedu.note.service;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.tedu.note.dao.UserDao;
import cn.tedu.note.entity.User;
@Service("userService")
public class UserServiceImpl implements UserService{
@Resource private UserDao userDao;
@Transactional
public User login(String username,String password) {
User user = userDao.findUserByName(username);
if(user==null) {
throw new RuntimeException("用户名不存在");
}
if(user.getPassword().equals(password)) {
return user;
}
throw new RuntimeException("密码错误");
}
@Transactional
public List<Map<String,Object>> listUsers(String name){
if(name==null || name.trim().isEmpty()) {//或运算两边的表达式不能交换顺序,当name为空的时候,name.trim()就可能出现空指针异常
throw new RuntimeException("参数不能为空");
}
return userDao.findUsersLikeName(name);
}
}
|
package com.example.demo.service.Impl;
import com.example.demo.Dao.ILuceneDao;
import com.example.demo.entity.Project;
import com.example.demo.mapper.ProjectMapper;
import com.example.demo.service.IProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProjectService implements IProjectService {
@Autowired
private ProjectMapper mapper;
@Autowired
private ILuceneDao luceneDao;
@Override
public Project getProjectById(String id) {
return mapper.getProjectById(id);
}
@Override
public List<Project> getAllProject() {
return mapper.getAllProject();
}
}
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
public class delListener implements ActionListener {
public ChoosePanel cPanel;
public JTextField tf;
private String src;
delListener(ChoosePanel cPanel,JTextField tf){
this.cPanel=cPanel;
this.tf=cPanel.tf;
}
@Override
public void actionPerformed(ActionEvent e) {
src=tf.getText();
if((src!=null)){
try{
File file = new File(src);
file.delete();
JOptionPane.showMessageDialog(new JFrame(),file.getName()+"is deleted!");
}catch(Exception e1){
JOptionPane.showMessageDialog(new JFrame(),"Error! Try again, please!");
e1.printStackTrace();
}
}else JOptionPane.showMessageDialog(new JFrame(),"Error! Choose a file!");
}
}
|
package LightProcessing.common.tile;
import LightProcessing.common.lib.*;
import net.minecraft.tileentity.TileEntity;
public class TileEntityDarkGen extends TileEntity {
public void updateEntity() {
if (this.worldObj.getBlockMetadata(this.xCoord, this.yCoord, this.zCoord) == 1) {
for (int i = -10; i < 10; i++) {
for (int j = 0; j < 10; j++) {
for (int k = -10; k < 10; k++) {
if (this.worldObj.isAirBlock(this.xCoord + k, this.yCoord + j, this.zCoord + i)) {
this.worldObj.setBlock(this.xCoord + k, this.yCoord + j, this.zCoord + i, IDRef.DARK_BLOCK_ID, 2, 2);
}
}
}
}
}
}
} |
package net.hackdog.graphble;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import net.hackdog.minimalble.R;
import java.util.HashMap;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
public static final boolean DEBUG = false;
private static final String MATCHBOX = "MatchBox";
private static final int REQUEST_PERMISSIONS = 100;
private static final int REQUEST_ENABLE_BT = 101;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int CHANNEL_IDS[] =
{ R.id.channel0, R.id.channel1, R.id.channel2, R.id.channel3 };
private final static HashMap<String, Integer> mChannelMap;
private Intent SERVICE_INTENT;
private GraphView mChannels[] = new GraphView[CHANNEL_IDS.length];
private Button mScanButton;
BleService mService;
static {
mChannelMap = new HashMap<>();
mChannelMap.put("6ff90100-b2be-4f02-bbd8-e795ca3ca70c", 0);
mChannelMap.put("6ff90101-b2be-4f02-bbd8-e795ca3ca70c", 1);
mChannelMap.put("6ff90102-b2be-4f02-bbd8-e795ca3ca70c", 2);
mChannelMap.put("6ff90103-b2be-4f02-bbd8-e795ca3ca70c", 3);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < CHANNEL_IDS.length; i++) {
mChannels[i] = (GraphView) findViewById(CHANNEL_IDS[i]);
mChannels[i].setLabel("Channel " + i);
mChannels[i].setValue("off");
}
mScanButton = (Button) findViewById(R.id.scan_button);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.GONE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
fab.setVisibility(View.GONE);
SERVICE_INTENT = new Intent(this, BleService.class);
if (savedInstanceState == null) {
// Check permissions before starting
checkPermissions();
} else {
startService();
}
}
void startService() {
if (DEBUG) Log.v(TAG, "Starting service");
// Keep the service running during device rotations
startService(SERVICE_INTENT);
// Bind to it
if (!bindService(SERVICE_INTENT, mConnection, Context.BIND_AUTO_CREATE)) {
Log.w(TAG, "Failed to start service");
}
}
// TODO: stop service when we leave the activity
ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
if (DEBUG) Log.v(TAG, "Service connected, yay!");
BleService.LocalBinder binder = (BleService.LocalBinder) service;
mService = binder.getService();
mService.registerCallback(mBleServiceCallback);
maybeStartScanning();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
if (DEBUG) Log.v(TAG, "Service disconnected, boo!");
mService = null;
}
};
private void maybeStartScanning() {
if (!mService.isConnected() && !mService.isScanning()) {
mService.startScan(MATCHBOX);
}
}
@Override
protected void onPause() {
super.onPause();
if (mService != null) {
mService.unregisterCallback(mBleServiceCallback);
if (mService.isScanning()) {
mService.stopScan();
}
unbindService(mConnection);
}
}
@Override
protected void onResume() {
super.onResume();
startService();
}
protected void onStop() {
super.onStop();
if (!isChangingConfigurations()) {
// Don't leave the service running
//stopService(SERVICE_INTENT);
//finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onRequestPermissionsResult(
int requestCode, String permissions[], int[] grantResults) {
boolean granted = true; // assume true until we find otherwise
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
boolean isGranted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
if (DEBUG) Log.v(TAG, "Permission " + (isGranted ? "granted" : "denied")
+ permissions[i]);
if (!isGranted) granted = false;
}
if (granted) {
startService();
}
}
}
}
}
private void checkPermissions() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH)
|| ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
// show permission info dialog TODO
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.BLUETOOTH,
Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSIONS);
}
}
final int HISTORY = 1000;
byte[][] mData = {null, null, null, null};
int mIndex[] = {0,0,0,0};
BleServiceCallback mBleServiceCallback = new BleServiceCallback() {
@Override
public void onCharacteristicChanged(UUID uuid, byte[] data) {
String sUuid = uuid.toString();
if (mChannelMap.containsKey(sUuid)) {
int chan = mChannelMap.get(sUuid);
if (mData[chan] == null) {
mData[chan] = new byte[HISTORY];
}
for (int i = 2; i < data.length; i++) {
mData[chan][(mIndex[chan]++)%HISTORY] = data[i];
// if (mIndex[chan] >= HISTORY) {
// mIndex[chan] = 0;
// }
}
mChannels[chan].setData(mData[chan]);
} else {
// probably settings
Log.w(TAG, "not handling uuid " + uuid.toString());
}
}
@Override
public void onCharacteristicRead(UUID uuid, byte[] data) {
}
@Override
public void onConnectionStateChanged(int state) {
final String msg;
final boolean enabled;
switch (state) {
case STATE_CONNECTING:
msg = "Connecting...";
enabled = false;
break;
case STATE_CONNECTED:
msg = "Connected";
enabled = false;
break;
case STATE_DISCONNECTED:
msg = "Disconnected";
enabled = true;
break;
case STATE_SCANNING:
msg = "Scanning...";
enabled = false;
break;
case STATE_SCAN_COMPLETE:
msg = "Complete";
enabled = false;
break;
case STATE_SCAN_FAILED:
msg = "Scan";
enabled = true;
break;
default:
msg = "";
enabled = true;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
mScanButton.setText(msg);
mScanButton.setEnabled(enabled);
}
});
}
};
}
|
package com.example.geofence;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static com.example.geofence.R.id.listView;
/**
* App starts from here.
* It shows screen of this activity if list of locations is not empty,
* or goes to MapActivity
*/
public class StartActivity extends AppCompatActivity {
final String TAG = "StartActivity";
LocationData selectedLocationData;
ArrayList<LocationData> locationDataList = new ArrayList<>();
InternalStorage internalStorage;
// This class is used to provide alphabetic sorting for LocationData list
class CustomAdapter extends ArrayAdapter<LocationData> {
public CustomAdapter(Context context, ArrayList<LocationData> locationDataArrayList) {
super(context, R.layout.row_layout, locationDataArrayList);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myInflater = LayoutInflater.from(getContext());
View theView = myInflater.inflate(R.layout.row_layout, parent, false); // Last two arguments are significant if we inflate this into a parent.
String cline = getItem(position).getName();
TextView myTextView = (TextView) theView.findViewById(R.id.customTextView);
myTextView.setText(cline);
return theView;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate started");
super.onCreate(savedInstanceState);
internalStorage = new InternalStorage();
internalStorage.setContext(this);
locationDataList = internalStorage.readLocationDataList();
Log.v(TAG, "onCreate, locationDataList" + locationDataList);
if (locationDataList.size() == 0) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
} else {
setContentView(R.layout.activity_start);
final ArrayAdapter myAdapter = new CustomAdapter(this, locationDataList);
ListView listView = (ListView) findViewById(R.id.listView);
Collections.sort(locationDataList, new Comparator<LocationData>() {
/* This comparator sorts LocationData objects alphabetically. */
@Override
public int compare(LocationData a1, LocationData a2) {
// String implements Comparable
return (a1.getName()).compareTo(a2.getName());
}
});
listView.setAdapter(myAdapter);
final ListView myListView2 = listView;
myListView2.setOnItemClickListener(new AdapterView.OnItemClickListener() { // Dobavlenij kod 21.02,2017
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectedLocationData = (LocationData) myAdapter.getItem(i);
Toast.makeText(StartActivity.this, "Alarm '" + selectedLocationData.getName() + "' is set", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(StartActivity.this, MapsActivity.class);
myIntent.putExtra(InternalStorage.SEL_LOC_DATA_KEY, selectedLocationData);
Log.i("StartActivity", selectedLocationData.getName() + " is selected");
startActivity(myIntent);
}
});
myListView2.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
AlertDialog.Builder alert = new AlertDialog.Builder(StartActivity.this);
alert.setMessage("Are you sure you want to delete this?");
alert.setCancelable(false);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
locationDataList.remove(i);
myAdapter.notifyDataSetChanged();
internalStorage.writeLocationDataList(locationDataList);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
return true;
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu); // More on this line: http://stackoverflow.com/questions/10303898/oncreateoptionsmenu-calling-super
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
Intent intent;
switch (item.getItemId()) {
case R.id.menuItemSettings:
intent = new Intent(this, PreferencesActivity.class);
this.startActivity(intent);
return true;
case R.id.menuItemHelp:
intent = new Intent(this, HelpActivity.class);
this.startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void toMap(@SuppressWarnings("unused") View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
}
|
package com.bean;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
@Data
@Entity
@Table(name = "t_sys_set")
public class SysSet implements Serializable {
@Id
@Column(name = "set_id")
private Integer setId;
@Column(name = "check_max_day_num")
private Integer checkMaxDayNum;
@Column(name = "gh_if_msg_push")
private Byte ghIfMsgPush;
@Column(name = "msg_num")
private Integer msgNum;
@Column(name = "server_ip")
private String serverIp;
@Column(name = "holidays")
private String holidays;
@Column(name = "register_max_day_num")
private Integer registerMaxDayNum;
}
|
package com.wincentzzz.project.template.springhack.mapper;
import com.wincentzzz.project.template.springhack.dto.request.AppointmentMedicineRequest;
import com.wincentzzz.project.template.springhack.models.Appointment;
import com.wincentzzz.project.template.springhack.models.AppointmentMedicine;
import com.wincentzzz.project.template.springhack.models.Medicine;
public class AppointmentMedicineMapper {
public static AppointmentMedicine toAppointmentMedicine(AppointmentMedicineRequest appointmentMedicineRequest){
return AppointmentMedicine.builder()
.appointment(Appointment.builder()
.id(appointmentMedicineRequest.getAppointmentId())
.build())
.medicine(Medicine.builder()
.id(appointmentMedicineRequest.getMedicineId())
.build())
.weight(appointmentMedicineRequest.getWeight())
.build();
}
}
|
package com.tencent.mm.ui.widget.textview;
import android.content.Context;
import android.text.Layout;
import android.text.Spannable;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import com.tencent.mm.ui.ap;
import com.tencent.mm.ui.base.c;
public final class a {
public boolean ccw = true;
TextView ih;
Context mContext;
OnScrollChangedListener uOY;
public b uOZ;
public b uPa;
d uPb = new d(this);
public c uPc;
Spannable uPd;
com.tencent.mm.ui.widget.b.a uPe;
int uPf;
int uPg;
private int uPh;
int uPi;
int uPj;
private c uPk;
boolean uPl;
OnPreDrawListener uPm;
private int[] uPn = new int[2];
final Runnable uPo = new 1(this);
static /* synthetic */ b a(a aVar, boolean z) {
return b.b(aVar.uOZ) == z ? aVar.uOZ : aVar.uPa;
}
public a(a aVar) {
this.ih = aVar.ih;
this.uPe = aVar.uPq;
this.mContext = this.ih.getContext();
this.uPh = aVar.uPh;
this.uPi = aVar.uPi;
this.uPj = ap.fromDPToPix(this.mContext, aVar.uPr);
this.ih.setText(this.ih.getText(), BufferType.SPANNABLE);
this.ih.setOnLongClickListener(new 2(this));
this.ih.setOnTouchListener(new 3(this));
this.ih.setOnClickListener(new 4(this));
this.ih.addOnAttachStateChangeListener(new 5(this));
this.uPm = new 6(this);
this.ih.getViewTreeObserver().addOnPreDrawListener(this.uPm);
this.uOY = new 7(this);
this.ih.getViewTreeObserver().addOnScrollChangedListener(this.uOY);
}
public final void cBn() {
this.ccw = true;
if (this.uOZ != null) {
this.uOZ.uPs.dismiss();
}
if (this.uPa != null) {
this.uPa.uPs.dismiss();
}
if (this.uPe != null) {
this.uPe.ctb();
}
}
public final void cBo() {
this.uPb.uPz = null;
if (this.uPd != null && this.uPk != null) {
this.uPd.removeSpan(this.uPk);
this.uPk = null;
}
}
public final void a(b bVar) {
int lineBaseline;
int i;
Layout layout = this.ih.getLayout();
int i2 = b.b(bVar) ? this.uPb.Tw : this.uPb.tK;
if (layout != null) {
lineBaseline = ((int) layout.getPaint().getFontMetrics().descent) + layout.getLineBaseline(layout.getLineForOffset(i2));
i2 = (int) layout.getPrimaryHorizontal(i2);
} else {
i2 = 0;
lineBaseline = 0;
}
bVar.uPp.ih.getLocationInWindow(bVar.uPy);
if (bVar.uPt) {
i = bVar.mWidth;
} else {
i = 0;
}
if (!bVar.uPt) {
int[] fq = bVar.fq(i2, lineBaseline);
i2 = fq[0];
lineBaseline = fq[1];
}
bVar.uPs.showAtLocation(bVar.uPp.ih, 0, (i2 - i) + bVar.getExtraX(), lineBaseline + bVar.getExtraY());
}
public final void cBp() {
int i = 16;
if (this.uPe != null) {
this.ih.getLocationInWindow(this.uPn);
Layout layout = this.ih.getLayout();
int primaryHorizontal = ((int) layout.getPrimaryHorizontal(this.uPb.Tw)) + this.uPn[0];
int lineTop = (layout.getLineTop(layout.getLineForOffset(this.uPb.Tw)) + this.uPn[1]) - 16;
if (primaryHorizontal <= 0) {
primaryHorizontal = 16;
}
if (lineTop >= 0) {
i = lineTop;
}
if (primaryHorizontal > b.getScreenWidth(this.mContext)) {
lineTop = b.getScreenWidth(this.mContext) - 16;
} else {
lineTop = primaryHorizontal;
}
this.uPe.bU(lineTop, i);
}
}
public final void fp(int i, int i2) {
if (i != -1) {
this.uPb.Tw = i;
}
if (i2 != -1) {
this.uPb.tK = i2;
}
if (this.uPb.Tw > this.uPb.tK) {
int i3 = this.uPb.Tw;
this.uPb.Tw = this.uPb.tK;
this.uPb.tK = i3;
}
if (this.uPd != null) {
this.uPb.uPz = this.uPd.subSequence(this.uPb.Tw, this.uPb.tK).toString();
if (this.uPk == null) {
this.uPk = new c(this.ih, this.mContext.getResources().getColor(this.uPh), this.uPb.Tw, this.uPb.tK);
}
if (this.uPk != null) {
c cVar = this.uPk;
int i4 = this.uPb.Tw;
int i5 = this.uPb.tK;
cVar.start = i4;
cVar.end = i5;
}
Layout layout = this.ih.getLayout();
this.uPd.setSpan(this.uPk, layout.getLineStart(layout.getLineForOffset(this.uPb.Tw)), this.uPb.tK, 17);
if (this.uPc != null) {
this.uPc.O(this.uPb.uPz);
}
}
}
}
|
package com.example.nata.hallimane;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Random;
import static com.example.nata.hallimane.UrlClass.email_verfication;
public class ForgotPasswordMail extends AppCompatActivity {
EditText F_email;
Button otp;
public static final String ALLOWED_CHARACTERS="0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM*$%#";
long backPressedTime = 0;
public static String emailSenderToUpdatePassword="";
// flag for Internet connection status
Boolean isInternetPresent = false;
static long internetvalue = 1;
// Connection detector class
ConnectionDetector cd;
GMailSender sender;
String sub = " ";
public static String y = "";
public static String emailstr ="";
public static String code = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password_mail);
View BackgroundImage = findViewById(R.id.activity_forgot_password_mail);
Drawable background = BackgroundImage.getBackground();
background.setAlpha(200);
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// Add your mail Id and Password
sender = new GMailSender("botsattendance@gmail.com", "natraj31195");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.
Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
F_email = (EditText)findViewById(R.id.forgotPasswordMail);
}
public void invokeOTP(View view){
emailstr =F_email.getText().toString().trim();
emailSenderToUpdatePassword=emailstr;
if (emailSenderToUpdatePassword!=null &&!emailstr.isEmpty()){
//Toast.makeText(getBaseContext(),emailstr+" is registered already",Toast.LENGTH_SHORT).show();
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
internetvalue = 1;
CheckEmailExistance(emailstr);
// showAlertDialog(ForgotEmailCode.this, "Internet Connection","You have internet connection", true);
}else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(ForgotPasswordMail.this, "No Internet Connection",
"You don't have internet connection.", false);
internetvalue = 0;
}
}else {
Toast.makeText(getBaseContext(),"Please Enter email", Toast.LENGTH_SHORT).show();
}
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,"OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
class MyAsyncClass extends AsyncTask<Void, Void, Void> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ForgotPasswordMail.this);
pDialog.setCanceledOnTouchOutside(false);
pDialog.setMessage("Please wait...");
pDialog.show();
}
@Override
protected Void doInBackground(Void... mApi) {
try {
// Add subject, Body, your mail Id, and receiver mail Id.
sender.sendMail("Password Reset",code, "botsattendance@gmail.com",sub);
//long lalle = 0 ;
}
catch (Exception ex) {}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.cancel();
if (internetvalue == 1){
Toast.makeText(getApplicationContext(), "Email sent to "+emailstr, Toast.LENGTH_LONG).show();
//startActivity(new Intent(ForgotPasswordActivity.this, OtpActivity.class));
F_email.setText(null);
startActivity(new Intent(ForgotPasswordMail.this,OtpActivity.class));
}else
Toast.makeText(getApplicationContext(), "Email not sent", Toast.LENGTH_SHORT).show();
}
}
public static String random(final int sizeofRandomString){
final Random rand =new Random();
final StringBuilder sb =new StringBuilder(sizeofRandomString);
for (int i =0;i<sizeofRandomString;i++)
sb.append(ALLOWED_CHARACTERS.charAt(rand.nextInt(ALLOWED_CHARACTERS.length())));
return sb.toString();
}
public static String EMailSendToUpdatePassword(){
return emailSenderToUpdatePassword;
}
//code for email existance
public void CheckEmailExistance(String E_email){
class CheckEmailExistanceAsync extends AsyncTask<String,Void,String>{
private Dialog loadingDialog;
AlertDialog alertDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog=new AlertDialog.Builder(ForgotPasswordMail.this).create();
loadingDialog = ProgressDialog.show(ForgotPasswordMail.this,"Please wait","Loading...");
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
alertDialog.setTitle("Email Verification");
alertDialog.setCanceledOnTouchOutside(false);{
if (result.equals("success")){
loadingDialog.dismiss();
sub = F_email.getText().toString();
try {
new MyAsyncClass().execute();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
//sending code ends
code =random(4);
}else{
loadingDialog.dismiss();
alertDialog.setMessage(result);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
}
@Override
protected String doInBackground(String... params) {
String email = params[0];
try {
URL url = new URL(email_verfication);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String email_veri_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8");
bufferedWriter.write(email_veri_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line="";
while ((line=bufferedReader.readLine())!=null){
response=line;
}
bufferedReader.close();
inputStream.close();
return response;
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
}
CheckEmailExistanceAsync CEXA = new CheckEmailExistanceAsync();
CEXA.execute(E_email);
}
public static String sendCode(){
return code;
}
@Override
public void onBackPressed() { // to prevent irritating accidental logouts
long t = System.currentTimeMillis();
if (t - backPressedTime > 2000) { // 2 secs
backPressedTime = t;
startActivity(new Intent(getApplicationContext(),MainActivity.class));
} else {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
}
}
|
package online;
import Util.R;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by cuong on 11/22/2015.
*/
public class HttpConnectionMethods {
public static boolean postBestPlayer(String name, String facebookID, String score) {
String params = String.format(R.BEST_PLAYER_POST_PARAMS, name, facebookID, score);
try {
HttpURLConnection con = (HttpURLConnection) new URL(R.BEST_PLAYER_POST_URL).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozzila/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("charset", "utf-8");
// write post request
con.setDoOutput(true);
OutputStreamWriter stream = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
stream.write(params);
stream.flush();
stream.close();
return (con.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static String getBestPlayer() {
try {
HttpURLConnection con =
(HttpURLConnection) new URL(R.BEST_PLAYER_GET_URL + R.BEST_PLAYER_GET_PARAMS)
.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozzila/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* for reseting score of best player
*/
// public static void main(String args[]) {
// postBestPlayer("Hải tặc", "01241241241", "0");
// System.out.println(getBestPlayer());
// }
}
|
package Lab04.Zad2;
public class InterestA implements Interest{
@Override
public void compute() {
System.out.println("Computing interest A");
}
}
|
package com.emp.friskyplayer.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import com.emp.friskyplayer.R;
import com.emp.friskyplayer.utils.PlayerConstants;
public class WidgetUpdaterHelper {
private static WidgetUpdaterHelper instance = null;
private Context ctx;
protected WidgetUpdaterHelper(Context _ctx) {
this.ctx = _ctx;
}
public static WidgetUpdaterHelper getInstance(Context _ctx) {
if (instance == null) {
instance = new WidgetUpdaterHelper(_ctx);
}
return instance;
}
public void updateWidgetInfo(int state, String title) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(ctx);
ComponentName thisWidget = new ComponentName(ctx, WidgetProvider.class);
int[] ids = appWidgetManager.getAppWidgetIds(thisWidget);
for (int widgetId : ids) {
RemoteViews remoteViews = new RemoteViews(
this.ctx.getPackageName(), R.layout.widget_layout);
// Sets view values
remoteViews.setTextViewText(R.id.widgetTitleTextView,title);
if (state == PlayerConstants.STATE_STOPPED){
remoteViews.setImageViewResource(R.id.widgetPlayPauseImageView, R.drawable.ic_action_play);
}else{
remoteViews.setImageViewResource(R.id.widgetPlayPauseImageView, R.drawable.ic_action_pause);
}
// Register an onClickListener
Intent clickIntent = new Intent(this.ctx, WidgetProvider.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.widgetTitleTextView, pendingIntent);
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
|
package de.fhg.iais.roberta.worker;
import java.util.Collections;
import java.util.List;
import de.fhg.iais.roberta.bean.UsedMethodBean;
import de.fhg.iais.roberta.components.Project;
import de.fhg.iais.roberta.syntax.Phrase;
import de.fhg.iais.roberta.visitor.collect.AbstractUsedMethodCollectorVisitor;
import de.fhg.iais.roberta.visitor.collect.ICollectorVisitor;
/**
* Uses the {@link AbstractUsedMethodCollectorVisitor} to visit the current AST and collect all used methods. Data collected is stored in the
* {@link UsedMethodBean}.
*/
public abstract class AbstractUsedMethodCollectorWorker implements IWorker {
@Override
public final void execute(Project project) {
UsedMethodBean.Builder builder = new UsedMethodBean.Builder();
ICollectorVisitor visitor = this.getVisitor(builder);
Iterable<List<Phrase<Void>>> tree = project.getProgramAst().getTree();
for ( Iterable<Phrase<Void>> phrases : tree ) {
for ( Phrase<Void> phrase : phrases ) {
phrase.accept(visitor);
}
}
builder.addAdditionalEnums(this.getAdditionalMethodEnums());
UsedMethodBean bean = builder.build();
project.appendWorkerResult(bean);
}
/**
* Returns the appropriate visitor for this worker. Used by subclasses to keep the execute method generic. Could be removed in the future, when visitors are
* specified in the properties as well, or inferred from the worker name.
*
* @param builder the used hardware bean builder
* @return the appropriate visitor for the current robot
*/
protected abstract ICollectorVisitor getVisitor(UsedMethodBean.Builder builder);
/**
* Returns additional enums which should be added to the used method collection. Used by subclasses to keep the execute method generic.
*
* @return the additional enums required
*/
protected List<Class<? extends Enum<?>>> getAdditionalMethodEnums() {
return Collections.emptyList();
}
}
|
package final_exam;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Manager {
protected String [] menupan = {"순살 후라이드","양념 순살","간장 순살", "맥주 500cc","맥주 1000cc","음료수"};
protected int [] menu_howmany = {0,0,0,0,0,0};
protected static int [] price = {16000, 18000, 17000, 4000, 7000, 1000};
protected int [] sum;
protected static ArrayList<Manager> order = new ArrayList<Manager>();
int sunsal;
int yangnum;
int ganjang;
int beer_500;
int beer_1000;
int beberage;
int table_num;
int cash_finish;
String date;
Manager(String date,int sunsal , int yangnum , int ganjang , int beer_500, int beer_1000, int beberage,int table_num,int cash_finish){
this.date = date;
this.sunsal = sunsal;
this.yangnum = yangnum;
this.ganjang = ganjang;
this.beer_500 = beer_500;
this.beer_1000 = beer_1000;
this.beberage = beberage;
this.table_num = table_num;
this.cash_finish = cash_finish;
}
protected static int total_sum(int num){
int sum_1 = order.get(num).sunsal * price[0];
int sum_2 = order.get(num).yangnum * price[1];
int sum_3 = order.get(num).ganjang * price[2];
int sum_4 = order.get(num).beer_500 * price[3];
int sum_5 = order.get(num).beer_1000 * price[4];
int sum_6 = order.get(num).beberage * price[5];
return sum_1 + sum_2 + sum_3 + sum_4 + sum_5 + sum_6;
}
static void delete(int num, String date){
for(int i = 0; i < order.size(); i ++){
if(order.get(i).table_num == num && order.get(i).cash_finish == 0 && order.get(i).date.equals(date)){
String date_before = Manager.order.get(i).date;
int sunsal = Integer.parseInt(String.valueOf(Manager.order.get(i).sunsal));
int yangnum = Integer.parseInt(String.valueOf(Manager.order.get(i).yangnum));
int ganjang = Integer.parseInt(String.valueOf(Manager.order.get(i).ganjang));
int beer_500 = Integer.parseInt(String.valueOf(Manager.order.get(i).beer_500));
int beer_1000 = Integer.parseInt(String.valueOf(Manager.order.get(i).beer_1000));
int beberage = Integer.parseInt(String.valueOf(Manager.order.get(i).beberage));
int table_num_before = Integer.parseInt(String.valueOf(Manager.order.get(i).table_num));
Manager.order.remove(i);
Manager.order.add(i,new Manager(date_before, sunsal,yangnum,ganjang,beer_500,beer_1000,beberage,table_num_before,2));
break;
}
}
}
static void listadd(String date ,int sunsal , int yangnum , int ganjang , int beer_500, int beer_1000, int beberage, int table_num,int cash_finish){
order.add(new Manager(date,sunsal,yangnum,ganjang,beer_500, beer_1000, beberage, table_num,cash_finish));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Manager> manager = new ArrayList<Manager>();
}
public static void pay_ok(int table_num) {
// TODO Auto-generated method stub
for(int i = 0; i < Manager.order.size() ; i ++){
if(Manager.order.get(i).table_num == table_num){
if(Manager.order.get(i).cash_finish == 0){
String date = Manager.order.get(i).date;
int sunsal = Integer.parseInt(String.valueOf(Manager.order.get(i).sunsal));
int yangnum = Integer.parseInt(String.valueOf(Manager.order.get(i).yangnum));
int ganjang = Integer.parseInt(String.valueOf(Manager.order.get(i).ganjang));
int beer_500 = Integer.parseInt(String.valueOf(Manager.order.get(i).beer_500));
int beer_1000 = Integer.parseInt(String.valueOf(Manager.order.get(i).beer_1000));
int beberage = Integer.parseInt(String.valueOf(Manager.order.get(i).beberage));
int table_num_before = Integer.parseInt(String.valueOf(Manager.order.get(i).table_num));
Manager.order.remove(i);
Manager.order.add(i,new Manager(date, sunsal,yangnum,ganjang,beer_500,beer_1000,beberage,table_num_before,1));
break;
}
}
}
}
public static void modify(int table_num) {
for(int i = 0; i < Manager.order.size() ; i ++){
if(Manager.order.get(i).table_num == table_num){
if(Manager.order.get(i).cash_finish == 0){
Manager.order.remove(i);
break;
}
}
}
}
}
|
package net.mizucoffee.wiimote4j;
import java.util.EventListener;
/**
* OnBoardStateChangeListener
*
* @author KawakawaRitsuki
* @since 0.1
*/
public interface OnBoardStateChangeListener extends EventListener {
void onChanged(int status);
} |
package com.seemoreinteractive.seemoreinteractive.Model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class UserStoreTriggers implements Serializable {
private static final long serialVersionUID = 8L;
List<StoreTriggers> StoreTriggers;
public UserStoreTriggers() {
StoreTriggers = new ArrayList<StoreTriggers>();
}
public void add(StoreTriggers storeTriggers) {
StoreTriggers.add(storeTriggers);
}
public StoreTriggers getClientStores(String clientId) {
for (StoreTriggers storeTriggers : StoreTriggers) {
if (storeTriggers.getClientId() == clientId)
return storeTriggers;
}
return null;
}
public StoreTriggers getClientStoreList(String storeCode) {
for (StoreTriggers storeTriggers : StoreTriggers) {
if(storeTriggers.getStoreCode().equals(storeCode))
return storeTriggers;
}
return null;
}
public List<StoreTriggers> getAllUserStoresList(String storeCode) {
List<StoreTriggers> list = new ArrayList<StoreTriggers>();
for (StoreTriggers storeTriggers : StoreTriggers) {
if (storeTriggers.getStoreCode().equals(storeCode)){
list.add(storeTriggers);
}
}
return list;
}
public StoreTriggers getStores() {
for (StoreTriggers storeTriggers : StoreTriggers) {
return storeTriggers;
}
return null;
}
public int size() {
return StoreTriggers.size();
}
public List<StoreTriggers> list() {
return StoreTriggers;
}
public void mergeWithStores(UserStoreTriggers newStores) {
// TODO Auto-generated method stub
List<StoreTriggers> oldStores = new ArrayList<StoreTriggers>(StoreTriggers);
/*for (Visual oldVisual : oldVisuals) {
newVisuals.add(oldVisual);
}*/
oldStores.addAll(newStores.list());
//visuals = newVisuals.list();
StoreTriggers = oldStores;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package trash;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
/**
*
* @author emrah
*/
public class _TwitterTest {
public static void main(String[] args) {
try {
String oauth_signature_method = "HMAC-SHA1";
String oauth_consumer_key = "MJwqPRqoXyAVwerBStUvHA";
String uuid_string = UUID.randomUUID().toString();
uuid_string = uuid_string.replaceAll("-", "");
String oauth_nonce = uuid_string;
String oauth_timestamp = (new Long(new Date().getTime() / 1000)).toString();
String parameter_string = "oauth_consumer_key=" + oauth_consumer_key + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_version=1.0";
System.out.println("parameter_string=" + parameter_string);
String signature_base_string = "POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&" + URLEncoder.encode(parameter_string, "UTF-8");
System.out.println("signature_base_string=" + signature_base_string);
String oauth_signature = "";
try {
oauth_signature = computeSignature(signature_base_string, "NvC0i4BdNzk986LfGAhSyahMbYHeVZtapLNwz5kopsw&"); // note the & at the end. Normally the user access_token would go here, but we don't know it yet for request_token
System.out.println("oauth_signature=" + URLEncoder.encode(oauth_signature, "UTF-8"));
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
String authorization_header_string = "OAuth oauth_consumer_key=\"" + oauth_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\""
+ oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature, "UTF-8") + "\"";
System.out.println("authorization_header_string=" + authorization_header_string);
String oauth_token = "";
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("https://api.twitter.com/oauth/request_token");
httppost.setHeader("Authorization", authorization_header_string);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
oauth_token = responseBody.substring(responseBody.indexOf("oauth_token=") + 12, responseBody.indexOf("&oauth_token_secret="));
System.out.println("ResponseBody"+responseBody);
} catch (ClientProtocolException cpe) {
System.out.println(cpe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
} finally {
httpclient.getConnectionManager().shutdown();
}
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(_TwitterTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKey secretKey = null;
byte[] keyBytes = keyString.getBytes();
secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secretKey);
byte[] text = baseString.getBytes();
return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}
}
|
public class AircraftCarrier extends Ship{
} |
package com.cjw.server.service;
import com.cjw.server.pojo.AdminRole;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author cjw
* @since 2021-07-12
*/
public interface IAdminRoleService extends IService<AdminRole> {
}
|
package com.woohun.lang.String.ex1;
import java.util.Scanner;
public class NationSearch {
private Scanner sc;
public NationSearch() {
sc = new Scanner(System.in);
}
public Nation search(Nation[] nations) {
System.out.println("검색할 나라이름을 입력하세요.");
String NationName = sc.next();
Nation n = null;
for(int i=0;i<nations.length;i++) {
if(NationName.equals(nations[i].getName())) {
n=nations[i];
}
}
return n;
}
}
|
package com.sportingCenterWebApp.calendarservice.controller;
import com.sportingCenterWebApp.calendarservice.model.Subscription;
import com.sportingCenterWebApp.calendarservice.repo.SubscriptionRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserSubscriptionController {
private final SubscriptionRepository subscriptionRepository;
public UserSubscriptionController(SubscriptionRepository abbRepository) {
this.subscriptionRepository = abbRepository;
}
@GetMapping("/subscriptions")
public List<Subscription> getSubscriptions() {
return (List<Subscription>) subscriptionRepository.findAll();
}
}
|
package br.com.nozinho.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "perfil")
@NamedQueries({
@NamedQuery(name = "Perfil.findPerfisExceptAdm", query = "SELECT p FROM Perfil p WHERE p.nome <> 'ADMINISTRADOR'"),
@NamedQuery(name = "Perfil.findByIdFetchPermissao", query = "SELECT p from Perfil p LEFT JOIN FETCH p.permissoes WHERE p.id = :id")
})
public class Perfil extends Entidade {
/**
*
*/
private static final long serialVersionUID = 9145368379107176587L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idperfil")
private Long id;
@Column(name = "nome_perfil")
private String nome;
@Column(name = "status")
private boolean status;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
@JoinTable(name = "perfil_permissao", joinColumns = {@JoinColumn(name = "idperfil")}, inverseJoinColumns = {@JoinColumn(name = "idpermissao")})
private List<Permissao> permissoes;
@Override
public Serializable getId() {
return id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setId(Long id) {
this.id = id;
}
public List<Permissao> getPermissoes() {
if(permissoes == null){
permissoes = new ArrayList<>();
}
return permissoes;
}
public void setPermissoes(List<Permissao> permissoes) {
this.permissoes = permissoes;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Perfil other = (Perfil) obj;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
}
@Override
public String toString() {
return "Perfil [id=" + id + ", nome=" + nome + ", status=" + status
+ "]";
}
}
|
package com.lay.open_eventbus_compiler;
/**
* 常量类
*/
public class Constants {
// 注解处理器中支持的注解类型
public static final String SUBSCRIBER_ANNOTATION_TYPES = "com.lay.open_eventbus_annotation.Subscriber";
// APT生成类文件所属包名
public static final String PACKAGE_NAME = "packageName";
// APT生成类文件的类名
public static final String CLASS_NAME = "className";
// 所有事件订阅方法, 生成索引接口
public static final String SUBSCRIBERINFO_INDEX = "com.lay.open_eventbus_annotation.SubscriberInfoIndex";
// 全局属性名
public static final String FIELD_NAME = "SUBSCRIBER_INDEX";
// putIndex方法的参数对象名
public static final String PUTINDEX_PARAMETER_NAME = "info";
// 加入Map集合方法名
public static final String PUTINDEX_METHOD_NAME = "putIndex";
// getSubscriberInfo方法的参数对象名
public static final String GETSUBSCRIBERINFO_PARAMETER_NAME = "subscriberClass";
// 通过订阅者对象()获取所有订阅方法的方法名
public static final String GETSUBSCRIBERINFO_METHOD_NAME = "getSubscriberInfo";
} |
package com.company;
import palindrom.Sentence;
public class Main {
public static void main(String[] args) {
// write your code here
Sentence greeting = new Sentence("Hello!");
greeting.reverse();
System.out.println(greeting.getReverse());
Sentence greeting2 = new Sentence("Hello!");
greeting2.reverse2();
System.out.println(greeting2.getText());
}
}
|
package com.graphic.RNCanvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import java.util.ArrayList;
import java.util.HashMap;
public class CanvasConvert {
public static ArrayList<HashMap> convertActions(ReadableArray paramReadableArray) {
int j = paramReadableArray.size();
ArrayList<HashMap> arrayList = new ArrayList();
for (int i = 0; i < j; i++) {
try {
ReadableMap readableMap = paramReadableArray.getMap(i);
arrayList.add(createAction(readableMap.getString("method"), readableMap.getArray("arguments").toArrayList().toArray()));
} catch (Exception exception) {
exception.printStackTrace();
}
}
return arrayList;
}
public static int[] convertColor(float[] paramArrayOffloat) {
return (paramArrayOffloat.length != 4) ? new int[] { 255, 0, 0, 0 } : new int[] { (int)(paramArrayOffloat[3] * 255.0F), (int)(paramArrayOffloat[0] * 255.0F), (int)(paramArrayOffloat[1] * 255.0F), (int)(paramArrayOffloat[2] * 255.0F) };
}
public static int convertColorListToColor(int[] paramArrayOfint) {
return Color.argb(paramArrayOfint[0], paramArrayOfint[1], paramArrayOfint[2], paramArrayOfint[3]);
}
public static Paint.Cap convertLineCap(String paramString) {
Paint.Cap cap = Paint.Cap.BUTT;
if (paramString.equals("round"))
return Paint.Cap.ROUND;
if (paramString.equals("square"))
cap = Paint.Cap.SQUARE;
return cap;
}
public static DashPathEffect convertLineDash(float[] paramArrayOffloat, float paramFloat) {
int i;
float[] arrayOfFloat;
float f = paramArrayOffloat.length;
byte b = 0;
if (f % 2.0F != 0.0F) {
i = 1;
} else {
i = 0;
}
if (i) {
arrayOfFloat = new float[paramArrayOffloat.length * 2];
i = b;
} else {
arrayOfFloat = new float[paramArrayOffloat.length];
i = b;
}
while (i < arrayOfFloat.length) {
arrayOfFloat[i] = paramArrayOffloat[(int)(i % f)];
i++;
}
if (paramFloat <= 0.0F)
paramFloat = 0.0F;
return new DashPathEffect(arrayOfFloat, paramFloat);
}
public static Paint.Join convertLineJoin(String paramString) {
Paint.Join join = Paint.Join.MITER;
if (paramString.equals("bevel"))
return Paint.Join.BEVEL;
if (paramString.equals("round"))
join = Paint.Join.ROUND;
return join;
}
public static Paint.Align convertTextAlign(String paramString) {
Paint.Align align = Paint.Align.LEFT;
if (paramString.equals("right"))
return Paint.Align.RIGHT;
if (paramString.equals("center"))
align = Paint.Align.CENTER;
return align;
}
public static int convertTextBaseline(String paramString) {
return paramString.equals("top") ? 1 : (paramString.equals("middle") ? 2 : 0);
}
public static HashMap createAction(String paramString, Object[] paramArrayOfObject) {
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
hashMap.put("method", paramString);
hashMap.put("arguments", paramArrayOfObject);
return hashMap;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\graphic\RNCanvas\CanvasConvert.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package thuc_hanh;
public class IterativeBinarySearch {
public static void main(String[] args) {
int[] arr = {0,1,2,3,4,5,6,7,8,9};
int result = binarySearch(9, arr);
if (result == -1) System.out.println("not found");
else System.out.println("index: " + result );
}
public static int binarySearch(int x, int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (x == arr[mid]) return mid;
if (x > arr[mid]) left = mid + 1;
else right = mid - 1;
}
return -1;
}
}
|
package com.isystk.sample.common.exception;
/**
* アプリケーション内部で発生した例外を catch & throw するための実行時例外です。
*/
public class SystemException extends RuntimeException {
private static final long serialVersionUID = 8462188377363105093L;
/**
* @param message この例外に関する詳細な情報.
* @param cause 原因となった例外
*/
public SystemException(String message, Throwable cause) {
super(message, cause);
if ((message == null || message.trim().length() == 0) && cause == null) {
throw new IllegalArgumentException("Either of message or cause must be not null.");
}
}
/**
* メッセージを指定するコンストラクタ。
*
* @param message メッセージ
*/
public SystemException(String message) {
super(message);
}
/**
* 根源の例外を指定するコンストラクタ。
*
* @param cause 根源の例外
*/
public SystemException(Throwable cause) {
super(cause);
}
/*
* (non-Javadoc)
*
* @see java.lang.Throwable#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getClass().getName());
if (getCause() != null) {
sb.append(": ").append(getCause().getClass().getName());
}
String message = getLocalizedMessage();
if (message != null) {
sb.append(": ").append(message);
}
return sb.toString();
}
}
|
package com.xinruke.common.vo.query;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import springfox.documentation.annotations.ApiIgnore;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName BaseQueryVO
* @CreateDate 2019/6/7
* @Author FengXinQiang
* @Version V1.0.0.0
* @Decription 基础查询
*/
@ApiModel("基础查询")
public class BaseQueryVO {
@ApiModelProperty("每页记录数,默认20")
private int pageSize = 20;
@ApiModelProperty("当前页号,默认1")
private int pageNo = 1;
@ApiModelProperty("排序字段列表")
private List<OrderField> orderFields;
/**
* 查询条件集合
*/
@JsonIgnore
private QueryConditions queryConditions;
/**
*
*/
public BaseQueryVO() {
orderFields = new ArrayList<OrderField>();
queryConditions = new QueryConditions();
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public List<OrderField> getOrderFields() {
return orderFields;
}
public void setOrderFields(List<OrderField> orderFields) {
this.orderFields = orderFields;
}
public QueryConditions getQueryConditions() {
return queryConditions;
}
public void setQueryConditions(QueryConditions queryConditions) {
this.queryConditions = queryConditions;
}
}
|
//
// 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: 2019.04.17 at 08:40:10 PM ICT
//
package object.visualparadigm;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice maxOccurs="unbounded">
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}StringProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}IntegerProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}DoubleProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}BooleanProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}HTMLProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}ModelProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}ModelsProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}ModelRefProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}ModelRefsProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}TextModelProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}DiagramRefProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}DiagramElementRefProperty" maxOccurs="unbounded"/>
* <element ref="{http://www.visual-paradigm.com/product/vpuml/modelexporter}StringArrayProperty" maxOccurs="unbounded"/>
* </choice>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"stringPropertyOrIntegerPropertyOrDoubleProperty"
})
@XmlRootElement(name = "ModelProperties")
public class ModelProperties {
@XmlElements({
@XmlElement(name = "StringProperty", type = StringProperty.class),
@XmlElement(name = "IntegerProperty", type = IntegerProperty.class),
@XmlElement(name = "DoubleProperty", type = DoubleProperty.class),
@XmlElement(name = "BooleanProperty", type = BooleanProperty.class),
@XmlElement(name = "HTMLProperty", type = HTMLProperty.class),
@XmlElement(name = "ModelProperty", type = ModelProperty.class),
@XmlElement(name = "ModelsProperty", type = ModelsProperty.class),
@XmlElement(name = "ModelRefProperty", type = ModelRefProperty.class),
@XmlElement(name = "ModelRefsProperty", type = ModelRefsProperty.class),
@XmlElement(name = "TextModelProperty", type = TextModelProperty.class),
@XmlElement(name = "DiagramRefProperty", type = DiagramRefProperty.class),
@XmlElement(name = "DiagramElementRefProperty", type = DiagramElementRefProperty.class),
@XmlElement(name = "StringArrayProperty", type = StringArrayProperty.class)
})
protected List<Property> stringPropertyOrIntegerPropertyOrDoubleProperty;
/**
* Gets the value of the stringPropertyOrIntegerPropertyOrDoubleProperty property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the stringPropertyOrIntegerPropertyOrDoubleProperty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStringPropertyOrIntegerPropertyOrDoubleProperty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StringProperty }
* {@link IntegerProperty }
* {@link DoubleProperty }
* {@link BooleanProperty }
* {@link HTMLProperty }
* {@link ModelProperty }
* {@link ModelsProperty }
* {@link ModelRefProperty }
* {@link ModelRefsProperty }
* {@link TextModelProperty }
* {@link DiagramRefProperty }
* {@link DiagramElementRefProperty }
* {@link StringArrayProperty }
*
*
*/
public List<Property> getStringPropertyOrIntegerPropertyOrDoubleProperty() {
if (stringPropertyOrIntegerPropertyOrDoubleProperty == null) {
stringPropertyOrIntegerPropertyOrDoubleProperty = new ArrayList<Property>();
}
return this.stringPropertyOrIntegerPropertyOrDoubleProperty;
}
}
|
package com.example.healthmanage.ui.activity.famousDoctorHall.adapter;
import android.content.Context;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.healthmanage.R;
import com.example.healthmanage.ui.activity.famousDoctorHall.response.ChinaCityDataBean;
import java.util.List;
/**
* desc:
* date:2021/7/5 14:15
* author:bWang
*/
public class CityAdapter extends BaseQuickAdapter<ChinaCityDataBean.CityListBean, BaseViewHolder> {
private Context mContext;
public CityAdapter(@Nullable List<ChinaCityDataBean.CityListBean> data,Context context) {
super(R.layout.item_select_right,data);
this.mContext = context;
}
@Override
protected void convert(BaseViewHolder helper, ChinaCityDataBean.CityListBean item) {
helper.setText(R.id.tv_rank,item.getName())
.setTextColor(R.id.tv_rank,item.isSelect()?mContext.getResources().getColor(R.color.colorTxtBlue):mContext.getResources().getColor(R.color.colorTxtBlack));
}
}
|
package com.polsl.edziennik.desktopclient.view.admin;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import com.polsl.edziennik.delegates.DelegateFactory;
import com.polsl.edziennik.delegates.exceptions.DelegateException;
import com.polsl.edziennik.desktopclient.controller.utils.factory.interfaces.IFilter;
import com.polsl.edziennik.desktopclient.controller.utils.workers.Worker;
import com.polsl.edziennik.desktopclient.view.admin.dialogs.ExamTaskTypeDialog;
import com.polsl.edziennik.desktopclient.view.admin.dialogs.GradeTypeDialog;
import com.polsl.edziennik.desktopclient.view.common.SubjectRules;
import com.polsl.edziennik.desktopclient.view.common.panels.SendFilePanel;
import com.polsl.edziennik.desktopclient.view.common.panels.button.SaveButtonPanel;
import com.polsl.edziennik.modelDTO.file.FileDTO;
import com.polsl.edziennik.modelDTO.subjectrules.SubjectRulesDTO;
public class SubjectRulesManagement extends SubjectRules {
private SendFilePanel sendPanel;
private final SaveButtonPanel buttonPanel;
private JButton gradeTypes;
private JButton examTaskTypes;
private JLabel configure;
private GradeTypeDialog gradeTypesPanel;
private ExamTaskTypeDialog examTaskTypesPanel;
private IFilter filter;
public SubjectRulesManagement() {
setEditable(true);
buttonPanel = new SaveButtonPanel();
buttonPanel.getSaveButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
UpdateWorker worker = new UpdateWorker();
worker.execute();
worker.startProgress();
}
});
add(buttonPanel, BorderLayout.SOUTH);
}
@Override
public void create() {
super.create();
filter = factory.createFilter();
sendPanel = new SendFilePanel(filter.getDocumentFilter());
sendPanel.getChoseButton().addActionListener(sendPanel.new DefaultListener());
sendPanel.getSendButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FileDTO file = sendPanel.getFile();
if (file == null || file.getContent() == null) {
JOptionPane.showMessageDialog(null, bundle.getString("fileTransferError"));
} else {
SaveFileWorker w = new SaveFileWorker(file);
w.execute();
w.startProgress();
}
}
});
configure = label.getLabel("configure");
gradeTypes = button.getButton("gradeTypes", "gradeTypesHint");
gradeTypes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gradeTypesPanel = new GradeTypeDialog();
}
});
examTaskTypes = button.getButton("examTaskTypes", "examTaskTypesHint");
examTaskTypes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
examTaskTypesPanel = new ExamTaskTypeDialog();
}
});
}
public void setSubjectRulesData() {
if (currentSubject == null) currentSubject = new SubjectRulesDTO();
currentSubject.setAcademicYear(academicYearText.getText());
currentSubject.setSemester(semesterText.getText());
currentSubject.setDescription(descriptionText.getText());
currentSubject.setName(nameText.getText());
}
@Override
public void setComponents() {
super.setComponents();
panel.add(sendPanel, cc.xyw(3, 17, 5));
panel.add(configure, cc.xy(1, 21));
panel.add(gradeTypes, cc.xy(3, 21));
panel.add(examTaskTypes, cc.xyw(4, 21, 3));
}
@Override
public void setEditable(boolean b) {
nameText.setEditable(b);
academicYearText.setEditable(b);
semesterText.setEditable(b);
descriptionText.setEditable(b);
}
private class UpdateWorker extends Worker<Void> {
public UpdateWorker() {
super("save");
}
@Override
protected Void doInBackground() {
try {
setSubjectRulesData();
DelegateFactory.getAdminDelegate().updateSubjectRules(currentSubject);
} catch (DelegateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void done() {
stopProgress();
}
}
private class SaveFileWorker extends Worker<FileDTO> {
private FileDTO f;
public SaveFileWorker(FileDTO f) {
super("save");
this.f = f;
}
@Override
protected FileDTO doInBackground() throws Exception {
if (f != null) return DelegateFactory.getCommonDelegate().addFile(f);
return null;
}
@Override
public void done() {
stopProgress();
FileDTO tmp;
try {
tmp = get();
if (tmp != null) {
f.setId(tmp.getId());
if (currentSubject == null) currentSubject = new SubjectRulesDTO();
currentSubject.setFileId(tmp.getId());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class FileProvider extends Worker<FileDTO> {
@Override
protected FileDTO doInBackground() throws Exception {
return DelegateFactory.getCommonDelegate().getFile(currentSubject.getFileId());
}
@Override
public void done() {
stopProgress();
try {
FileDTO result = get();
if (result != null)
downloadFileChooser.setSelectedFile(new File(result.getName() + result.getExtension()));
if (downloadFileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File f = downloadFileChooser.getSelectedFile();
fileManager.saveFile(result, f.getAbsolutePath());
}
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
|
package com.cnk.travelogix.supplier.inventory.service.impl;
import javax.annotation.Resource;
import com.cnk.travelogix.acco.inventory.core.model.AccoInventoryGridModel;
import com.cnk.travelogix.accoinventory.core.model.AccoInventoryDefinitionModel;
import com.cnk.travelogix.accoinventory.core.model.AccoInventoryDetailModel;
import com.cnk.travelogix.accoinventory.core.model.AccoPenaltyChargesReleaseModel;
import com.cnk.travelogix.accoinventory.core.model.InventoryRoomInfoModel;
import com.cnk.travelogix.common.inventory.core.enums.InventoryType;
import com.cnk.travelogix.masterdata.core.enums.RoomCategory;
import com.cnk.travelogix.masterdata.core.enums.RoomType;
import com.cnk.travelogix.supplier.commercials.core.advancedefinition.model.accommodation.AccoSupplierAdvanceDefinitionModel;
import com.cnk.travelogix.supplier.inventory.dao.InventoryDao;
import com.cnk.travelogix.supplier.inventory.service.InventoryService;
import de.hybris.platform.servicelayer.model.ModelService;
public class InventoryServiceImpl implements InventoryService {
@Resource(name = "inventoryDao")
InventoryDao inventoryDao;
@Resource(name = "modelService")
ModelService modelService;
@Override
public AccoInventoryDefinitionModel getInventoryDefination(String supplier , String code) {
return inventoryDao.findInventoryDefination(supplier , code);
}
@Override
public AccoInventoryGridModel getInventoryGrid() {
return inventoryDao.findInventoryGrid();
}
@Override
public AccoInventoryDetailModel getInventroyDetail(String productCode, String cityIso,
InventoryType inventoryType) {
return inventoryDao.findInventroyDetail(productCode, cityIso, inventoryType);
}
@Override
public InventoryRoomInfoModel getInventryRoomInfo(String productCode, String cityIso, RoomCategory roomCategory,
RoomType roomType) {
return inventoryDao.findInventryRoomInfo(productCode, cityIso, roomCategory, roomType);
}
@Override
public AccoSupplierAdvanceDefinitionModel getAccoSupplierAdvanceDefinition(String supplier,
RoomCategory roomCategory, RoomType roomType) {
return inventoryDao.findSupplierAdvanceDefination(supplier, roomCategory, roomType);
}
@Override
public AccoPenaltyChargesReleaseModel getPenaltychargesRelease(String supplier, RoomCategory roomCategory,
RoomType roomType) {
return inventoryDao.findPenaltychargesRelease(supplier, roomCategory, roomType);
}
} |
package juc;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
/**
* @author wyg_edu
* @date 2020年5月9日 上午8:09:30
* @version v1.0
* 多线程中获取新线程的方式
*/
public class CallableDemo {
public static void main(String[] args) throws Exception {
FutureTask<Integer> futureTask1 = new FutureTask<Integer>(new MyThread());
FutureTask<Integer> futureTask2 = new FutureTask<Integer>(new MyThread());
new Thread(futureTask1,"AA").start();
new Thread(futureTask2,"BB").start();// 需要起两个, 否则第二个会直接复用第一个的结果
int n1 = 100;
int n2 = 0;
while(!futureTask1.isDone()) {
n2 = futureTask1.get();// 要求获得计算返回值,如果没有接收到返回值,则会导致阻塞知道计算完成 所以表达式一般放到最后执行
}
System.out.println("result:\t" + (n1 + n2));
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("******* come in Callable");
return 1024;
}
}
|
package com.rapid.test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.rapid.controller.ProductDataController;
import com.rapid.controller.ShoppingCartController;
import com.rapid.model.Order;
import com.rapid.model.OrderItem;
import com.rapid.model.Product;
import com.rapid.notification.MailService;
import com.rapid.order.service.OrderService;
public class OrderServiceTest {
@Test
void invalidOrder() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
//Sending an empty cart to the order
List<OrderItem> cartItems = new ArrayList<>();
Order order = orderService.createOrder(cartItems);
assertThat(order.getErrorMessage()).isEqualTo("The order was not placed because the cart must have at least 1 item");
}
@Test
void validOrder() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
ShoppingCartController.clearCart();
Product p1 = new Product("Apple", new BigDecimal(0.60), 5);
Product p2 = new Product("Orange", new BigDecimal(0.25), 3);
ShoppingCartController.addItem(new OrderItem(p1, 1));
ShoppingCartController.addItem(new OrderItem(p2, 1));
ShoppingCartController.applyOffer1();
ShoppingCartController.applyOffer2();
Order order = orderService.createOrder(ShoppingCartController.getCartItems());
assertThat(order.getSuccessMessage()).contains("Your order has been created. Your order number is");
}
@Test
void invalidOrder_ItemDoesntExist() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
ShoppingCartController.clearCart();
Product p1 = new Product("Banana", new BigDecimal(0.60), 5);
Product p2 = new Product("Peach", new BigDecimal(0.60), 3);
ShoppingCartController.addItem(new OrderItem(p1, 1));
ShoppingCartController.addItem(new OrderItem(p2, 1));
ShoppingCartController.applyOffer1();
ShoppingCartController.applyOffer2();
Order order = orderService.createOrder(ShoppingCartController.getCartItems());
assertThat(order.getErrorMessage()).contains("doesn't exist in the catalog");
}
@Test
void validateOrderTotal() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
ShoppingCartController.clearCart();
Product p1 = new Product("Apple", new BigDecimal(0.60), 5);
Product p2 = new Product("Apple", new BigDecimal(0.60), 5);
Product p3 = new Product("Apple", new BigDecimal(0.60), 5);
Product p4 = new Product("Orange", new BigDecimal(0.25), 3);
ShoppingCartController.addItem(new OrderItem(p1, 1));
ShoppingCartController.addItem(new OrderItem(p2, 1));
ShoppingCartController.addItem(new OrderItem(p3, 1));
ShoppingCartController.addItem(new OrderItem(p4, 1));
ShoppingCartController.applyOffer1();
ShoppingCartController.applyOffer2();
List<OrderItem> cartItems = ShoppingCartController.getCartItems();
Order order = orderService.createOrder(cartItems);
BigDecimal orderTotal = order.getAmount();
assertThat(new BigDecimal(2.05).setScale(2, RoundingMode.CEILING)).isEqualTo(orderTotal);
}
@Test
void validateOrderLineItemQtyAndTotals() {
final OrderService orderService = new OrderService();
ShoppingCartController.clearCart();
List<String> itemsArray = new ArrayList<>();
itemsArray.add("Apple");
itemsArray.add("Apple");
itemsArray.add("Apple");
itemsArray.add("Orange");
itemsArray.add("Orange");
ShoppingCartController.addItemsToCart(itemsArray);
List<OrderItem> cartItems = ShoppingCartController.getCartItems();
Order order = orderService.createOrder(cartItems);
List<OrderItem> orderCartItems = order.getCartLineItems();
Integer appleQty = null;
BigDecimal appleLineTotal = null;
for(OrderItem item: orderCartItems) {
if(item.getProduct().getName().equals("Apple")) {
appleQty = item.getQuantity();
appleLineTotal = item.getLineTotal();
}
}
assertThat(new Integer(6)).isEqualTo(appleQty);
assertThat(new BigDecimal(1.8).setScale(1, RoundingMode.FLOOR)).isEqualTo(appleLineTotal.setScale(1, RoundingMode.CEILING));
Integer orangeQty = null;
BigDecimal orangeLineTotal = null;
for(OrderItem item: orderCartItems) {
if(item.getProduct().getName().equals("Orange")) {
orangeQty = item.getQuantity();
orangeLineTotal = item.getLineTotal();
}
}
assertThat(new Integer(3)).isEqualTo(orangeQty);
assertThat(new BigDecimal(0.50).setScale(1, RoundingMode.FLOOR)).isEqualTo(orangeLineTotal.setScale(1, RoundingMode.CEILING));
}
@Test
void quantityExceedsLimit() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
//Populating cart items
List<OrderItem> cartItems = new ArrayList<>();
Product p1 = new Product("Apple", new BigDecimal(0.60));
Product p2 = new Product("Apple", new BigDecimal(0.60));
Product p3 = new Product("Apple", new BigDecimal(0.60));
Product p4 = new Product("Orange", new BigDecimal(0.25));
cartItems.add(new OrderItem(p1, 1));
cartItems.add(new OrderItem(p2, 1));
cartItems.add(new OrderItem(p3, 1));
cartItems.add(new OrderItem(p4, 1001));
Order order = orderService.createOrder(cartItems);
assertThat(order.getErrorMessage()).contains("The quantity of one of the items exceeds the limit");
}
@Test
void testOrderReceivedFromObservableToObserver() {
OrderService orderService = new OrderService(); //Observable
MailService mailService = new MailService(); //Observer
//building product data during runtime
ProductDataController.buildProductDataList();
//Sending an empty cart to the order
List<OrderItem> cartItems = new ArrayList<>();
Product p1 = new Product("Apple", new BigDecimal(0.60), 5);
Product p2 = new Product("Orange", new BigDecimal(0.25), 3);
cartItems.add(new OrderItem(p1, 1));
cartItems.add(new OrderItem(p2, 1));
Order order = orderService.createOrder(cartItems);
orderService.addObserver(mailService);
orderService.setOrder(order);
assertThat(mailService.getOrder().getSuccessMessage()).contains("Your order has been created. Your order number is");
}
@Test
void invalidOrderStocksRunout() {
final OrderService orderService = new OrderService();
//building product data during runtime
ProductDataController.buildProductDataList();
ShoppingCartController.clearCart();
Product p1 = new Product("Apple", new BigDecimal(0.60), 5);
Product p2 = new Product("Apple", new BigDecimal(0.60), 5);
Product p3 = new Product("Apple", new BigDecimal(0.60), 5);
Product p4 = new Product("Orange", new BigDecimal(0.25), 3);
ShoppingCartController.addItem(new OrderItem(p1, 1));
ShoppingCartController.addItem(new OrderItem(p2, 1));
ShoppingCartController.addItem(new OrderItem(p3, 1));
ShoppingCartController.addItem(new OrderItem(p4, 1));
ShoppingCartController.applyOffer1();
ShoppingCartController.applyOffer2();
List<OrderItem> cartItems = ShoppingCartController.getCartItems();
Order order = orderService.createOrder(cartItems);
assertThat(order.getErrorMessage()).contains("Your failed because we are running out of stock.");
}
}
|
package com.weatherandroid.cc;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import Model.Suggestion;
import Model.SuggestionAdapter;
/**
* Created by Administrator on 2018/3/14.
*/
public class outsug_item extends LinearLayout {
private int PingmuWidth = 0;
public outsug_item(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.outsugitem,this);
PingmuWidth = getResources().getDisplayMetrics().widthPixels;
LinearLayout tx = (LinearLayout) findViewById(R.id.sug_text);
tx.setMinimumWidth(PingmuWidth/10*7);
}
/**
*
*/
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.rendering;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.cmsfacades.data.AbstractPageData;
/**
* Interface responsible for retrieving page for rendering purposes.
*/
public interface PageRenderingService
{
/**
* Returns {@link AbstractPageData} object based on pageLabelOrId or code.
* @param pageTypeCode the page type
* @param pageLabelOrId the page label or id. This field is used only when the page type is ContentPage.
* @param code the code depends on the page type. If the page type is ProductPage then the code should be a product code.
* If the page type is CategoryPage then the code should be a category code.
* If the page type is CatalogPage then the code should be a catalog page.
* @return the {@link AbstractPageData} object.
* @throws CMSItemNotFoundException if the page does not exists.
*/
AbstractPageData getPageRenderingData(final String pageTypeCode, final String pageLabelOrId, final String code) throws
CMSItemNotFoundException;
}
|
package com.ojas.jwt;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
public class JwtTokenFilter extends GenericFilterBean {
static Logger log = Logger.getLogger(JwtTokenFilter.class.getName());
private JwtTokenGenerator jwtTokenGenerator;
public JwtTokenFilter(JwtTokenGenerator jwtTokenGenerator) {
this.jwtTokenGenerator = jwtTokenGenerator;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.debug("Incoming request jwttokenfilter dofilter method : " + request + " and " + response + " and " + chain);
String tokenResolved = jwtTokenGenerator.tokenResolved((HttpServletRequest) request);
if (tokenResolved != null && jwtTokenGenerator.validateToken(tokenResolved)) {
Authentication auth = tokenResolved != null ? jwtTokenGenerator.authentication(tokenResolved) : null;
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}
|
package com.komaxx.komaxx_gl.util;
public class Interpolators {
private Interpolators(){}
/**
* Extra simple Interpolator: linear
*/
public static class LinearInterpolator implements Interpolator{
private final float startY;
private final float endY;
private long startX;
private long endX;
private float yDelta;
private float xDelta;
public LinearInterpolator(float startY, float endY, long startX, long endX){
this.startY = startY;
this.endY = endY;
this.startX = startX;
this.endX = endX;
yDelta = endY - startY;
xDelta = endX - startX;
}
@Override
public float getValue(long x) {
if (x >= endX) return endY;
if (x <= startX) return startY;
float pos = (float)(x-startX) / xDelta;
return startY + pos*yDelta;
}
@Override
public long getStartX() {return startX;}
@Override
public long getEndX() {return endX;}
@Override
public float getEndY() { return endY;}
@Override
public void translateX(long deltaX) {
startX += deltaX;
endX += deltaX;
}
}
/**
* different behavior depending on <code>power</code>:<br/>
* > 1: smooth start, fastening, abrupt ending<br/>
* ==1: linear interpolation<br/>
* < 1: quick start, slowing down<br/>
* <b>NOTE</b>: Values <= 0 for "power" are not permitted. Will then interpolate linearly!
* @author Matthias Schicker
*/
public static class PowerInterpolator implements Interpolator{
protected final double startY;
protected final double endY;
protected long startX;
protected long endX;
protected double yDelta;
protected double xDelta;
protected final double power;
public PowerInterpolator(double power, double startY, double endY, long startX, long endX){
if (power < 0) power = 1;
this.power = power;
this.startY = startY;
this.endY = endY;
this.startX = startX;
this.endX = endX;
yDelta = endY - startY;
xDelta = endX - startX;
}
@Override
public float getValue(long x) {
if (x <= startX) return (float) startY;
if (x >= endX) return (float) endY;
double pos = (double)(x-startX) / xDelta;
return (float)(startY + Math.pow(pos, power) * yDelta);
}
@Override
public long getStartX() {return startX;}
@Override
public long getEndX() {return endX;}
@Override
public float getEndY() {return (float) endY;}
@Override
public void translateX(long deltaX) {
startX += deltaX;
endX += deltaX;
}
}
/**
* Creates the inverse effect of a PowerInterpolator: Starts quick, then slows down.
*/
public static class InverseSquareInterpolator implements Interpolator {
protected final double startY;
protected final double endY;
protected long startX;
protected long endX;
protected double yDelta;
protected double xDelta;
public InverseSquareInterpolator(double startY, double endY, long startX, long endX){
this.startY = startY;
this.endY = endY;
this.startX = startX;
this.endX = endX;
yDelta = endY - startY;
xDelta = endX - startX;
}
@Override
public float getValue(long x) {
if (x <= startX) return (float) startY;
if (x >= endX) return (float) endY;
double pos = (double)(x-startX) / xDelta; // normalize to [0|1]
return (float)(startY + (1-(1-(pos*pos))) * yDelta);
}
@Override
public long getStartX() {return startX;}
@Override
public long getEndX() {return endX;}
@Override
public float getEndY() {return (float) endY;}
@Override
public void translateX(long deltaX) {
startX += deltaX;
endX += deltaX;
}
}
public static class BumpInterpolator implements Interpolator {
protected final double startY;
protected final double maxY;
protected long startX;
protected long endX;
protected double yDelta;
protected double xDelta;
public BumpInterpolator(float startY, float maxY, long startX, long endX) {
this.startY = startY;
this.maxY = maxY;
this.startX = startX;
this.endX = endX;
yDelta = maxY - startY;
xDelta = endX - startX;
}
@Override
public float getValue(long x) {
if (x >= endX) return (float) startY;
double pos = ((double)(x-startX) / xDelta) * 2.0 - 1.0; // transformed x to [-1|1]
return (float)(startY + (1.0 - Math.pow(pos, 2)) * yDelta);
}
@Override
public long getStartX() { return startX; }
@Override
public long getEndX() { return endX; }
@Override
public float getEndY() { return (float) maxY; }
@Override
public void translateX(long deltaX) {
startX += deltaX;
endX += deltaX;
}
}
public static class OverBumpInterpolator extends PowerInterpolator {
public OverBumpInterpolator(double startY, double endY, long startX, long endX) {
super(0, startY, endY, startX, endX);
}
@Override
public float getValue(long x) {
if (x >= endX) return (float) endY;
if (x <= startX) return (float) startY;
double pos = (double)(x-startX) / xDelta;
return (float) (startY + (1.2 * Math.sin(2*pos))*yDelta);
}
}
public static interface Interpolator {
float getValue(long x);
long getStartX();
long getEndX();
float getEndY();
void translateX(long delta);
}
/**
* Not really a hyperbel ;) Starts quick, smooth ending.
* @author Matthias Schicker
*/
public static class HyperbelInterpolator extends PowerInterpolator{
public HyperbelInterpolator(double startY, double endY, long startX, long endX){
super(1, startY, endY, startX, endX);
}
@Override
public float getValue(long x) {
if (x >= endX) return (float) endY;
if (x <= startX) return (float) startY;
double pos = (double)(x-startX) / xDelta;
return (float)(startY + (1 + Math.pow(pos-1, 3)) * yDelta);
}
}
/**
* This interpolator is created with a current speed and an attenuation-strength
*/
public static class AttenuationInterpolator implements Interpolator {
private final double startY;
private long startX;
private long endX;
private final double endY;
private final double startSpeedPerX;
private final double linearEndY;
private final double xSpan;
public AttenuationInterpolator(double startY, long startX, long endX, double startSpeedPerX){
this.startY = startY;
this.startX = startX;
this.endX = endX;
this.startSpeedPerX = startSpeedPerX;
xSpan = endX - startX;
linearEndY = 0.5 * startSpeedPerX*(double)xSpan;
endY = doGetValue(endX);
}
@Override
public long getEndX() {
return endX;
}
@Override
public float getEndY() {
return getValue(endX);
}
@Override
public long getStartX() {
return startX;
}
@Override
public float getValue(long x) {
if (x >= endX) return (float) endY;
if (x <= startX) return (float) startY;
return doGetValue(x);
}
private float doGetValue(long x){
double deltaX = x-startX;
return (float) (startY + startSpeedPerX * (double)deltaX
- Math.pow(deltaX / xSpan, 2) * linearEndY
);
}
@Override
public void translateX(long deltaX) {
startX += deltaX;
endX += deltaX;
}
}
}
|
package com.sensetime.accessibilitydemo;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
/**
* @author qinhaihang_vendor
* @version $Rev$
* @time 2019/3/20 20:17
* @des
* @packgename com.sensetime.accessibilitydemo
* @updateAuthor $Author$
* @updateDate $Date$
* @updateDes
*/
public class AccessibilityUtils {
private static final String TAG = AccessibilityUtils.class.getSimpleName();
/**
* 该辅助功能开关是否打开了
* @param accessibilityServiceName:指定辅助服务名字
* @param context:上下文
* @return
*/
public static boolean isAccessibilitySettingsOn(Context context,String accessibilityServiceName) {
int accessibilityEnable = 0;
String serviceName = context.getPackageName() + "/" +accessibilityServiceName;
try {
accessibilityEnable = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, 0);
} catch (Exception e) {
Log.e(TAG, "get accessibility enable failed, the err:" + e.getMessage());
}
if (accessibilityEnable == 1) {
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
String settingValue = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
if (accessibilityService.equalsIgnoreCase(serviceName)) {
Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
}else {
Log.d(TAG,"Accessibility service disable");
}
return false;
}
/**
* 跳转到系统设置页面开启辅助功能
* @param accessibilityServiceName:指定辅助服务名字
* @param context:上下文
*/
public static void openAccessibility(Activity context,String accessibilityServiceName){
if (!isAccessibilitySettingsOn(context,accessibilityServiceName)) {
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
context.startActivity(intent);
}
}
}
|
package com.conglomerate.dev.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
public class WrongEmailException extends ResponseStatusException {
public WrongEmailException(String username, String email) {
super(HttpStatus.BAD_REQUEST, "The provided email " + email + " does not match the email on file for " + username);
}
}
|
package com.test.leverton.repository.impl;
import com.test.leverton.model.URL;
import com.test.leverton.repository.URLShortnerRepository;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
/**
* Created by adarshbhattarai on 4/25/18.
*/
@Repository
//@Transactional
public class URLShortnerRepositoryImpl implements URLShortnerRepository{
static List<URL> urls = new ArrayList<>();
//@PersistenceContext
// private EntityManager entityManager;
@Override
public URL findByURL(String longUrl) {
URL url;
try{
url = urls.stream().filter(i->i.getLongUrl().equals(longUrl)).findAny().get();
} catch (Exception e){
url =null;
}
return url;
}
@Override
public void remove(URL url) {
urls.remove(url);
}
@Override
public URL add(URL url) {
urls.add(url);
return url;
}
@Override
public List<URL> getAllURL() {
/*return entityManager.createNativeQuery("SELECT * from URL)
.getResultList();*/
return urls;
}
}
|
package com.tencent.mm.ui.widget.textview;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
class a$5 implements OnAttachStateChangeListener {
final /* synthetic */ a uPp;
a$5(a aVar) {
this.uPp = aVar;
}
public final void onViewAttachedToWindow(View view) {
}
public final void onViewDetachedFromWindow(View view) {
a aVar = this.uPp;
aVar.ih.getViewTreeObserver().removeOnScrollChangedListener(aVar.uOY);
aVar.ih.getViewTreeObserver().removeOnPreDrawListener(aVar.uPm);
aVar.cBo();
aVar.cBn();
aVar.uOZ = null;
aVar.uPa = null;
aVar.uPe = null;
}
}
|
package com.luhc.blog.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luhc.blog.dao.PostDao;
import com.luhc.blog.entity.ArchivePostVo;
import com.luhc.blog.entity.Post;
import com.luhc.blog.service.PostService;
@Service(value = "postService")
public class PostServiceImpl implements PostService {
@Autowired
private PostDao postDao;
@Override
public List<Post> findAll() {
return postDao.findAll();
}
@Override
public List<ArchivePostVo> archivePost() {
return postDao.archivePost();
}
@Override
public List<Post> searchArchive(String day) {
return postDao.searchArchive(day);
}
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungsInformationFolieType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.FolierstationEnum;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.SchichtTypEnum;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.TFapoIdentifikationType;
import java.io.StringWriter;
import java.math.BigInteger;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class BeschichtungsInformationFolieTypeBuilder
{
public static String marshal(BeschichtungsInformationFolieType beschichtungsInformationFolieType)
throws JAXBException
{
JAXBElement<BeschichtungsInformationFolieType> jaxbElement = new JAXBElement<>(new QName("TESTING"), BeschichtungsInformationFolieType.class , beschichtungsInformationFolieType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private FolierstationEnum station;
private TFapoIdentifikationType auftragRef;
private BigInteger schichtNr;
private SchichtTypEnum schichtTyp;
private String stoffNr;
private String maschine;
public BeschichtungsInformationFolieTypeBuilder setStation(FolierstationEnum value)
{
this.station = value;
return this;
}
public BeschichtungsInformationFolieTypeBuilder setAuftragRef(TFapoIdentifikationType value)
{
this.auftragRef = value;
return this;
}
public BeschichtungsInformationFolieTypeBuilder setSchichtNr(BigInteger value)
{
this.schichtNr = value;
return this;
}
public BeschichtungsInformationFolieTypeBuilder setSchichtTyp(SchichtTypEnum value)
{
this.schichtTyp = value;
return this;
}
public BeschichtungsInformationFolieTypeBuilder setStoffNr(String value)
{
this.stoffNr = value;
return this;
}
public BeschichtungsInformationFolieTypeBuilder setMaschine(String value)
{
this.maschine = value;
return this;
}
public BeschichtungsInformationFolieType build()
{
BeschichtungsInformationFolieType result = new BeschichtungsInformationFolieType();
result.setStation(station);
result.setAuftragRef(auftragRef);
result.setSchichtNr(schichtNr);
result.setSchichtTyp(schichtTyp);
result.setStoffNr(stoffNr);
result.setMaschine(maschine);
return result;
}
} |
package GameStrategy;
import project.Turn;
public interface GameStrategy {
Turn execute();
boolean isSolved();
}
|
package learnJava.masterClass;
public class Main {
public static void main(String[] args) {
byte validByte =100;
short validShort =10000;
int validInt =123_456_100;
long validLong = 50000L + 10L*(validByte+validInt+validShort);
System.out.println(validLong);
}
}
|
package lck.productevaluation.home.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import butterknife.BindView;
import butterknife.ButterKnife;
import lck.productevaluation.R;
import lck.productevaluation.home.activity.DetailProductActivity;
import lck.productevaluation.server.model.search.ResultSearch;
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ItemProductHolder> {
private ResultSearch mResultSearch;
private Context mContext;
public ProductAdapter(ResultSearch resultSearch, Context context){
this.mResultSearch = resultSearch;
this.mContext = context;
}
public void updateData(ResultSearch resultSearch) {
this.mResultSearch = resultSearch;
notifyDataSetChanged();
}
@NonNull
@Override
public ItemProductHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View v = inflater.inflate(R.layout.item_product, viewGroup, false);
return new ItemProductHolder(v);
}
@Override
public void onBindViewHolder(@NonNull ItemProductHolder itemProduct, final int i) {
Picasso.get().load(this.mResultSearch.getData().get(i).getThumbnailUrl()).into(itemProduct.imgProduct);
itemProduct.txtName.setText(this.mResultSearch.getData().get(i).getName());
itemProduct.txtPrice.setText(Integer.toString(this.mResultSearch.getData().get(i).getPrice())+"đ");
if (this.mResultSearch.getData().get(i).getDiscountRate() == 0) {
itemProduct.txtDiscount.setText("");
} else {
itemProduct.txtDiscount.setText("-"+Integer.toString(this.mResultSearch.getData().get(i).getDiscountRate())+"%");
}
itemProduct.txtNumReview.setText(Integer.toString(this.mResultSearch.getData().get(i).getReviewCount()));
itemProduct.txtNumLike.setText(Integer.toString(this.mResultSearch.getData().get(i).getFavouriteCount()));
itemProduct.rtbRating.setRating(this.mResultSearch.getData().get(i).getRatingAverage());
itemProduct.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,DetailProductActivity.class);
intent.putExtra("data",mResultSearch.getData().get(i));
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
if (this.mResultSearch == null) {
return 0;
}
return this.mResultSearch.getData().size();
}
public class ItemProductHolder extends RecyclerView.ViewHolder{
@BindView(R.id.img_product)
ImageView imgProduct;
@BindView(R.id.txt_name_product)
TextView txtName;
@BindView(R.id.txt_price)
TextView txtPrice;
@BindView(R.id.txt_discount)
TextView txtDiscount;
@BindView(R.id.txt_num_review)
TextView txtNumReview;
@BindView(R.id.txt_num_like)
TextView txtNumLike;
@BindView(R.id.rtb_rating)
RatingBar rtbRating;
public ItemProductHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
}
}
|
/*
* Copyright 2018 Ameer Antar.
*
* 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 org.antfarmer.ejce.password.encoder.bc;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Properties;
import java.util.regex.Pattern;
import org.antfarmer.ejce.password.encoder.AbstractScryptPasswordEncoder;
import org.antfarmer.ejce.util.ByteUtil;
import org.antfarmer.ejce.util.TextUtil;
import org.bouncycastle.crypto.generators.SCrypt;
/**
* Password encoder using Bouncy Castle's SCrpyt implementation.
* @author Ameer Antar
*/
public class BcScryptEncoder extends AbstractScryptPasswordEncoder {
private static final Pattern SPLITTER = Pattern.compile("\\$");
private int cpuCost;
private int memoryCost;
private int parallelization;
private int keyLength;
private int saltLength;
private SecureRandom random;
private int minimumEncLength;
private int maximumEncLength;
/**
* {@inheritDoc}
*/
@Override
public void doConfigure(final Properties parameters, final String prefix) {
cpuCost = parseInt(parameters, prefix, KEY_CPU_COST, DEFAULT_CPU_COST);
memoryCost = parseInt(parameters, prefix, KEY_MEM_COST, DEFAULT_MEM_COST);
parallelization = parseInt(parameters, prefix, KEY_PARALLELIZATION, DEFAULT_PARALLELIZATION);
keyLength = parseInt(parameters, prefix, KEY_KEY_LENGTH, DEFAULT_KEY_LENGTH);
saltLength = parseInt(parameters, prefix, KEY_SALT_LENGTH, DEFAULT_SALT_LENGTH);
random = getRandom(parameters, prefix);
if (cpuCost <= 1 || cpuCost > 65536) {
throw new IllegalArgumentException("Cpu cost parameter must be > 1 and <= 65536.");
}
if ((cpuCost & (cpuCost - 1)) != 0) {
throw new IllegalArgumentException("Cpu cost must be a power of 2.");
}
if (memoryCost < 1 || memoryCost > 0xff) { // header only allows up to 255
throw new IllegalArgumentException("Memory cost must be >= 1 and < 256.");
}
final int maxParallel = Integer.MAX_VALUE / (128 * memoryCost * 8);
// header only allows up to 255
if (parallelization < 1 || parallelization > 0xff || parallelization > maxParallel) {
throw new IllegalArgumentException("Parallelization parameter p must be >= 1 and <= "
+ (maxParallel < 0xff ? maxParallel : 0xff)
+ " (based on block size r of " + memoryCost + ")");
}
if (keyLength < 1 || keyLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Key length must be >= 1 and <= " + Integer.MAX_VALUE);
}
if (saltLength < 1 || saltLength > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Salt length must be >= 1 and <= " + Integer.MAX_VALUE);
}
minimumEncLength = 3 + 5 + (4 * (keyLength + saltLength) / 3);
maximumEncLength = 3 + 16 + (4 * (keyLength + saltLength) / 3);
}
/**
* {@inheritDoc}
*/
@Override
public String doEncode(final CharSequence rawPassword) {
final byte[] salt = new byte[saltLength];
random.nextBytes(salt);
final byte[] pass = toBytes(rawPassword);
try {
final byte[] derived = SCrypt.generate(pass, salt, cpuCost, memoryCost, parallelization, keyLength);
final String params = Long.toString(((int) (Math.log(cpuCost) / Math.log(2)) << 16) | memoryCost << 8 | parallelization, 16);
final StringBuilder sb = new StringBuilder(maximumEncLength);
sb.append("$").append(params).append('$').append(encodeBytes(salt)).append('$').append(encodeBytes(derived));
return sb.toString();
}
finally {
ByteUtil.clear(pass);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isMatch(final CharSequence rawPassword, final String encodedPassword) {
if (!TextUtil.hasLength(encodedPassword)) {
return false;
}
if (encodedPassword.length() < minimumEncLength) {
return false;
}
return decodeAndCheckMatches(rawPassword, encodedPassword);
}
private boolean decodeAndCheckMatches(final CharSequence rawPassword, final String encodedPassword) {
final String[] parts = SPLITTER.split(encodedPassword);
if (parts.length != 4) {
return false;
}
final long params = Long.parseLong(parts[1], 16);
final byte[] salt = decodeBytes(parts[2]);
final byte[] derived = decodeBytes(parts[3]);
final int cpuExp = (int) (params >> 16 & 0xffff);
final int cpuCost = 1 << cpuExp;
final int memoryCost = (int) params >> 8 & 0xff;
final int parallelization = (int) params & 0xff;
final byte[] generated;
final byte[] pass = toBytes(rawPassword);
try {
generated = SCrypt.generate(pass, salt, cpuCost, memoryCost, parallelization, keyLength);
}
finally {
ByteUtil.clear(pass);
}
return Arrays.equals(derived, generated);
}
}
|
package com.acme.orderserver.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "tb_order")
public class Order implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "store_id")
@NotNull
private Long storeId;
@NotNull
@Size(min = 2, max = 255)
private String address;
@Column(name = "confirmation_date")
private LocalDateTime confirmationDate;
@NotNull
@Enumerated(EnumType.STRING)
private Order.Status status;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "order_order_item", joinColumns = @JoinColumn(name = "order_id"),
inverseJoinColumns = @JoinColumn(name = "order_item_id"))
private List<OrderItem> items;
public enum Status {
CREATED, REFUNDED, PAY
}
}
|
package persistence;
// Code partly taken from JsonSerializationDemo
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import model.SuggestUniversity;
import org.json.*;
// Represents a reader that reads suggestionList from SuggestUniversity as an JSON Array from JSON data stored in file
public class JsonReader {
private String source;
// Code partly taken from JsonSerializationDemo
// EFFECTS: constructs reader to read from source file
public JsonReader(String source) {
this.source = source;
}
// Code partly taken from JsonSerializationDemo
// EFFECTS: reads workroom from file and returns it;
// throws IOException if an error occurs reading data from file
public SuggestUniversity read() throws IOException {
String jsonData = readFile(source);
JSONObject jsonObject = new JSONObject(jsonData);
return parseSuggestUniversity(jsonObject);
}
// Code partly taken from JsonSerializationDemo
// EFFECTS: reads source file as string and returns it
private String readFile(String source) throws IOException {
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get(source), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder.append(s));
}
return contentBuilder.toString();
}
// Code partly taken from JsonSerializationDemo
// EFFECTS: parses suggestionList, and returns it as a SuggestUniversity object
private SuggestUniversity parseSuggestUniversity(JSONObject jsonObject) {
SuggestUniversity suggestUniversity = new SuggestUniversity();
JSONArray jsonArray = jsonObject.getJSONArray("Suggested");
for (int i = 0; i < jsonArray.length();i++) {
suggestUniversity.addToSuggestionList(jsonArray.getString(i));
}
return suggestUniversity;
}
}
|
package com.smxknife.java.ex4.inneroverride;
public class BigEgg2 extends Egg2 {
public class Yolk extends Egg2.Yolk {
public Yolk(){
System.out.println("BigEgg2.Yolk");
}
public void f() {
System.out.println("BigEgg2.Yolk.f");
}
}
public BigEgg2() {
System.out.println("New BigEgg2");
insertYolk(new Yolk());
}
public static void main(String[] args) {
Egg2 egg2 = new BigEgg2();
egg2.g();
}
}
|
package org.ah.minecraft.tweaks;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
public class HarderHunger extends Tweak {
@Override
public void init(final Server server, Plugin plugin) {
server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
@Override
public void run() {
for (Player p : Bukkit.getOnlinePlayers()) {
if (Math.random() > 0.5 && p.getSaturation() > 1) {
p.setSaturation(p.getSaturation() - 1);
}
}
}
}, 1200, 1200);
//
// server.getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
// @Override
// public void run() {
// for (Player p : Bukkit.getOnlinePlayers()) {
// p.sendMessage(ChatColor.RED + "Hunger: " + ChatColor.YELLOW + p.getFoodLevel() + ChatColor.RED + "SATURATION: " + ChatColor.YELLOW + p.getSaturation());
// }
// }
// }, 20, 20);
}
}
|
package top.yunp.startactivitywithpermission;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import top.yunp.startactivitywithpermission.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
presenter = new Presenter(this);
binding.setPresenter(presenter);
}
}
|
package ch02.quiz2_1;
@FunctionalInterface
public interface ApplePrinter {
String print(Apple apple);
}
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); 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.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting;
public enum HorizAlignment {
LEFT("left"), CENTER("center"), RIGHT("right)");
private final String name;
private HorizAlignment(String name) {
this.name = name;
}
/**
* Return a String description of this type.
*
* @return The String description
*/
@Override
public String toString() {
return name;
}
public static HorizAlignment getHorizAlignment(String str) {
return HorizAlignment.valueOf(str);
}
}
|
package crossing;
import uk.co.real_logic.agrona.DirectBuffer;
public interface LOBManager {
DirectBuffer processOrder(DirectBuffer message);
boolean isClientMarketDataRequest();
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* TvDemand generated by hbm2java
*/
public class TvDemand implements java.io.Serializable {
private TvDemandId id;
public TvDemand() {
}
public TvDemand(TvDemandId id) {
this.id = id;
}
public TvDemandId getId() {
return this.id;
}
public void setId(TvDemandId id) {
this.id = id;
}
}
|
package mariculture.compatibility;
import mariculture.core.handlers.LogHandler;
import mariculture.core.lib.Modules;
import mariculture.core.lib.Modules.Module;
import mariculture.core.util.Fluids;
import net.minecraftforge.fluids.FluidRegistry;
import org.apache.logging.log4j.Level;
public class Compat extends Module {
@Override
public void preInit() {
if (FluidRegistry.getFluid("milk") != null) {
Fluids.instance.addFluid("milk", FluidRegistry.getFluid("milk"));
}
}
@Override
public void init() {
if (Modules.isActive(Modules.fishery)) {
try {
//CompatBait.init();
} catch (Exception e) {
LogHandler.log(Level.WARN, "Something went wrong when loading the Bait Compatibility Config");
}
}
CompatFluids.init();
}
@Override
public void postInit() {
setLoaded(null);
}
}
|
/**
*
* @Title: StaticPageServiceImpl.java
* @Package com.yqwl.service.impl
* @Description: TODO)
* @author zhoujiaxin
* @date 2019年4月20日
*/
package com.yqwl.service.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.yqwl.service.StaticPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
*
* @Description 静态页面业务层
*
* @author zhoujiaxin
* @createDate 2019年4月20日
*/
@Service
public class StaticPageServiceImpl implements StaticPageService ,ServletContextAware{
private ServletContext servletContext;
private Configuration configuration;
public void setFreeMarkerConfigurer(FreeMarkerConfigurer freeMarkerConfigurer){
this.configuration = freeMarkerConfigurer.getConfiguration();
}
@Override
public void indexStatic(Map<String, Object> map,String resultName,String templateName){
// 输出流
Writer out = null;
try {
// 读进来 UTF-8
Template template = configuration.getTemplate(templateName+".html");
// 获取路径
String path = getPath("/"+resultName+".html");
File f = new File(path);
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
// 输出流
out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
template.process(map, out);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(String path){
return servletContext.getRealPath(path);
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}
|
package com.playsafe.conversions.service;
import org.springframework.stereotype.Service;
@Service
public class ConversionsServiceImpl implements ConversionService {
public static final double KELVIN_CONSTANT = 273.15;
public static final double MILES_TO_KM_CONSTANT = 1.60934;
public static final double KM_TO_MILES_CONSTANT = 0.621371;
@Override
public double convertKelvintoDegrees(double kelvin) {
return kelvin - KELVIN_CONSTANT;
}
@Override
public double convertDegreetoKelvin(double degree) {
return degree + KELVIN_CONSTANT;
}
@Override
public double convertMilestoKm(double miles) {
return miles * MILES_TO_KM_CONSTANT;
}
@Override
public double convertKmtoMiles(double km) {
return km * KM_TO_MILES_CONSTANT;
}
}
|
package pattern.adapter;
/**
* @Classname VoltageAdapter
* @Description
* @Date 2020-03-31 21:54
* @Created by yinrong
*/
public class VoltageAdapter extends Voltage220V implements Voltage5V {
@Override
public int outPut5V() {
int src=outPut220V();
int dstV=src/44;
return dstV ;
}
}
|
package testing;
import expressiontobt.ExpressionToBinaryTree;
import expressiontobt.ExpressionTreeNode;
/**
* Test related to constructing a BT
* from an expression and representing it in different
* notations.
*
* @author Dylan
*/
public class ExpressionToBinaryTreeUnitTests
{
private static ExpressionTreeNode treeRoot;
private static String userExpression;
//private static final Scanner userInput = new Scanner(System.in);
private static final ExpressionToBinaryTree bt = new ExpressionToBinaryTree();
public static void testExpressionTreeConversions()
{
ExpressionToBinaryTree.setUserExpression("((5*5)+(8/2))");
bt.buildTree(userExpression);
ExpressionToBinaryTree.printExpressionNotation();
String r1 = "Expected Prefix Result: +*55/82";
String r2 = "Expected Infix Result: 5*5+8/2";
String r3 = "Expected Postfix Result: 55*82/+";
System.out.println("-------------------------------\n" + r1 + "\n" + r2 + "\n" + r3);
}
public static void runTests()
{
System.out.println("\n/*Testing Related to Binary Expression Trees:*/");
testExpressionTreeConversions();
}
}
/*
run:
Main Menu:
----------
1. Huffman Encoding Program
2. Infix to Postfix Program
3. Expression to Expression Tree Program
4. Run Unit Tests
5. Exit
4
/*Testing Related to Huffman Encoding:*//*
Character Weights:
'D'-1 'Y'-8 'L'-17 'A'-27 'N'-35 'C'-55
Letter: D Code: 11000
Letter: Y Code: 11001
Letter: L Code: 1101
Letter: A Code: 111
Letter: N Code: 10
Letter: C Code: 0
performHuffmanEncoding() test passed? true
/*Unit Tests Related to Infix To Postfix Converter:(Stack-based Algorithm)*//*
isEmpty() test passed? true
isFull() test passed? true
push() test passed? true
pop() test passed? true
convertInfixToPostfix() test passed? true
/*Testing Related to Binary Expression Trees:*//*
Equivalent Notations:
Prefix: +*55/82
Infix: 5*5+8/2
Postfix: 55*82/+
-------------------------------
Expected Prefix Result: +*55/82
Expected Infix Result: 5*5+8/2
Expected Postfix Result: 55*82/+
Main Menu:
----------
1. Huffman Encoding Program
2. Infix to Postfix Program
3. Expression to Expression Tree Program
4. Run Unit Tests
5. Exit
5
BUILD SUCCESSFUL (total time: 18 seconds)
*/
|
package sforum.security;
import org.springframework.security.core.Authentication;
import sforum.beans.Application;
import sforum.beans.SessionData;
import sforum.model.User;
import sforum.repository.UserRepository;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by @ivan.
*/
public class AuthenticationSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
@Inject
private Application application;
@Inject
private SessionData sessionData;
@Inject
private UserRepository userRepository;
@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException {
final UserDetails principal = (UserDetails) authentication.getPrincipal();
final Long userId = principal.getUserId();
final User user = userRepository.findOne(userId);
sessionData.setCurrentUser(user);
application.userLoggedIn(userId);
// response.sendRedirect(request.getHeader("Referer"));
request.getRequestDispatcher("/loginSuccess?referer=" + request.getHeader("Referer")).forward(request, response);
}
}
|
package Adventure.Items;
import java.util.*;
//********--------------------------------------------------********\\
// This class is used for counting, organizing and weighing items. \\
// Inventory holds a constant of MAX_WEIGHT. \\
// Inventory holds an int value of weight. \\
// Inventory holds lists of inventory(Items) and count(ints). \\
// It is meant to be instatiated. \\
//********--------------------------------------------------********\\
public class Inventory implements Iterable<Item> {
public final int MAX_WEIGHT;
private int weight;
private List<Item> inventory = new ArrayList<Item>();
private List<Integer> count = new ArrayList<Integer>();
//--------------\\
// Constructors \\
//--------------\\
public Inventory() {
MAX_WEIGHT = 1000;
}
public Inventory(int inventoryWeight) {
if (inventoryWeight == 0) MAX_WEIGHT = 1000000000;
else MAX_WEIGHT = inventoryWeight;
}
public Inventory(int inventoryWeight, List<Item> list) {
MAX_WEIGHT = inventoryWeight;
for (Item i : list) {
inventory.add(i);
}
}
public Inventory(int inventoryWeight, List<Item> itemList, List<Integer> countList) {
MAX_WEIGHT = inventoryWeight;
for (int i = 0; i < itemList.size(); i++) {
inventory.add(countList.get(i), itemList.get(i));
}
}
//----------------------\\
// Orginization Methods \\
//----------------------\\
private void organize(int amount, Item item) { // Puts an item into its proper place in the inventory.
if (inventory.isEmpty()) {
inventory.add(item);
count.add(amount);
} else {
for (int j = 0; j < inventory.size(); j++) {
if (j == inventory.size() - 1) {
inventory.add(item);
count.add(amount);
break;
} else {
int order = item.compareTo(inventory.get(j));
if (order <= 0) {
inventory.add(j, item);
count.add(j, amount);
break;
}
}
}
}
}
//---------------------------\\
// Weight-Moderating Methods \\
//---------------------------\\
private boolean testWeight(Item item) {
return ((weight + item.weight) <= MAX_WEIGHT);
}
private boolean addWeight(int amount, Item item) {
if (testWeight(item)) {
weight += item.weight;
return true;
} else {
System.out.println("Sorry, that exceeds capacity.");
return false;
}
}
private void removeWeight(int amount, Item item) {
weight -= item.weight * amount;
}
private int resetWeight() {
for (Item i : inventory) {
weight = i.weight * count.get(inventory.indexOf(i));
}
return weight;
}
//-----------------------\\
// Item Addition Methods \\
//-----------------------\\
public boolean add(int amount, Item item) {
if (addWeight(amount, item)) {
if (contains(item)) {
System.out.println("here");
count.set(indexOf(item), count.get(indexOf(item)) + amount);
} else {
organize(amount, item);
}
return true;
} else {
return false;
}
}
public boolean add(Item item) {
return add(1, item);
}
public boolean add(Item... items) {
boolean result = true;
for (Item i : items) {
if (!add(1, i)) result = false;
}
return result;
}
//----------------------\\
// Item Removal Methods \\
//----------------------\\
public Item remove(int amount, int index) {
Item result = inventory.get(index);
if (count.get(index) > amount) {
count.set(index, count.get(index) - amount);
removeWeight(amount, result);
} else if (count.get(index) == amount) {
count.remove(index);
inventory.remove(index);
removeWeight(amount, result);
} else {
System.out.println("Sorry, you don't have enough of that.");
}
return result;
}
public void remove(int amount, Item item) {
remove(amount, indexOf(item));
}
public Item remove(int index) {
return remove(1, index);
}
public void remove(Item item) {
remove(1, indexOf(item));
}
public void removeAll(Item item) {
inventory.remove(item);
count.remove(inventory.indexOf(item));
resetWeight();
}
//---------------------\\
// Item Moving Methods \\
//---------------------\\
public void move(int amount, Item item, Inventory to) {
if (to.add(amount, item)) {
remove(amount, item);
}
}
public void move(Item item, Inventory to) {
move(1, item, to);
}
//-----------------\\
// Listing Methods \\
//-----------------\\
public String toString() {
String result = "";
for (int i = 0; i < inventory.size(); i += contains(get(i).name)) {
int tempCount = countName(get(i));
if (tempCount == 1) result += tempCount + " " + get(i).name + ", ";
else result += tempCount + " " + get(i).name + "s, ";
}
if (result.length() > 0) return result.substring(0, result.length() - 2);
else return "no items";
}
//-----------------\\
// Getting Methods \\
//-----------------\\
public int count(Item item) {
if (contains(item)) {
return count.get(indexOf(item));
} else {
return 0;
}
}
public int countName(Item item) {
int separateCount = contains(item.name);
if (separateCount == 1) {
return count.get(indexOf(item));
} else if (separateCount > 1) {
int result = 0;
for (int i = indexOf(item); i < indexOf(item)+separateCount; i++) {
result += count.get(i);
}
return result;
} else {
return 0;
}
}
public Item get(int index) {
return inventory.get(index);
}
public Item get(String itemName) { // Warning, this will ONLY return the FIRST Item with the given name.
for (Item i : inventory) {
if (i.name.equals(itemName)) return i;
}
return null;
}
public Item getLast(String itemName) {
Item result = null;
for (Item i : inventory) {
if (i.name.equals(itemName)) result = i;
}
return result;
}
public List<Item> getAll(String itemName) {
List<Item> result = new ArrayList<Item>();
for (Item i : inventory) {
if (i.name.equals(itemName)) result.add(i);
}
return result;
}
public int weight() {
return weight;
}
public int contains(String itemName) { // Returns how many Items there are with itemName as their name.
int result = 0;
for (Item i : inventory) {
if (i.name.equals(itemName)) result++;
}
return result;
}
public boolean contains(Item item) {
boolean result = false;
for (Item i : inventory) {
if (i.equals(item)) result = true;
}
return result;
}
//-----------------------\\
// Miscellaneous Methods \\
//-----------------------\\
public Iterator<Item> iterator() {
return inventory.iterator();
}
public int indexOf(Item item) {
return inventory.indexOf(item);
}
} |
package com.lxd.function;
public class StringFunction {
public static String toUpper(String str){
return str.toUpperCase();
}
}
|
package Test;
import java.util.UUID;
public class Test {
String ttp = String.valueOf(System.currentTimeMillis());
byte[] timeStamp = ttp.getBytes();
String uuidStr = UUID.randomUUID().toString();
byte[] uuid = uuidStr.getBytes("UTF-8");
byte[] resourceURI = "/v2/sv/addUser".getBytes("UTF-8");
}
|
package kr.or.kosta.ams.bin;
import kr.or.kosta.ams.boundary.MainFrame;
public class AMS {
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
frame.setSize(550,550);
frame.setTitle("KOSTA AMS - ¸ÞÀÎȸé");
frame.setContents();
frame.setEventRegister();
}
}
|
package com.espendwise.manta.util.validation.rules;
import com.espendwise.manta.model.data.WorkflowData;
import com.espendwise.manta.service.WorkflowService;
import com.espendwise.manta.support.spring.ServiceLocator;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.arguments.ObjectArgument;
import com.espendwise.manta.util.criteria.StoreAccountCriteria;
import com.espendwise.manta.util.trace.ExceptionReason;
import com.espendwise.manta.util.validation.ValidationRule;
import com.espendwise.manta.util.validation.ValidationRuleResult;
import org.apache.log4j.Logger;
import java.util.List;
public class WorkflowUniqueConstraint implements ValidationRule {
private static final Logger logger = Logger.getLogger(WorkflowUniqueConstraint.class);
private Long accountId;
private String workflowName;
private Long workflowId;
private String workflowTypeCd;
public WorkflowUniqueConstraint(Long accountId, String workflowName, Long workflowId, String workflowTypeCd) {
this.accountId = accountId;
this.workflowName = workflowName;
this.workflowId = workflowId;
this.workflowTypeCd = workflowTypeCd;
}
public Long getAccountId() {
return accountId;
}
public String getWorkflowName() {
return workflowName;
}
public Long getWorkflowId() {
return workflowId;
}
public String getWorkflowTypeCd() {
return workflowTypeCd;
}
public ValidationRuleResult apply() {
logger.info("apply()=> BEGIN");
if (getWorkflowName() == null) {
return null;
}
ValidationRuleResult result = new ValidationRuleResult();
// StoreAccountCriteria criteria = new StoreAccountCriteria();
// criteria.setStoreId(getStoreId());
WorkflowService workflowService = getWorkflowService();
List<WorkflowData> workflows = workflowService.findWorkflowCollection(getAccountId());
if (workflows != null && workflows.size() > 0) {
for (WorkflowData workflow : workflows) {
if (!Utility.strNN(getWorkflowName()).equalsIgnoreCase(workflow.getShortDesc())) {
continue;
}
if (getWorkflowId() == null
|| (workflow.getWorkflowId().longValue() != getWorkflowId().longValue())
|| (!workflow.getWorkflowTypeCd().equals(getWorkflowTypeCd()) )) {
result.failed(
ExceptionReason.WorflowRuleUpdateReason.WORKFLOW_MUST_BE_UNIQUE,
new ObjectArgument<String>(getWorkflowName())
);
return result;
}
}
}
logger.info("apply()=> END, SUCCESS");
result.success();
return result;
}
public WorkflowService getWorkflowService() {
return ServiceLocator.getWorkflowService();
}
}
|
package todo.entity;
import java.sql.SQLException;
import javax.xml.bind.annotation.XmlRootElement;
import inventory.service.StatementManager;
import com.mysql.jdbc.Statement;
@XmlRootElement
public class Branch {
private Statement stmt;
private int branchID;
private String branchName;
private String location;
private String telephone;
public Branch() {
stmt = StatementManager.getStatement();
}
public Branch(int branchID, String branchName, String location,
String telephone) {
this.branchID = branchID;
this.branchName = branchName;
this.location = location;
this.telephone = telephone;
stmt = StatementManager.getStatement();
}
public void setBranchName(String branchName) {
String query = "UPDATE Branch " + " SET branchName = '" + branchName
+ "' " + "WHERE branchID = '" + branchID + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.branchName = branchName;
}
public void setLocation(String location) {
String query = "UPDATE Branch " + " SET location = '" + location
+ "' " + "WHERE branchID = '" + branchID + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.location = location;
}
public void setTelephone(String telephone) {
String query = "UPDATE Branch " + " SET telephone = '" + telephone
+ "' " + "WHERE branchID = '" + branchID + "'";
try {
stmt.executeUpdate(query);
} catch (SQLException e) {
System.out.println("Cannot query");
e.printStackTrace();
}
this.telephone = telephone;
}
public int getBranchID() {
return branchID;
}
public String getBranchName() {
return branchName;
}
public String getLocation() {
return location;
}
public String getTelephone() {
return telephone;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Branch ID : " + branchID + "\n");
sb.append("Branch Name : " + branchName + "\n");
sb.append("Location : " + location + "\n");
sb.append("Telephone : " + telephone + "\n");
return sb.toString();
}
}
|
package xframe.example.pattern.template;
public class Main {
public static void main(String[] args) {
AbstractTemplate template = new ContreteImpl();
template.templateMethod();
}
}
|
package com.tencent.mm.plugin.topstory.ui;
public final class b {
}
|
package com.komaxx.komaxx_gl.math;
/**
* Provides static procedures to manipulate vectors defined as float[3].
* <b>NOT thread safe</b>
*
* @author Matthias Schicker
*/
public class Vector {
private static float[] distanceTmp = new float[3];
private Vector(){}
public static float[] aMinusB2(float[] vA, float[] vB){
vA[0] -= vB[0];
vA[1] -= vB[1];
return vA;
}
public static float[] aMinusB3(float[] vA, float[] vB){
vA[0] -= vB[0];
vA[1] -= vB[1];
vA[2] -= vB[2];
return vA;
}
public static float[] aMinusB3(float[] result, float[] a, float[] b){
result[0] = a[0] - b[0];
result[1] = a[1] - b[1];
result[2] = a[2] - b[2];
return result;
}
public static float[] aMinusB2(float[] result, float[] a, float[] b){
result[0] = a[0] - b[0];
result[1] = a[1] - b[1];
return result;
}
public static float[] aMinusB3(float[] result, float[] a, int aOffset, float[] b){
result[0] = a[aOffset] - b[0];
result[1] = a[aOffset + 1] - b[1];
result[2] = a[aOffset + 2] - b[2];
return result;
}
/**
* Makes the vector have length 1
*/
public static float[] normalize3(float[] v){
float vLength = length3(v);
v[0] /= vLength;
v[1] /= vLength;
v[2] /= vLength;
return v;
}
/**
* Makes the vector have length 1
*/
public static float[] normalize2(float[] v){
float vLength = length2(v);
v[0] /= vLength;
v[1] /= vLength;
return v;
}
/**
* Makes the w value 1
*/
public static float[] normalize4(float[] v){
float factor = 1f / v[3];
v[0] *= factor;
v[1] *= factor;
v[2] *= factor;
v[3] *= factor;
return v;
}
public static float[] scalarMultiply2(float[] v, float scalar){
v[0] *= scalar;
v[1] *= scalar;
return v;
}
public static float[] scalarMultiply3(float[] v, float scalar){
v[0] *= scalar;
v[1] *= scalar;
v[2] *= scalar;
return v;
}
public static float[] addBtoA3(float[] a, float[] b){
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
return a;
}
public static float[] addBtoA2(float[] a, float[] b){
a[0] += b[0];
a[1] += b[1];
return a;
}
public static float[] aPlusB3(float[] result, float[] a, float[] b){
result[0] = a[0] + b[0];
result[1] = a[1] + b[1];
result[2] = a[2] + b[2];
return result;
}
public static float[] aPlusB2(float[] result, float[] a, float[] b){
result[0] = a[0] + b[0];
result[1] = a[1] + b[1];
return result;
}
public static void average3(float[] result, float[] a, int aOffset, float[] b, int bOffset) {
result[0] = (a[aOffset] + b[bOffset]) / 2;
result[1] = (a[aOffset + 1] + b[bOffset + 1]) / 2;
result[2] = (a[aOffset + 2] + b[bOffset + 2]) / 2;
}
public static float[] average3(float[] result, float[] a, float[] b) {
result[0] = (a[0] + b[0]) / 2;
result[1] = (a[1] + b[1]) / 2;
result[2] = (a[2] + b[2]) / 2;
return result;
}
public static float[] average2(float[] result, float[] a, float[] b, float[] c) {
result[0] = (a[0] + b[0] + c[0]) / 3f;
result[1] = (a[1] + b[1] + c[1]) / 3f;
return result;
}
public static float[] aToB3(float[] result, float[] a, float[] b){
return aMinusB3(result, b, a);
}
public static float[] aToB3(float[] result, float[] a, float[] b, int bOffset) {
return aMinusB3(result, b, bOffset, a);
}
public static float[] aToB2(float[] result, float[] a, float[] b) {
if (result == null) result = new float[2];
return aMinusB2(result, b, a);
}
public static float length3(float[] v){
return (float) Math.sqrt( v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
}
public static float length2(float[] v){
return (float) Math.sqrt( v[0]*v[0] + v[1]*v[1] );
}
public static float sqrLength2(float[] v){
return v[0]*v[0] + v[1]*v[1];
}
public static float distance3(float[] a, float[] b) {
return length3(aMinusB3(distanceTmp, a, b));
}
public static float dotProduct2(float[] v1, float[] v2){
return v1[0]*v2[0] + v1[1]*v2[1];
}
public static float distance2(float[] a, float[] b) {
return length2(aMinusB2(distanceTmp, a, b));
}
/**
* Delivers the square of the distance between the two vectors
*/
public static float sqrDistance2(float[] a, float[] b) {
return sqrLength2(aMinusB2(distanceTmp, a, b));
}
public static String toString(float[] v) {
StringBuffer ret = new StringBuffer();
ret.append('(').append(v[0]);
for (int i = 1; i < v.length; i++){
ret.append(" | ").append(v[i]);
}
ret.append(')');
return ret.toString();
}
public static String toString(float[] v, int digits) {
float digitFactor = 1;
for (int i = 0; i < digits; i++) digitFactor *= 10;
StringBuffer ret = new StringBuffer();
ret.append('(').append( (int)(v[0]*digitFactor) / digitFactor );
for (int i = 1; i < v.length; i++){
ret.append(" | ").append( (int)(v[i]*digitFactor) / digitFactor );
}
ret.append(')');
return ret.toString();
}
public static float[] invert2(float[] v) {
v[0] = -v[0];
v[1] = -v[1];
return v;
}
public static float[] invert3(float[] v) {
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
return v;
}
public static float[] invert4(float[] v) {
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
v[3] = -v[3];
return v;
}
public static float[] set3(float[] v, float[] nuValues) {
v[0] = nuValues[0];
v[1] = nuValues[1];
v[2] = nuValues[2];
return v;
}
public static float[] set2(float[] v, float[] nuValues) {
v[0] = nuValues[0];
v[1] = nuValues[1];
return v;
}
public static float[] set2(float[] v, float x, float y) {
v[0] = x;
v[1] = y;
return v;
}
public static void minus3(float[] v) {
v[0] = -v[0];
v[1] = -v[1];
v[2] = -v[2];
}
public static void set3(float[] v, float[] src, int srcOffset) {
v[0] = src[srcOffset];
v[1] = src[srcOffset + 1];
v[2] = src[srcOffset + 2];
}
public static void set3(float[] v, float x, float y, float z) {
v[0] = x;
v[1] = y;
v[2] = z;
}
public static void set4(float[] v, float x, float y, float z, float w) {
v[0] = x;
v[1] = y;
v[2] = z;
v[3] = w;
}
public static void set4(float[] v, int dstOffset, float[] src, int srcOffset) {
v[dstOffset] = src[srcOffset];
v[dstOffset + 1] = src[srcOffset + 1];
v[dstOffset + 2] = src[srcOffset + 2];
v[dstOffset + 3] = src[srcOffset + 3];
}
public static void set4(float[] v, float[] src) {
v[0] = src[0];
v[1] = src[1];
v[2] = src[2];
v[3] = src[3];
}
public static void moveY(float[] vectors, int offset, float yMovement) {
vectors[offset + 1] += yMovement;
}
public static void moveXY(float[] vectors, int offset, float x, float y) {
vectors[offset] += x;
vectors[offset + 1] += y;
}
public static float[] normal2(float[] result, float[] v) {
result[0] = -v[1];
result[1] = v[0];
return result;
}
public static boolean isNormalized2(float[] v) {
return v[0] <= 1 && v[0] >= -1 && v[1] <= 1 && v[1] >= -1 && // quick fail checks
(v[0]*v[0] + v[1]*v[1] == 1); // TODO: Use a more robust equal check that considers float imprecisions!!
}
}
|
package laioffer.serial;
/**
* Created by mengzhou on 6/25/17.
*/
public class GraphTheory {
// Graph:
// Vertex: (i, j, direction) which can pass through
// Neighbor:
// edge weight:
// BFS vs DFS
// Best First Search:
// Vertex: (i, i)
// Neighbor: the longest distance node from 4 directions
}
|
/**
* @file: com.innovail.trouble.screen - MainMenuScreen.java
* @date: Apr 15, 2012
* @author: bweber
*/
package com.innovail.trouble.screen;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL11;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.collision.Ray;
import com.innovail.trouble.core.ApplicationSettings;
import com.innovail.trouble.core.TroubleApplicationState;
import com.innovail.trouble.graphics.GameFont;
import com.innovail.trouble.graphics.GameFont.FontType;
import com.innovail.trouble.graphics.GameMesh;
import com.innovail.trouble.uicomponent.BackgroundImage;
import com.innovail.trouble.uicomponent.MenuEntry;
import com.innovail.trouble.utils.GameInputAdapter;
/**
*
*/
public class MainMenuScreen extends TroubleScreen
{
private static final String TAG = "MainMenuScreen";
private static final String AppPartName = TroubleApplicationState.MAIN_MENU;
private final BitmapFont _menuFont;
private final SpriteBatch _spriteBatch;
private final BackgroundImage _backgroundImage;
private final GameMesh _logo;
private final List <GameMesh> _menuEntriesList;
private final float [] _yRotationAngle;
private final int [] _yRotationDirection;
private static final float _RotationMaxAngle = 2.0f;
private static final float _RotationAngleIncrease = 0.2f;
private static float _rotationDelta = 0.0f;
private static final float _RotationMaxDelta = 0.05f;
private final Matrix4 _viewMatrix;
private final Matrix4 _transformMatrix;
public MainMenuScreen ()
{
super ();
Gdx.app.log (TAG, "MainMenuScreen()");
_spriteBatch = new SpriteBatch ();
_menuFont = ApplicationSettings.getInstance ().getGameFont (GameFont.typeToString (FontType.BITMAP)).getBitmapFont ();
_backgroundImage = ApplicationSettings.getInstance ().getBackgroundImage (AppPartName);
_logo = ApplicationSettings.getInstance ().getLogo ();
_menuEntriesList = ApplicationSettings.getInstance ().getMenuEntryList (AppPartName);
_yRotationAngle = new float [_menuEntriesList.size ()];
_yRotationDirection = new int [_menuEntriesList.size ()];
final Random rand = new Random ();
for (int i = 0; i < _menuEntriesList.size (); i++) {
_yRotationAngle[i] = rand.nextFloat ();
_yRotationAngle[i] *= rand.nextBoolean () ? 1.0f : -1.0f;
_yRotationDirection[i] = rand.nextBoolean () ? 1 : -1;
}
_viewMatrix = new Matrix4 ();
_transformMatrix = new Matrix4 ();
final float aspectRatio = (float) Gdx.graphics.getWidth () / (float) Gdx.graphics.getHeight ();
_camera = new PerspectiveCamera (100, 2f * aspectRatio, 2f);
_camera.position.set (0, 0, 2);
_camera.direction.set (0, 0, -4).sub (_camera.position).nor ();
showFrontAndBack ();
}
@Override
public void createInputProcessor ()
{
Gdx.input.setInputProcessor (new GameInputAdapter () {
/*
* (non-Javadoc)
* @see com.badlogic.gdx.InputProcessor#keyDown(int)
*/
@Override
public boolean keyDown (final int keycode)
{
boolean rv = true;
switch (keycode) {
case Input.Keys.SPACE:
Gdx.app.log (TAG, "keyDown() - SPACE");
break;
case Input.Keys.R:
if (_filling) {
Gdx.app.log (TAG, "keyDown() - wireframing");
Gdx.gl11.glPolygonMode (GL10.GL_FRONT_AND_BACK, GL10.GL_LINE);
_filling = false;
} else {
Gdx.app.log (TAG, "keyDown() - Filling");
Gdx.gl11.glPolygonMode (GL10.GL_FRONT_AND_BACK, GL10.GL_FILL);
_filling = true;
}
break;
case Input.Keys.UP:
Gdx.app.log (TAG, "keyDown() - UP");
break;
case Input.Keys.DOWN:
Gdx.app.log (TAG, "keyDown() - DOWN");
break;
case Input.Keys.LEFT:
Gdx.app.log (TAG, "keyDown() - LEFT");
break;
case Input.Keys.RIGHT:
Gdx.app.log (TAG, "keyDown() - RIGHT");
break;
default:
rv = false;
}
return rv;
}
/*
* (non-Javadoc)
* @see com.badlogic.gdx.InputProcessor#touchUp(int, int, int, int)
*/
@Override
public boolean touchUp (final int x, final int y,
final int pointer, final int button)
{
if (!_isDragged || (_dragEvents < MIN_NUMBER_OF_DRAGS)) {
final Iterator <GameMesh> currentMesh = _menuEntriesList.iterator ();
int j = 0;
final Ray touchRay = _camera.getPickRay (x, y, 0, 0, Gdx.graphics.getWidth (), Gdx.graphics.getHeight ());
if (_DEBUG) {
Gdx.app.log (TAG, "Touch position - x: " + x + " - y: " + y);
Gdx.app.log (TAG, "Touch ray - " + touchRay.toString ());
}
while (currentMesh.hasNext ()) {
final MenuEntry currentEntry = (MenuEntry) currentMesh.next ();
if (touchRay != null) {
if (_DEBUG) {
Gdx.app.log (TAG, "currentEntry BB - " + currentEntry.getBoundingBox ().toString ());
}
if (Intersector.intersectRayBoundsFast (touchRay, currentEntry.getBoundingBox ())) {
_currentState = currentEntry.getName ();
Gdx.app.log (TAG, "Mesh " + j + " touched -> " + _currentState);
break;
}
}
j++;
}
}
return super.touchUp (x, y, pointer, button);
}
});
}
@Override
protected void render (final GL11 gl, final float delta)
{
_rotationDelta += delta;
Gdx.gl11.glPolygonMode (GL10.GL_FRONT_AND_BACK, GL10.GL_FILL);
renderLogo (gl);
renderMenu (gl);
gl.glDisable (GL10.GL_CULL_FACE);
gl.glDisable (GL10.GL_DEPTH_TEST);
}
@Override
protected void renderBackground (final float width, final float height)
{
_viewMatrix.setToOrtho2D (0.0f, 0.0f, width, height);
_spriteBatch.setProjectionMatrix (_viewMatrix);
_spriteBatch.setTransformMatrix (_transformMatrix);
_spriteBatch.begin ();
_spriteBatch.disableBlending ();
_spriteBatch.setColor (Color.WHITE);
_spriteBatch.draw ((Texture) _backgroundImage.getImageObject (), 0, 0, width, height, 0, 0, _backgroundImage.getWidth (), _backgroundImage.getHeight (), false, false);
_spriteBatch.enableBlending ();
_spriteBatch.setBlendFunction (GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);
final String text = ApplicationSettings.getInstance ().getCopyRightNotice ();
final float textWidth = _menuFont.getBounds (text).width;
final float textHeight = _menuFont.getBounds (text).height;
_menuFont.draw (_spriteBatch, text, Gdx.graphics.getWidth () / 2 - textWidth / 2, textHeight + 5);
_spriteBatch.end ();
}
private void renderLogo (final GL11 gl)
{
final Color currentColor = _logo.getColor ();
gl.glPushMatrix ();
gl.glTranslatef (0.0f, 1.0f, 0.3f);
gl.glRotatef (90.0f, 1.0f, 0.0f, 0.0f);
gl.glColor4f (currentColor.r, currentColor.g, currentColor.b, currentColor.a);
_logo.getMesh ().render ();
gl.glPopMatrix ();
}
private void renderMenu (final GL11 gl)
{
final Iterator <GameMesh> currentMesh = _menuEntriesList.iterator ();
float yLocation = 0.0f;
int i = 0;
while (currentMesh.hasNext ()) {
final GameMesh thisMesh = currentMesh.next ();
gl.glPushMatrix ();
gl.glTranslatef (0.0f, yLocation, 0.0f);
gl.glRotatef (_yRotationAngle[i], 0.0f, 0.0f, 1.0f);
thisMesh.getMesh ().render ();
gl.glPopMatrix ();
final Matrix4 transform = new Matrix4 ();
final Matrix4 tmp = new Matrix4 ();
transform.setToTranslation (0.0f, yLocation, 0.0f);
tmp.setToRotation (0.0f, 0.0f, 1.0f, _yRotationAngle[i]);
transform.mul (tmp);
thisMesh.transformBoundingBox (transform);
if (_DEBUG) {
Gdx.gl11.glPolygonMode (GL10.GL_FRONT_AND_BACK, GL10.GL_LINE);
gl.glPushMatrix ();
thisMesh.getBBMesh ().render (GL10.GL_TRIANGLES);
gl.glPopMatrix ();
Gdx.gl11.glPolygonMode (GL10.GL_FRONT_AND_BACK, GL10.GL_FILL);
}
yLocation -= 0.7f;
if (_rotationDelta >= _RotationMaxDelta) {
if (_yRotationDirection[i] == 1) {
_yRotationAngle[i] += _RotationAngleIncrease;
if (_yRotationAngle[i] >= _RotationMaxAngle) {
_yRotationDirection[i] = -1;
}
} else {
_yRotationAngle[i] -= _RotationAngleIncrease;
if (_yRotationAngle[i] <= -_RotationMaxAngle) {
_yRotationDirection[i] = 1;
}
}
}
i++;
}
if (_rotationDelta >= _RotationMaxDelta) {
_rotationDelta = 0.0f;
}
}
@Override
protected void setLighting (final GL11 gl)
{
setLighting (gl, _logo.getColor ());
}
@Override
public void setOwnState ()
{
_currentState = TroubleApplicationState.MAIN_MENU;
}
@Override
protected void update (final float delta)
{
/* Nothing to do here. */
}
}
|
package com.example.mariajose.project;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by MariaJose on 10-04-2018.
*/
@Entity
public class Question {
@PrimaryKey
private int qid;
@ColumnInfo(name = "type")
private String type;
@ColumnInfo(name = "text")
private String text;
public int getQid() {
return qid;
}
public String getText() {
return text;
}
public String getType() {
return type;
}
public void setQid(int qid) {
this.qid = qid;
}
public void setText(String text) {
this.text = text;
}
public void setType(String type) {
this.type = type;
}
}
|
// Sun Certified Java Programmer
// Chapter 8; P678
// Inner Classes
public class Tester678 {
public static void main(String[] args) {
Runnable r = new Runnable(); // can't instantiate interface
/*Runnable r = new Runnable() { // curly brace, not semicolon
public void run() { }
};*/
}
}
|
package cn.canlnac.onlinecourse.presentation.presenter;
import android.support.annotation.NonNull;
import java.io.File;
import javax.inject.Inject;
import cn.canlnac.onlinecourse.domain.interactor.DefaultSubscriber;
import cn.canlnac.onlinecourse.domain.interactor.UseCase;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.ui.fragment.DocumentFragment;
@PerActivity
public class DownloadInDocumentPresenter implements Presenter {
DocumentFragment downloadInDocumentActivity;
private final UseCase uploadUseCase;
private String type;
@Inject
public DownloadInDocumentPresenter(UseCase uploadUseCase) {
this.uploadUseCase = uploadUseCase;
}
public void setView(@NonNull DocumentFragment downloadInDocumentActivity, String type) {
this.downloadInDocumentActivity = downloadInDocumentActivity;
this.type = type;
}
public void initialize() {
this.uploadUseCase.execute(new DownloadInDocumentPresenter.DownloadInDocumentSubscriber());
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void destroy() {
this.uploadUseCase.unsubscribe();
}
private final class DownloadInDocumentSubscriber extends DefaultSubscriber<File> {
@Override
public void onCompleted() {
DownloadInDocumentPresenter.this.downloadInDocumentActivity.setShowingFile(false);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
DownloadInDocumentPresenter.this.downloadInDocumentActivity.showToastMessage("网络连接错误");
DownloadInDocumentPresenter.this.downloadInDocumentActivity.setShowingFile(false);
}
@Override
public void onNext(File file) {
DownloadInDocumentPresenter.this.downloadInDocumentActivity.setShowingFile(false);
DownloadInDocumentPresenter.this.downloadInDocumentActivity.showFile(type,file);
}
}
} |
package com.tencent.mm.wallet_core.ui.formview;
import com.tencent.mm.wallet_core.ui.formview.a.b;
class a$8 extends b {
a$8() {
super((byte) 0);
}
public final boolean a(WalletFormView walletFormView) {
return walletFormView.isPhoneNum();
}
}
|
package L5;
public interface DAOFactory<T> {
DAO<T> getDao(String type);
}
|
package gti310.tp3.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
*
* @author Philippe Potvin <ppotvin@lanets.ca>
*
*/
public class ConcreteParser implements Parser<E>
{
private E store = new E();
private String fName;
private final String EOF = "$";
private final String TAB = "\t";
private int[][] matrix = null;
public E parse(String filename)
{
fName=filename;
//Start with file validation template
if(parseValidation())
{
/*
* storege O(|V|^2)
* Add Vertex O(|V|^2)
* Add Edge O(1)
* Remove Vertex O(|V|^2)
* Remove Edge O(1)
*/
FileInputStream is = null;
try
{
is = new FileInputStream(new File(fName));
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
//first line: fetch nbHead O(1)
store.setNbHead(Integer.parseInt(reader.readLine()));
//second line: fetch infinity value O(1)
store.setInf(Integer.parseInt(reader.readLine()));
//third line: fetch startHead : 1 if none O(1)
String startHead = reader.readLine();
if (!(startHead.equals("")))
{
store.setStart(Integer.parseInt(startHead));
}
else
{
store.setStart(1);
}
//matix initiation
int nbHead = store.getNbHead();
matrix = new int[nbHead][nbHead];
//fill 0 value 0(n^2)
int i,j = 0;
for (i=0;i<nbHead;i++)
{
for (j=0;j<nbHead;j++)
{
matrix[i][j] = 0;
}
}
//matrix fill with file parsed values
while ((line = reader.readLine()) != null)
{
if (!(line.contains(EOF)))
{
try
{
String[] strArray = line.split(TAB);
matrix[(Integer.parseInt(strArray[0]) - 1)][(Integer.parseInt(strArray[1]) - 1)] = Integer.parseInt(strArray[2]);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
break;
}
}
store.setMatix(matrix);
is.close();
reader.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
System.out.println("File format not valid!");
return store;
}
/**
* Validate file structure before initating the parsing creation
*/
private boolean parseValidation()
{
int i = 0;
boolean valid = true;
try
{
Scanner s = new Scanner(new FileReader(fName));
while(s.hasNextInt())
{
Pattern p = Pattern.compile("[\\D]+");
String[] output = p.split(s.nextLine());
if(i==0 && output.length!=1 || i==1 && output.length!=1 || i==2 && output.length!=1)
{
valid = false;
}
if(i>2)
{
if(output.length!=3)
{
valid=false;
}
}
i++;
}
if(!s.next().equals(EOF))
{
valid=false;
}
s.close();
}
catch(FileNotFoundException e)
{
System.out.println("Can't find file!");
e.printStackTrace();
}
return valid;
}
} |
package leecode.dfs;
//递归博客http://39.96.217.32/blog/4
//https://lyl0724.github.io/2020/01/25/1/
/*
递归三部曲
看那个调用图
A
调用| |返回值
A
| |
终止条件
1.找到递归的终止条件
2.知道本层递归需要做什么(知道调用的返回值是什么,即函数的返回值)
2.1 对本层递归的处理就是对传入参数的处理
2.2 本层递归要不要用到下层递归的返回值,知道返回的是什么,要不要将他们保存起来
2.3如果是先序遍历,本层递归处理完成后,下一层传入的参数要不要变化
*/
public class 平衡二叉树_110 {
public boolean isBalanced1(TreeNode root) {
if(root==null){
return true;
}
int left=height(root.left);
int right=height(root.right);
if( Math.abs(left-right)>1){
return false;
}else {
return isBalanced1(root.left)&&isBalanced1(root.right);
}
}
public int height(TreeNode root){
if(root==null){
return 0;
}
return Math.max(height(root.left),height(root.right))+1;
}
public class returnnode{
int high;
boolean flag;
public returnnode(int high,boolean flag){
this.flag=flag;
this.high=high;
}
}
public returnnode isBalanced_1(TreeNode root) {
if(root==null){
return new returnnode(0,true);
}
returnnode left=isBalanced_1(root.left);
returnnode right=isBalanced_1(root.right);
if(left.flag==false||right.flag==false){
return new returnnode(0,false);
}
if(Math.abs(left.high-right.high)>1){
return new returnnode(0,false);
}
int height=Math.max(left.high,right.high);
return new returnnode(height+1,true);
}
}
|
package com.xcj.mapper;
import java.util.List;
import com.xcj.pojo.Permission;
import com.xcj.utils.MyMapper;
public interface PermissionMapper extends MyMapper<Permission> {
public List<Permission> findPermsByRoleId(Long id);
} |
/*
* Copyright 2018 Bradley Steele
*
* 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 me.bradleysteele.timedrewards.command.timedrewards;
import com.google.common.collect.Lists;
import me.bradleysteele.commons.register.command.BCommand;
import me.bradleysteele.commons.util.Messages;
import me.bradleysteele.commons.util.Players;
import me.bradleysteele.timedrewards.resource.yml.Locale;
import me.bradleysteele.timedrewards.util.Permissions;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
/**
* @author Bradley Steele
*/
public class CmdTimedRewardsBlankMessage extends BCommand {
public CmdTimedRewardsBlankMessage() {
this.setAliases("blankmessage", "blankmsg");
this.setDescription("Sends a message to a player with no tr prefix.");
this.setAllowConsole(true);
this.setSync(false);
this.setPermission(Permissions.TR_BLANKMESSAGE);
this.setPermissionDenyMessage(Locale.CMD_NO_PERM.getMessage());
}
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length >= 2) {
Player player = Players.getPlayer(args[0]);
if (player == null) {
Players.sendMessage(sender, Locale.CMD_TR_BLANKMSG_INVALID.getMessage("{player}", args[0]));
return;
}
List<String> words = Lists.newArrayList(args);
words.remove(0);
Players.sendMessage(player, Messages.colour(String.join(" ", words)));
} else {
Players.sendMessage(sender, Locale.CMD_INVALID.getMessage("{args}", "trs blankmsg <player> <message>"));
}
}
}
|
package ru.lischenko_dev.fastmessenger.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import ru.lischenko_dev.fastmessenger.R;
import ru.lischenko_dev.fastmessenger.common.ThemeManager;
import ru.lischenko_dev.fastmessenger.vkapi.models.VKDocument;
public class MaterialsDocAdapter extends BaseAdapter {
private ArrayList<MaterialsAdapter> items;
private Context context;
private LayoutInflater inflater;
private String size;
private int lel;
private ThemeManager manager;
public MaterialsDocAdapter(Context context, ArrayList<MaterialsAdapter> items) {
this.context = context;
this.items = items;
this.manager = ThemeManager.get(context);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int i) {
return items.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
MaterialsAdapter item = (MaterialsAdapter) getItem(i);
VKDocument doc = item.attachment.doc;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.materials_docs_list, viewGroup, false);
}
TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
TextView tvSize = (TextView) view.findViewById(R.id.tvArtist);
tvTitle.setTextColor(manager.getPrimaryTextColor());
ImageView ivDoc = (ImageView) view.findViewById(R.id.ivDoc);
if (doc.isImage())
Picasso.with(context).load(doc.photo_130).placeholder(new ColorDrawable(manager.isDarkTheme() ? Color.LTGRAY : Color.DKGRAY)).into(ivDoc);
else
ivDoc.setVisibility(View.GONE);
tvTitle.setText(doc.title);
tvSize.setText(String.valueOf(doc.ext));
return view;
}
}
|
package p3.Exceptions;
/** Exception thrown when some command recieves invalid arguments. */
@SuppressWarnings("serial")
public class ArgumentException extends Exception {
public ArgumentException(String msg) {
super(msg);
}
}
// To add a new exception, copy and rename this ""TEMPLATE"", use as we use this in all the project
// Most exceptions are catched in "controller" and thrown in "game" |
package sandbox.cdi;
import static org.junit.Assert.assertTrue;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Instance;
import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class JUTWaitForMultiEvent
{
private static SeContainer container;
private static CDI<Object> cdi;
private static AbstractEventReceiver abstractEventReceiver;
private class EventData1 { }
private static class EventEmitter1 { @Inject private Event<EventData1> event; }
private class EventData2 { }
private static class EventEmitter2 { @Inject private Event<EventData2> event; }
@SuppressWarnings("unused")
private abstract static class AbstractEventReceiver
{
private final static Logger LOGGER = LogManager.getLogger(AbstractEventReceiver.class);
private static int constructorCalls = 0;
private boolean eventData1Received = false;
private boolean eventData2Received = false;
private AbstractEventReceiver()
{
LOGGER.debug("constructorCalls: " + ++constructorCalls);
abstractEventReceiver = this;
}
private void receiveEventData1(@Observes EventData1 eventData)
{
LOGGER.debug("received " + eventData.getClass().getName());
eventData1Received = true;
handleReceivedEvents();
}
private void receiveEventData2(@Observes EventData2 eventData)
{
LOGGER.debug("received " + eventData.getClass().getName());
eventData2Received = true;
handleReceivedEvents();
}
private void handleReceivedEvents()
{
LOGGER.debug("eventData1Received: " + eventData1Received + ", eventData2Received: " + eventData2Received);
}
}
// @ApplicationScoped
// private static class ApplicationScopedEventReceiver extends AbstractEventReceiver
// {
// }
private static class EventReceiver extends AbstractEventReceiver
{
}
@BeforeClass public static void beforeClass()
{
SeContainerInitializer initializer = SeContainerInitializer.newInstance();
container = initializer.initialize();
cdi = CDI.current();
}
@AfterClass public static void afterClass() { container.close(); }
@Before public void before() { }
@After public void after() { }
@Test public void receiveEvents()
{
EventReceiver eventReceiver = CDI.current().select(EventReceiver.class).get();
Instance<EventEmitter1> instanceEventEmitter1 = cdi.select(EventEmitter1.class);
EventEmitter1 eventEmitter1 = instanceEventEmitter1.get();
EventData1 eventData1 = new EventData1();
eventEmitter1.event.fire(eventData1);
Instance<EventEmitter2> instanceEventEmitter2 = cdi.select(EventEmitter2.class);
EventEmitter2 eventEmitter2 = instanceEventEmitter2.get();
EventData2 eventData2 = new EventData2();
eventEmitter2.event.fire(eventData2);
assertTrue("abstractEventReceiver.eventData1Received", abstractEventReceiver.eventData1Received);
assertTrue("abstractEventReceiver.eventData2Received", abstractEventReceiver.eventData2Received);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.