text
stringlengths 10
2.72M
|
|---|
package jianzhioffer;
/**
* @ClassName : Solution11
* @Description : 从反转数组中找出最小的数字:要再看一下
* 这题不够熟悉
* 比较的是左右元素,而不是下标。
* 特殊情况是左、中、右相等
*
* 其他变形:判断翻转数组是否存在某个数,存在则返回index,不存在则插入这个数,返回插入后的index
* @Date : 2019/9/15 18:35
*/
public class Solution11 {
public int minNumberInRotateArray(int [] array) {
int left=0;
int right=array.length-1;
int mid=0;
while(array[left]>=array[right]){
if (right-left<=1){
mid=right;
break;
}
mid=(left+right)/2;
if (array[left]==array[mid] && array[right]==array[mid]){
if (array[left+1]!=array[right-1]){
mid=array[left+1]<array[right-1]?left+1:right-1;
}else{
left++;
right--;
}
}else{
if (array[left]<=array[mid]){
left=mid;
}else{
right=mid;
}
}
}
return array[mid];
}
}
|
package com.sap.als.persistence;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
@Entity
@NamedQueries({
@NamedQuery(name = "StepTestAxisById", query = "select a from StepTestAxis a where a.id = :id")
})
public class StepTestAxis implements Serializable {
private static final long serialVersionUID = 1L;
public StepTestAxis() {
}
@Id
@GeneratedValue
private long id;
private Integer time;
private Integer xAxis;
private Integer yAxis;
private Integer zAxis;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Integer getTime() {
return time;
}
public void setTime(Integer time) {
this.time = time;
}
public Integer getxAxis() {
return xAxis;
}
public void setxAxis(Integer xAxis) {
this.xAxis = xAxis;
}
public Integer getyAxis() {
return yAxis;
}
public void setyAxis(Integer yAxis) {
this.yAxis = yAxis;
}
public Integer getzAxis() {
return zAxis;
}
public void setzAxis(Integer zAxis) {
this.zAxis = zAxis;
}
}
|
package io.electrum.sdk.masking2.json;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.InvalidJsonException;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.internal.JsonFormatter;
import net.minidev.json.JSONArray;
import java.util.Map;
import java.util.Set;
public class JsonMaskingUtil {
/**
* Takes in a string containing JSON and a {@link Set} of {@link JsonMaskingUnit}s which dictate how the JSON
* should be masked.
*
* @param json the string containing the JSON to be masked
* @param units masking units which specify which masking schemes should be applied to fields
* identified by JSONPath strings
* @return a pretty-printed string which is a masked version of the originally supplied string.
* Null values are not valid JSON and result in a JsonMaskingException
* @throws JsonMaskingException if the string provided cannot be parsed as JSON, or if the supplied JsonPath
* is invalid
*/
public static String maskInJsonString(String json, Set<JsonMaskingUnit> units)
throws JsonMaskingException {
if (units == null) {
throw new JsonMaskingException("Null Set of JsonMaskingUnit objects - masking aborted");
}
try {
Configuration pathConfiguration = Configuration.builder().options(Option.AS_PATH_LIST).build();
DocumentContext pathContext = JsonPath.using(pathConfiguration).parse(json);
DocumentContext docContext = JsonPath.parse(json);
for (JsonMaskingUnit unit : units) {
JsonPath jsonPath = JsonPath.compile(unit.getJsonPath());
// First get a list of all the sub paths that apply for the given path (in the case that it includes some
// sort of wildcard behaviour)
JSONArray paths;
try {
paths = pathContext.read(jsonPath);
} catch (PathNotFoundException pnfe) {
// Failure to find any matches for the path results in an exception
// Catch it and move on
continue;
}
for (Object path : paths) {
JsonPath subPath = JsonPath.compile((String) path);
Object maskTarget = docContext.read(subPath);
// We only want to process actual data values, not container types
if (maskTarget instanceof JSONArray || maskTarget instanceof Map) {
continue;
}
// If its not some sort of map (JSON object) or JSONArray, the only options left are
// Number and String. We need a string, so we convert accordingly
String newValue;
if (maskTarget instanceof Number) {
newValue = maskTarget.toString();
} else if (maskTarget instanceof String) {
newValue = (String) maskTarget;
} else if (maskTarget == null) {
newValue = null;
} else {
throw new JsonMaskingException("Can't safely convert object of type " + maskTarget.getClass().toString()
+ " to String");
}
pathContext.set(subPath, unit.getMasker().mask(newValue));
}
}
return JsonFormatter.prettyPrint(pathContext.jsonString());
} catch (InvalidJsonException ije) {
throw new JsonMaskingException("Error attempting to parse the supplied String as JSON", ije);
} catch (InvalidPathException ipe) {
throw new JsonMaskingException("Error evaluating JSONPath", ipe);
} catch (IllegalArgumentException iae) {
throw new JsonMaskingException("Cannot mask empty or null JSON", iae);
}
}
}
|
package com.exam.dao.h2;
import com.exam.connection_pool.ConnectionPool;
import com.exam.connection_pool.ConnectionPoolException;
import com.exam.dao.ProfileDAO;
import com.exam.dao.TeamDAO;
import com.exam.dao.UserDAO;
import com.exam.models.User;
import com.exam.util.DataScriptExecutor;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class UserDAOImplTest {
private static UserDAO userDao;
private static ProfileDAO profileDAO;
private static TeamDAO teamDAO;
@BeforeClass
public static void DBinit() throws ConnectionPoolException {
ConnectionPool.create("src/main/resources/db.properties");
ConnectionPool connectionPool = ConnectionPool.getInstance();
connectionPool.initPoolData();
connectionPool.executeScript("src/main/resources/H2Init.sql");
userDao = new UserDAOImpl(connectionPool);
teamDAO = new TeamDAOImpl(connectionPool);
profileDAO = new ProfileDAOImpl(connectionPool);
}
private User generateUser(String email) {
return User.builder()
.email(email)
.password("123456")
.firstName("Иван")
.lastName("Иванов")
.gender(User.GENDER_MALE)
.role(User.ROLE_ADMIN)
.build();
}
@Test
public void read() throws Exception {
final String email = "read@ya.ru";
userDao.create(generateUser(email));
assertTrue(userDao.getByEmail(email)
.map(u -> userDao.read(u.getId()))
.isPresent());
}
@Test
public void getByEmail() throws Exception {
final String email = "getByEmail@junit.org";
userDao.create(generateUser(email));
assertTrue(userDao.getByEmail(email).isPresent());
}
@Test
public void create() throws Exception {
final String email = "create@junit.org";
userDao.create(generateUser(email));
assertTrue(userDao.getByEmail(email).isPresent());
}
@Test
public void update() throws Exception {
final String oldMail = "oldmail@exam.com";
final String newMail = "newmail@exam.com";
userDao.create(generateUser(oldMail));
userDao.getByEmail(oldMail)
.map(user1 ->
new User(
user1.getId(),
newMail,
user1.getPassword(),
user1.getFirstName(),
user1.getLastName(),
user1.getGender(),
user1.getRole()
)).ifPresent(user2 -> userDao.update(user2));
assertTrue(userDao.getByEmail(newMail).isPresent());
}
@Test
public void getFriends() throws Exception {
userDao.create(generateUser("getFriends@test.ru"));
}
// @Test
// public void delete() throws Exception {
// final String email = "delete@UserDaoTest.org";
// final String team_name = "User delete test";
// userDao.create(generateUser(email));
// teamDAO.create(Team.builder().name(team_name).build());
// profileDAO.create(Profile.builder()
// .id(userDao.getByEmail(email).orElseThrow(RuntimeException::new).getId())
// .team(team_name)
// .build());
//
// Optional<User> userOptional = userDao.getByEmail(email);
// assertTrue(userOptional.isPresent());
// userOptional.ifPresent(u -> userDao.delete(u.getId()));
// assertFalse(userDao.getByEmail(email).isPresent());
// }
}
|
package com.mhg.weixin.bean.enums;
/**
* @Classname MsgTypeEnum
* @Description TODO
* @Date 2020/1/29 14:52
* @Created by pwt
*/
public enum MsgTypeEnum {
TXET("text","文本消息");
private final String code;
private final String desc;
MsgTypeEnum(String code, String desc){
this.code = code;
this.desc = desc;
}
public String getCode(){
return code;
}
public String getDesc(){
return desc;
}
public static String getDescByCode(int code) {
String label = "";
for (MsgTypeEnum o : MsgTypeEnum.values()) {
if (o.getCode().equals(code)) {
label = o.getDesc();
}
}
return label;
}
public static String getCodeByDesc(String desc) {
String value = "";
for (MsgTypeEnum o : MsgTypeEnum.values()) {
if (o.getDesc().equals(desc)) {
value = o.getCode();
}
}
return value;
}
public static MsgTypeEnum getByCode(String code) {
for (MsgTypeEnum msgTypeEnum : values()) {
if (msgTypeEnum.getCode().equals(code)) {
return msgTypeEnum;
}
}
return null;
}
}
|
package ua.artcode.repository;
import ua.artcode.model.Country;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
@Component
public class CountryRepository {
private List<Country> countries;
@PostConstruct
public void initData(){
countries = new ArrayList<Country>();
Country Spain = new Country("Spain", "Madrid", 46.77, 505.99);
Country Poland = new Country("Poland", "Warsaw", 38.48, 312.68);
Country UnitedKingdom = new Country("United Kingdom", "London", 65.11, 242.49);
countries.add(Spain);
countries.add(Poland);
countries.add(UnitedKingdom);
}
public boolean addCountry(Country country){
return countries.add(country);
}
public Country getCountry(String name){
for (Country country : countries) {
if(country.getName().equals(name)) return country;
}
return null;
}
public List<Country> getAll(){
return countries;
}
}
|
package com.funnums.funnums.uihelpers;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Canvas;
import android.graphics.Paint;
/*
Adapted from James Cho's "Beginner's Guide to Android Game Development
Buttons we can use inside the game's SurfaceView, since we cannot use Android buttons inside
a SurfaceView
*/
public class UIButton {
//region of the screen corresponding to where this button can be touched
private Rect buttonRect;
private boolean buttonDown = false;
//imaged for when the button is pressed and not pressed
private Bitmap buttonImage, buttonDownImage;
public UIButton(int left, int top, int right, int bottom,
Bitmap buttonImage, Bitmap buttonPressedImage) {
//create dimensions for the button touch region
buttonRect = new Rect(left, top, right, bottom);
//set the images for the button
this.buttonImage = buttonImage;
this.buttonDownImage = buttonPressedImage;
}
public int getWidth()
{
return buttonImage.getWidth();
}
/*
Set new touch area
*/
public void setRect(int left, int top) {
buttonRect = new Rect(left, top, left + buttonImage.getWidth(),top + buttonImage.getHeight());
}
/*
Draw the button
*/
public void render(Canvas g, Paint p) {
p.setColor(Color.argb(255, 255, 255, 255));
Bitmap currentButtonImage = buttonDown ? buttonDownImage : buttonImage;
g.drawBitmap(currentButtonImage, buttonRect.left, buttonRect.top, p);
}
/*
respond when user touches button by changing the appearance of the button and setting flag
that button is pressed
*/
public boolean onTouchDown(int touchX, int touchY) {
if (buttonRect.contains(touchX, touchY)) {
buttonDown = true;
} else {
buttonDown = false;
}
return buttonDown;
}
/*
user lifted finger from button
*/
public void cancel() {
buttonDown = false;
}
/*
true when button is pressed
*/
public boolean isPressed(int touchX, int touchY) {
return buttonDown && buttonRect.contains(touchX, touchY);
}
public Bitmap getImg(){
return buttonImage;
}
public Bitmap getImgDown(){
return buttonDownImage;
}
}
|
package peace.developer.serj.photoloader.Util;
import android.graphics.Bitmap;
import android.util.LruCache;
public class CacheProvider {
private LruCache<Integer,Bitmap> mCache;
public CacheProvider (LruCache<Integer,Bitmap> cache){
mCache = cache;
}
public void saveToCache(Bitmap bitmap, int id){
mCache.put(id,bitmap);
}
public Bitmap getPhotoFromCache(int id){
return mCache.get(id);
}
}
|
package ChronoTimers;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import com.google.gson.Gson;
import Channels.Channel;
import Streams.GroupParallelStream;
import Streams.GroupStream;
import Streams.IStream;
import Streams.IndividualParallelStream;
import Streams.IndividualStream;
import Streams.ServerExportRecordFile;
import Streams.TimingRecord;
public class ChronoTimer {
public enum Event
{
IND, GRP, PARIND, PARGRP
}
public JTextPane printer;
IStream _stream;
ArrayList<IStream> _streams;
int _currentRun;
Channel _channels[];
boolean _isOn;
Clock clock;
ChronoTimer(){
_currentRun = 1;
_stream = new IndividualStream(_currentRun);
_streams = new ArrayList<IStream>();
_streams.add(_stream);
_channels = new Channel[8];
_channels[0] = new Channel();
_channels[1] = new Channel();
_channels[2] = new Channel();
_channels[3] = new Channel();
_channels[4] = new Channel();
_channels[5] = new Channel();
_channels[6] = new Channel();
_channels[7] = new Channel();
clock=Clock.systemUTC();
}
public Clock getClock(){
return clock;
}
public void turnOn(){
System.out.println("ON");
_isOn=true;
}
public void turnOff(){
System.out.println("OFF");
_isOn=false;
}
public void time(LocalDateTime set){
Clock systemClock = Clock.systemDefaultZone();
clock=Clock.offset(systemClock, Duration.between(LocalDateTime.now(), set));
//LocalDateTime check = LocalDateTime.now(clock);
//System.out.println(check.toString());
}
public void event(String eventType){
if(eventType.equalsIgnoreCase("IND")){
_stream = new IndividualStream(_currentRun);
_streams.set(_currentRun-1, _stream);
}
else if(eventType.equalsIgnoreCase("GRP")){
_stream = new GroupStream(_currentRun);
_streams.set(_currentRun-1, _stream);
}
else if(eventType.equalsIgnoreCase("PARIND")){
_stream = new IndividualParallelStream(_currentRun);
_streams.set(_currentRun-1, _stream);
}
else if(eventType.equalsIgnoreCase("PARGRP")){
_stream= new GroupParallelStream(_currentRun);
_streams.set(_currentRun-1, _stream);
}
}
public void connect(String sensorType, int channel){
if(_isOn)
{
_channels[channel-1].connect(sensorType);
}
}
public void disconnect(int channel){
if(_isOn){
_channels[channel-1] = null;
}
}
public void toggle(int channel){
if(_isOn)
{
_channels[channel-1].toggle();
}
}
public void start(){
if(_isOn)
{
_stream.startRecord(_channels[0].trigger(clock));
}
}
public void end(){
if(_isOn)
{
_stream.finishRecord(_channels[1].trigger(clock));
}
}
public void trigger(int channel)
{
if(_isOn && !(_stream instanceof GroupParallelStream)){
if(channel % 2 == 1){
_stream.startRecord(_channels[channel-1].trigger(clock));
}
else if(channel % 2 == 0){
_stream.finishRecord(_channels[channel-1].trigger(clock));
}
}
else if(_isOn && _stream instanceof GroupParallelStream){
if(channel % 2 == 1){
_stream.startRecord(_channels[channel-1].trigger(clock));
}
else if(channel % 2 == 0){
_stream.finishRecord(_channels[channel-1].trigger(clock), channel);
}
}
}
public void num(int BIBNumber)
{
if(_isOn)
{
_stream.num(BIBNumber);
}
}
public void print(){
if(_isOn)
{
if(printer == null)
System.out.println(_stream.toString());
else{
printer.setText("");
printer.setText(_stream.toString());
}
}
}
public void DNF() {
if(_isOn)
{
_stream.DNFRecord();
}
}
public void cancel() {
if(_isOn)
{
_stream.cancelRecord();
}
}
public void newRun(){
if(_isOn)
{
_stream = new IndividualStream(_currentRun);
_streams.add(_stream);
}
}
public void endRun(){
if(_isOn){
_stream = null;
_currentRun++;
}
}
public void export(int runNumber) throws FileNotFoundException{
Integer runNumberUp = new Integer(runNumber);
File file = new File("C:/Users/Noah/Documents/ChronoTimerOut/RunNumber" + runNumberUp.toString() + ".txt");
file.getParentFile().mkdirs();
PrintWriter writer = new PrintWriter(file);
writer.println(_streams.get(runNumber-1).toString());
writer.close();
try{
String jsonList = _streams.get(runNumber-1).toJSON(clock);
URL site = new URL("http://1-dot-chronotimerserverth.appspot.com/chronotimerserver");
HttpURLConnection conn = (HttpURLConnection) site.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes("data=" + jsonList);
out.close();
new InputStreamReader(conn.getInputStream());
}
catch (Exception e){
e.printStackTrace();
}
}
public String updateDisplay(){
return _stream.displayRecords(clock);
}
}
|
package componentes;
import java.awt.Font;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MeuBotao extends JButton {
public MeuBotao(String texto) {
super(texto);
}
public MeuBotao(String localImagem, String nome, boolean areaFilled, boolean borderPainted, boolean focusable) {
super(nome);
Icon icone = new ImageIcon(localImagem);
setIcon(icone);
setContentAreaFilled(areaFilled);
setBorderPainted(borderPainted);
setFocusable(focusable);
setFont();
}
public void setFont(){
setFont(new Font("Arial", Font.PLAIN, 13));
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.type.classreading;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.ClassVisitor;
import org.springframework.asm.MethodVisitor;
import org.springframework.asm.Opcodes;
import org.springframework.asm.SpringAsmInfo;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.MethodMetadata;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
/**
* ASM class visitor that creates {@link SimpleAnnotationMetadata}.
*
* @author Phillip Webb
* @author Juergen Hoeller
* @since 5.2
*/
final class SimpleAnnotationMetadataReadingVisitor extends ClassVisitor {
@Nullable
private final ClassLoader classLoader;
private String className = "";
private int access;
@Nullable
private String superClassName;
@Nullable
private String enclosingClassName;
private boolean independentInnerClass;
private final Set<String> interfaceNames = new LinkedHashSet<>(4);
private final Set<String> memberClassNames = new LinkedHashSet<>(4);
private final Set<MergedAnnotation<?>> annotations = new LinkedHashSet<>(4);
private final Set<MethodMetadata> declaredMethods = new LinkedHashSet<>(4);
@Nullable
private SimpleAnnotationMetadata metadata;
@Nullable
private Source source;
SimpleAnnotationMetadataReadingVisitor(@Nullable ClassLoader classLoader) {
super(SpringAsmInfo.ASM_VERSION);
this.classLoader = classLoader;
}
@Override
public void visit(int version, int access, String name, String signature,
@Nullable String supername, String[] interfaces) {
this.className = toClassName(name);
this.access = access;
if (supername != null && !isInterface(access)) {
this.superClassName = toClassName(supername);
}
for (String element : interfaces) {
this.interfaceNames.add(toClassName(element));
}
}
@Override
public void visitOuterClass(String owner, String name, String desc) {
this.enclosingClassName = toClassName(owner);
}
@Override
public void visitInnerClass(String name, @Nullable String outerName, String innerName, int access) {
if (outerName != null) {
String className = toClassName(name);
String outerClassName = toClassName(outerName);
if (this.className.equals(className)) {
this.enclosingClassName = outerClassName;
this.independentInnerClass = ((access & Opcodes.ACC_STATIC) != 0);
}
else if (this.className.equals(outerClassName)) {
this.memberClassNames.add(className);
}
}
}
@Override
@Nullable
public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
return MergedAnnotationReadingVisitor.get(this.classLoader, getSource(),
descriptor, visible, this.annotations::add);
}
@Override
@Nullable
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
// Skip bridge methods and constructors - we're only interested in original user methods.
if (isBridge(access) || name.equals("<init>")) {
return null;
}
return new SimpleMethodMetadataReadingVisitor(this.classLoader, this.className,
access, name, descriptor, this.declaredMethods::add);
}
@Override
public void visitEnd() {
MergedAnnotations annotations = MergedAnnotations.of(this.annotations);
this.metadata = new SimpleAnnotationMetadata(this.className, this.access,
this.enclosingClassName, this.superClassName, this.independentInnerClass,
this.interfaceNames, this.memberClassNames, this.declaredMethods, annotations);
}
public SimpleAnnotationMetadata getMetadata() {
Assert.state(this.metadata != null, "AnnotationMetadata not initialized");
return this.metadata;
}
private Source getSource() {
Source source = this.source;
if (source == null) {
source = new Source(this.className);
this.source = source;
}
return source;
}
private String toClassName(String name) {
return ClassUtils.convertResourcePathToClassName(name);
}
private boolean isBridge(int access) {
return (access & Opcodes.ACC_BRIDGE) != 0;
}
private boolean isInterface(int access) {
return (access & Opcodes.ACC_INTERFACE) != 0;
}
/**
* {@link MergedAnnotation} source.
*/
private static final class Source {
private final String className;
Source(String className) {
this.className = className;
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof Source that && this.className.equals(that.className)));
}
@Override
public int hashCode() {
return this.className.hashCode();
}
@Override
public String toString() {
return this.className;
}
}
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(SensorBridge)网桥管理
//generate by redcloud,2020-07-24 19:59:20
public class SensorBridge implements Serializable {
private static final long serialVersionUID = 52L;
// 主键id
private Long id ;
// 设备名称
private String titel ;
// IP地址
private String ip ;
// 厂商
private String firm ;
// 创建时间
private Long created ;
// 修改时间
private Long updated ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitel() {
return titel ;
}
public void setTitel(String titel) {
this.titel = titel;
}
public String getIp() {
return ip ;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getFirm() {
return firm ;
}
public void setFirm(String firm) {
this.firm = firm;
}
public Long getCreated() {
return created ;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated ;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
}
|
package org.point85.domain.dto;
import org.point85.domain.collector.CollectorDataSource;
public abstract class CollectorDataSourceDto extends NamedObjectDto {
private String host;
private String userName;
private String userPassword;
private String sourceType;
private Integer port;
protected CollectorDataSourceDto(CollectorDataSource source) {
super(source);
this.host = source.getHost();
this.userName = source.getUserName();
this.userPassword = source.getEncodedPassword();
this.sourceType = source.getDataSourceType() != null ? source.getDataSourceType().name() : null;
this.port = source.getPort();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getSourceType() {
return sourceType;
}
public void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}
|
package com.example.restclients2;
/**
* Created by NSG1 on 3/4/2015.
*/
public class getset
{
public int id;
public void set(int id)
{
this.id=id;
}
public int get()
{
return this.id;
}
}
|
/* ScalableTimerTask.java
Purpose:
Description:
History:
Wed Dec 5 14:31:40 2007, Created by tomyeh
Copyright (C) 2007 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.util;
import java.util.TimerTask;
/**
* A task that can be scheduled for one-time execution by
* a scalable timer ({@link ScalableTimer}.
*
* @author tomyeh
* @since 3.0.1
*/
abstract public class ScalableTimerTask extends TimerTask {
private ScalableTimerInfo _ti;
/*package*/ void setScalableTimerInfo(ScalableTimerInfo ti) {
_ti = ti;
}
/** The action to be performed by this timer task.
* The derived class must override this method instead of {@link #run}.
*/
abstract public void exec();
//super//
/** Invokes {@link #exec}.
* The derived class shall not override this method.
* Rather, override {@link #exec} instead.
*/
final public void run() {
setCalled();
exec();
}
/** Cancels this timer task.
*
* @return true if this task is scheduled for one-time execution and has not yet run.
* Returns false if the task was scheduled for one-time execution and has already run.
*/
public boolean cancel() {
final boolean b = super.cancel();
if (b) setCalled();
return b;
}
private void setCalled() {
if (_ti != null) {
synchronized (_ti) {
--_ti.count;
}
_ti = null;
}
}
}
|
package com.example.attest.service;
import com.example.attest.model.api.TransactionApi;
import com.example.attest.model.domain.Account;
public interface AccountService {
Account updateBalance(TransactionApi transactionApi);
}
|
package com.memory.platform.modules.system.base.service;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.memory.platform.core.service.IBaseService;
import com.memory.platform.modules.system.base.model.SystemDept;
import com.memory.platform.modules.system.base.model.SystemRole;
import com.memory.platform.modules.system.base.model.SystemUser;
import com.utils.file.model.SysUser;
public interface ISystemUserService extends IBaseService<SystemUser> {
/**
* 查询用户的所有部门
* @param userId
* @return
*/
public List<SystemDept> listUserDepts(String userId);
/**
* 查询用户的所有角色
* @param userId
* @return
*/
public List<SystemRole> listUserRoles(String userId);
public List<SystemUser> findUsers(String loginName, String pwd);
public void saveClientInfo(SystemUser user, HttpServletRequest request, String sessionId);
/**
* 批量保存用户
* @param list
*/
void saveUsers(List<SysUser> list);
}
|
package com.brainacademy.gui.bundle;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.*;
public class Application {
private static class MainFrame extends JFrame {
private JButton button1;
private JButton button2;
private JLabel label;
public MainFrame() {
super();
setMinimumSize(new Dimension(400, 300));
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
button1 = new JButton();
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Locale.setDefault(new Locale("en", "EN"));
updateTextMessage();
}
});
button2 = new JButton();
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Locale.setDefault(new Locale("ru", "RU"));
updateTextMessage();
}
});
label = new JLabel();
getContentPane().add(label);
getContentPane().add(button1);
getContentPane().add(button2);
updateTextMessage();
pack();
}
private void updateTextMessage() {
ResourceBundle bundle = ResourceBundle.getBundle("i18n.Bundle");
setTitle(bundle.getString("frame.title"));
button1.setText(bundle.getString("button.en.text"));
button2.setText(bundle.getString("button.ru.text"));
label.setText(bundle.getString("label.text"));
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Locale.setDefault(new Locale("ru", "RU"));
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
});
}
}
|
package com.test;
/**
* https://leetcode.com/problems/house-robber/
*
* 递推式: result[i] = Math.max(nums[i] + result[i-2], nums[i-1] + result[i - 3])
*
* @author yline
*/
public class SolutionA
{
public int rob(int[] nums) {
if (null == nums || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
if (nums.length == 2) {
return Math.max(nums[0], nums[1]);
}
if (nums.length == 3) {
return Math.max(nums[1], nums[0] + nums[2]);
}
int[] maxArray = new int[nums.length];
maxArray[0] = nums[0];
maxArray[1] = Math.max(nums[0], nums[1]);
maxArray[2] = Math.max(nums[1], maxArray[0] + nums[2]);
for (int i = 3; i < nums.length; i++) {
maxArray[i] = Math.max(nums[i] + maxArray[i-2],
nums[i-1] + maxArray[i-3]);
}
return Math.max(maxArray[nums.length - 1], maxArray[nums.length - 2]);
}
}
|
package Stack;
import java.util.Stack;
/*Reverse a string word by word
* Example
* Original Sentence : Hello, How are you?
* Reversing sentence using stack : you? are How Hello, */
public class StackReverseStringWordByWord {
public static void reverseStringWithStack(String sentence)
{
if(sentence == null)
return;
if(sentence.length() < 0)
return;
else
{
char[] sentenceChar = sentence.toCharArray();
Stack<String> stack = new Stack<String>();
StringBuilder s = new StringBuilder();
for(int i=0; i<sentenceChar.length;i++)
{
s = s.append(sentenceChar[i]);
if(sentenceChar[i] ==' ')
{
stack.push(s.toString());
s.setLength(0);
}
if(i == sentenceChar.length - 1)
{
s=s.append(" ");
stack.push(s.toString());
s.setLength(0);
}
}
while(!stack.isEmpty())
System.out.print(stack.pop());
}
}
public static void main(String args[])
{
String sentence = "Hello, How are you?";
System.out.println("Original Sentence : "+sentence);
System.out.print("Reversing sentence using stack : ");
reverseStringWithStack(sentence);
}
}
|
package filter;
import com.sun.deploy.net.HttpRequest;
import dbutil.DBUtil;
import entities.Users;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/filter.UserFilter")
public class UserFilter implements Filter {
DBUtil dbUtil;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
boolean userOnline = false;
Users users = (Users) ((HttpServletRequest) req).getSession().getAttribute("login");
if (users!=null) {
System.out.println(users.getName()+" is online!");
}
if (users != null) {
Users tmpUser = dbUtil.getUserByEmailAndPassword(users.getEmail(), users.getPassword());
if (tmpUser != null) {
userOnline = true;
req.setAttribute("userOnline", userOnline);
}
}
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
dbUtil = new DBUtil();
}
}
|
package util;
import java.io.PrintStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/**
* Class <code>MemoryTest</code> can be used to print out the memory usage every so often.
*
* @author "Austin Shoemaker" <austin@genome.arizona.edu>
* @see TimerTask
*/
public class MemoryTest extends TimerTask {
private static Timer timer = null;
/**
* Method <code>run</code> creates a new timer and schedules it to run every <code>timeBetweenTests</code>
* milliseconds. If this method has already been called without the stop method being called, nothing is done.
*
* @param timeBetweenTests an <code>int</code> value of time in milliseconds between tests
* @param out a <code>PrintStream</code> value of ouput PrintStream to print the usage to
*/
public synchronized static void run(int timeBetweenTests, PrintStream out) {
if (timer == null) {
timer = new Timer(true);
timer.schedule(new MemoryTest(out), new Date(), timeBetweenTests);
}
}
/**
* Method <code>stop</code> stops the timer if it was running.
*
*/
public synchronized static void stop() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
private PrintStream out;
private MemoryTest(PrintStream out) {
super();
this.out = out;
}
/**
* Method <code>run</code> acquires the free and total memory and prints it out to
* the given PrintStream in the form: "<free>\t<total>\t<free/total>"
*/
public void run() {
long free = Runtime.getRuntime().freeMemory();
long total = Runtime.getRuntime().totalMemory();
//double usage = free / (double) total;
out.println(free + "\t" + total + "\t" + (free / (double) total));
}
}
|
package no_spring.car;
import no_spring.audio.Alpine;
import no_spring.audio.Sony;
import no_spring.navigation.Garmin;
public class Audi2 {
public Alpine audioSystem = new Alpine();
public Garmin navigationSystem = new Garmin();
public void move() {
System.out.println("*****************************");
System.out.println("Audi in action");
System.out.println("*****************************");
}
}
|
package com.example.sypark9646.item21;
@FunctionalInterface
public interface Calculation {
Integer apply(Integer x, Integer y);
}
|
package org.juxtasoftware.service;
import org.junit.After;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import eu.interedition.text.rdbms.RelationalNameRepository;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/applicationContext-dataSource.xml", "classpath:/applicationContext-service.xml"})
public abstract class AbstractTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired protected RelationalNameRepository nameRepository;
@After
public void clearNameCache() {
nameRepository.clearCache();
}
}
|
package com.hzy.lamedemo;
import java.util.Calendar;
import java.util.Date;
public class CommonUtils {
public static String generateMp3FileName(){
long backTime = new Date().getTime();
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(backTime));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int date = cal.get(Calendar.DAY_OF_MONTH);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
String time = "rec_" + year + month + date + hour + minute + second + ".mp3";
return time;
}
}
|
package com.penglai.haima.ui.charge;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lzy.okgo.OkGo;
import com.penglai.haima.R;
import com.penglai.haima.base.BaseActivity;
import com.penglai.haima.base.Constants;
import com.penglai.haima.bean.ApplyAccountBean;
import com.penglai.haima.bean.UserInfoBean;
import com.penglai.haima.callback.DialogCallback;
import com.penglai.haima.callback.JsonCallback;
import com.penglai.haima.dialog.MessageShowDialog;
import com.penglai.haima.okgomodel.CommonReturnData;
import com.penglai.haima.utils.ClickUtil;
import com.penglai.haima.utils.SharepreferenceUtil;
import butterknife.BindView;
import butterknife.OnClick;
public class ChargeApplyActivity extends BaseActivity {
@BindView(R.id.tv_apply_balance)
TextView tvApplyBalance;
@BindView(R.id.ll_person_balance)
LinearLayout llPersonBalance;
@BindView(R.id.et_zfb_account)
EditText etZfbAccount;
@BindView(R.id.et_zfb_name)
EditText etZfbName;
@BindView(R.id.tv_charge_apply)
TextView tvChargeApply;
@BindView(R.id.et_apply_money)
EditText etApplyMoney;
private String balance;//余额
MessageShowDialog messageShowDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitleMiddleText("提现");
}
@Override
public int setBaseContentView() {
return R.layout.activity_charge_apply;
}
@Override
public void init() {
getIndexData();
setAccountInfo();
}
@OnClick(R.id.tv_charge_apply)
public void onViewClicked() {
if (ClickUtil.isFastDoubleClick()) {
return;
}
if (TextUtils.isEmpty(balance)) {
return;
}
String account = etZfbAccount.getText().toString().trim();
String name = etZfbName.getText().toString().trim();
if (TextUtils.isEmpty(account)) {
showToast("请输入支付宝账号");
return;
}
if (TextUtils.isEmpty(name)) {
showToast("请输入支付宝姓名");
return;
}
String amount = etApplyMoney.getText().toString().trim();
if (TextUtils.isEmpty(amount)) {
showToast("请输入金额");
return;
}
if (Integer.parseInt(amount) > Integer.parseInt(balance)) {
showToast("余额不足");
return;
}
if (Double.parseDouble(amount) < 10) {
showToast("提现金额小于最低提现金额(10元)");
return;
}
Apply(account, name, amount);
}
/**
* 获取余额
*/
private void getIndexData() {
OkGo.<CommonReturnData<UserInfoBean>>get(Constants.BASE_URL + "getUserInfo")
.execute(new DialogCallback<CommonReturnData<UserInfoBean>>(this, true) {
@Override
public void onSuccess(CommonReturnData<UserInfoBean> commonReturnData) {
UserInfoBean userInfo = commonReturnData.getData();
balance = userInfo.getBalance();
tvApplyBalance.setText(balance + "元");
}
});
}
/**
* 提现账户信息
*/
private void setAccountInfo() {
if (TextUtils.isEmpty(SharepreferenceUtil.getString(Constants.APPLY_ACCOUNT_NO))) {
getAccountInfo();
} else {
etZfbAccount.setText(SharepreferenceUtil.getString(Constants.APPLY_ACCOUNT_NO));
etZfbName.setText(SharepreferenceUtil.getString(Constants.APPLY_ACCOUNT_NAME));
}
}
/**
* 提现账户信息
*/
private void getAccountInfo() {
OkGo.<CommonReturnData<ApplyAccountBean>>post(Constants.BASE_URL + "withdraw/getLast")
.execute(new JsonCallback<CommonReturnData<ApplyAccountBean>>(this, false) {
@Override
public void onSuccess(CommonReturnData<ApplyAccountBean> commonReturnData) {
ApplyAccountBean data = commonReturnData.getData();
if (!TextUtils.isEmpty(data.getUser_account())) {
etZfbAccount.setText(data.getUser_account());
etZfbName.setText(data.getUser_name());
}
}
});
}
/**
* 申请提现
*/
private void Apply(final String account, final String name, String amount) {
OkGo.<CommonReturnData<Object>>post(Constants.BASE_URL + "withdraw/insertAccount")
.params("account", account)
.params("name", name)
.params("amount", amount)
.execute(new DialogCallback<CommonReturnData<Object>>(this, false) {
@Override
public void onSuccess(CommonReturnData<Object> commonReturnData) {
SharepreferenceUtil.saveString(Constants.APPLY_ACCOUNT_NO, account);
SharepreferenceUtil.saveString(Constants.APPLY_ACCOUNT_NAME, name);
//弹出提示
messageShowDialog = new MessageShowDialog(ChargeApplyActivity.this, new MessageShowDialog.OperateListener() {
@Override
public void sure() {
ChargeApplyActivity.this.finish();
}
});
messageShowDialog.setContentText("申请成功,等待打款");
messageShowDialog.show();
}
});
}
}
|
package com.blackflagbin.kcommondemowithjava.common.entity.net;
/**
* Created by blackflagbin on 2018/3/25.
*/
public class DataItem {
/**
* desc : 还在用ListView?
* ganhuo_id : 57334c9d67765903fb61c418
* publishedAt : 2016-05-12T12:04:43.857000
* readability :
* type : Android
* url : http://www.jianshu.com/p/a92955be0a3e
* who : 陈宇明
*/
public String desc;
public String ganhuo_id;
public String publishedAt;
public String readability;
public String type;
public String url;
public String who;
}
|
package com.cloudaping.cloudaping.controller;
import com.cloudaping.cloudaping.entity.User;
import com.cloudaping.cloudaping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Map;
@Controller
@RequestMapping(value = "/userPage/")
public class UserPageController {
private static final String USERPAGE_PATH = "userPage";
private static final String INFORMATION_PATH = USERPAGE_PATH + "/information";
private static final String ORDER_PATH = USERPAGE_PATH + "/order";
private static final String ADDRESS_PATH = USERPAGE_PATH + "/address";
private static final String PAYMENT_PATH = USERPAGE_PATH + "/payment";
private static final String FAVOURITE_PATH = USERPAGE_PATH + "/favourite";
private static final String PASSWORD_CHANGE_PATH = USERPAGE_PATH + "/password_change";
@Autowired
private UserService userService;
@GetMapping(path = "information")
public String getInformation(HttpSession session,
Map<String,Object> map) {
User user= (User) session.getAttribute("user");
map.put("user",user);
return INFORMATION_PATH;
}
@PostMapping(path = "information")
public String editInformation(HttpSession session,
@Valid User user,
Map<String,Object> map) {
User exsitsUser= (User) session.getAttribute("user");
user.setUserId(exsitsUser.getUserId());
user.setPassword(exsitsUser.getPassword());
session.setAttribute("user",user);
user= userService.save(user);
map.put("user",user);
return INFORMATION_PATH;
}
@GetMapping(path = "order")
public String getOrder() {
return ORDER_PATH;
}
@GetMapping(path = "address")
public String getAddress() {
return ADDRESS_PATH;
}
@GetMapping(path = "payment")
public String getPayment() {
return PAYMENT_PATH;
}
@GetMapping(path = "favourite")
public String getFavourite() {
return FAVOURITE_PATH;
}
@GetMapping(path = "password_change")
public String getPasswordChange() {
return PASSWORD_CHANGE_PATH;
}
@GetMapping(path = "logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:../index";
}
}
|
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.ext.jooqflyway.jobactivity;
import javax.inject.Inject;
import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.titus.common.util.SpringConfigurationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
@Configuration(prefix = "titus.ext.jooqflyway")
public class JooqConfiguration {
private static final String PREFIX = "titus.ext.jooqflyway.";
//private final Environment environment;
@Autowired
Environment environment;
/*@Inject
public JooqConfiguration(Environment environment) {
this.environment = environment;
}*/
public String getDatabaseUrl() {
return SpringConfigurationUtil.getString(environment, PREFIX + "databaseUrl", "jdbc://notSet");
}
public boolean isInMemoryDb() {
return SpringConfigurationUtil.getBoolean(environment, PREFIX + "inMemoryDb", false);
}
public String getProducerDatatabaseUrl() {
return SpringConfigurationUtil.getString(environment, PREFIX + "producer.databaseUrl", "jdbc://notSet");
}
}
|
package com.mahendran.parallelFiles;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.multipart.MultipartFile;
import com.mahendran.parallelFiles.controllers.MainController;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class TestParallelController {
@Autowired
private MainController controller;
@Autowired
private MockMvc mockMvc;
@Test
public void contextLoads() {
assertThat(controller).isNotNull();
}
@Test
public void testHomePage() throws Exception {
this.mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().contentType("text/html;charset=UTF-8"));
}
@Test
public void testUpload() throws Exception {
MultipartFile[] fileArray = new MultipartFile[]{
};
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/upload").file(new MockMultipartFile("test.txt",
"test.txt",
"text/plain",
"ThiS Is a Test\r\nOOOOoooOoO".getBytes(StandardCharsets.UTF_8)))
.file(new MockMultipartFile("test2.txt",
"test2.txt",
"text/plain",
"&^%*^&SKNJHKJHJKKJDDHHssssssest\r\nOOOOo444444ooOoO".getBytes(StandardCharsets.UTF_8))))
.andExpect(status().isOk());
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.ioc;
import org.junit.Test;
import xyz.noark.core.ioc.demo.BagService;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* IOC测试.
*
* @author 小流氓[176543888@qq.com]
* @since 3.0
*/
public class NoarkIocTest {
@Test
public void test() {
Ioc ioc = new NoarkIoc("xyz.noark.core.ioc.demo");
BagService bagService = ioc.get(BagService.class);
assertNotNull(bagService);
assertNotNull(bagService.getItemService());
assertNotNull(bagService.getVipService());
assertNotNull(bagService.getCommands());
assertTrue(bagService.getCommands().size() == 3);
assertTrue(bagService.getCommandList().size() == 3);
// Map注入...
assertTrue("rmb".equals(bagService.getCommands().get("// add rmb").doSomething()));
assertTrue("item".equals(bagService.getCommands().get("// add item").doSomething()));
assertTrue("exp".equals(bagService.getCommands().get("// add exp").doSomething()));
System.out.println(bagService.getCommandList());
}
}
|
package be.kdg.fastrada.controllers;
import be.kdg.canbus.car.config.Car;
import be.kdg.canbus.controllers.HexController;
import be.kdg.canbus.controllers.ZipController;
import be.kdg.canbus.data.TransportMessage;
import be.kdg.fastrada.dao.Repository;
import be.kdg.fastrada.logic.MessageMapper;
import be.kdg.fastrada.model.DatabaseMessage;
import be.kdg.fastrada.model.LayoutConfig;
import be.kdg.fastrada.model.Run;
import be.kdg.fastrada.model.User;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* Controller that handles the REST calls from an android application.
*/
@Controller
@SessionAttributes
@Scope("request")
public class AndroidController {
private static Logger logger = Logger.getLogger(AndroidController.class);
@Autowired
private User user;
private Repository<User> userRepository;
private Repository<DatabaseMessage> messageRepository;
private Repository<Car> configRepository;
private Repository<LayoutConfig> layoutRepository;
private BCryptPasswordEncoder encoder;
@Autowired
private MessageMapper messageMapper;
@Autowired
public AndroidController(
@Qualifier("userRepositoryImpl") Repository<User> userRepository,
@Qualifier("messageRepositoryImpl") Repository<DatabaseMessage> messageRepository,
@Qualifier("configRepositoryImpl") Repository<Car> configRepository,
@Qualifier("layoutRepositoryImpl") Repository<LayoutConfig> layoutRepository) {
this.layoutRepository = layoutRepository;
this.userRepository = userRepository;
this.messageRepository = messageRepository;
this.configRepository = configRepository;
this.encoder = new BCryptPasswordEncoder();
}
@RequestMapping(value = "/android/login.do", method = RequestMethod.POST)
public
@ResponseBody
boolean login(@RequestParam String username, @RequestParam String password) {
try {
user = userRepository.getObjectById(username);
return user != null && encoder.matches(password, user.getPassword());
} catch (Exception e) {
return false;
}
}
@RequestMapping(value = "/android/getConfigurationList.do", method = RequestMethod.GET)
public
@ResponseBody
String list() {
List<Car> cars = configRepository.getAllObjects();
String carList = "";
for (Car c : cars) {
carList += c.getName() + "~";
}
return carList;
}
@RequestMapping(value = "/android/getSpecificConfiguration.do", method = RequestMethod.POST)
public
@ResponseBody
Car getSpecificConfiguration(@RequestParam String configurationName) {
return configRepository.getObjectById(configurationName);
}
@RequestMapping(value = "/android/startRun.do", method = RequestMethod.POST)
public
@ResponseBody
boolean startRun(@RequestParam String username, @RequestParam String password, @RequestParam String usedConfiguration) {
try {
User user = userRepository.getObjectById(username);
if (user != null) {
if (encoder.matches(password, user.getPassword())) {
user.addRun(new Run(usedConfiguration));
userRepository.updateObject(user);
return true;
}
}
return false;
} catch (Exception e) {
return false;
}
}
@RequestMapping(value = "/android/transportData.do", method = RequestMethod.POST)
public
@ResponseBody
boolean receiveData(@RequestParam String hexadecimalCompressedData, @RequestParam String usedConfiguration) {
try {
List<TransportMessage> messagesList = ZipController.unZip(HexController.hexStringToByteArray(hexadecimalCompressedData));
List<DatabaseMessage> messages;
messages = messageMapper.parseToMessage(messagesList, usedConfiguration);
messageRepository.saveList(messages);
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
}
@RequestMapping(value = "/android/getLayout.do", method = RequestMethod.POST)
public
@ResponseBody
LayoutConfig getLayout(@RequestParam String userId) {
return layoutRepository.getObjectById(userId);
}
@RequestMapping(value = "/android/updateLayout.do", method = RequestMethod.POST)
public
@ResponseBody
boolean updateLayout(@RequestBody LayoutConfig newLayout) {
try {
newLayout.setId(newLayout.getId());
// List<LayoutConfig> existing = layoutRepository.getObjectsByAttribute("id",newLayout.getId());
LayoutConfig existing = layoutRepository.getObjectById(newLayout.getId());
if (existing != null) {
layoutRepository.deleteObject(newLayout.getId());
layoutRepository.saveObject(newLayout);
} else {
layoutRepository.saveObject(newLayout);
}
} catch (Exception e) {
logger.error(e.getMessage());
return false;
}
return true;
}
}
|
package com.tpg.brks.ms.expenses.persistence.entities;
import com.tpg.brks.ms.expenses.domain.AssignmentStatus;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
@Table(name = "assignments_tbl", schema = "brks_expenses")
@Entity(name = "Assignment")
@SequenceGenerator( name = "seq_generator", sequenceName = "assignments_seq" )
@Getter
@Setter
public class AssignmentEntity extends DescriptionEntity {
@NotNull
@ManyToOne
@JoinTable(name = "accounts_assignments_tbl",
joinColumns = @JoinColumn(name = "account_id"),
inverseJoinColumns = @JoinColumn(name = "assignment_id")
)
private AccountEntity account;
@NotNull
@Column(name="start_date")
private Date startDate;
@Column(name="end_date")
private Date endDate;
@NotNull
@Column(name = "assign_status")
@Enumerated(EnumType.STRING)
private AssignmentStatus status;
@OneToMany(mappedBy = "assignment")
private List<ExpenseReportEntity> expenseReports;
public AssignmentEntity() {}
}
|
package uk.ac.ebi.intact.view.webapp.application;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
/**
* This class is for all classes that need to be initialized with a transaction
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>10/09/12</pre>
*/
@Service
public class SpringInitializedService implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private TransactionTemplate tt;
private static final Log log = LogFactory.getLog(SpringInitializedService.class);
public SpringInitializedService() {
}
public SpringInitializedService(PlatformTransactionManager tm){
tt.setTransactionManager(tm);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try{
initialize();
}
catch (Exception ex){
log.error("Error during initialization",ex);
status.setRollbackOnly();
}
}
});
}
public void initialize(){
}
public synchronized void onReload(){
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try{
reload();
}
catch (Exception ex){
log.error("Error during initialization",ex);
status.setRollbackOnly();
}
}
});
}
public synchronized void reload(){
}
}
|
package viewer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Scanner;
import controller.ReplyWesternController;
import model.ReplyWesternDTO;
import model.WesternDTO;
import util.ScannerUtil;
public class ReplyWesternViewer {
private ReplyWesternController controller;
private Scanner sc;
private final String FORMAT_STRING = new String("y.M.d.a.h.m");
private UserViewer userViewer;
public ReplyWesternViewer(UserViewer userViewer) {
controller = new ReplyWesternController();
sc = new Scanner(System.in);
this.userViewer = userViewer;
}
public void printList(WesternDTO w) {
while (true) {
ArrayList<ReplyWesternDTO> list = controller.selectById(w.getFoodId());
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_STRING);
for (ReplyWesternDTO RW : list) {
System.out.printf("%d. %s - %s(%s)\n", RW.getId(), RW.getContent(),
userViewer.selectNameById(RW.getWriterId()).getNickname(),
sdf.format(RW.getWrittenDate().getTime()));
}
if (userViewer.logInNull()) {
String message = new String("1. 뒤로가기");
ScannerUtil.nextInt(sc, message, 1, 1);
break;
}
String message = new String("1. 댓글 등록 2. 삭제 3. 뒤로가기");
int userChoice = ScannerUtil.nextInt(sc, message, 1, 3);
if(userChoice == 1) {
// 댓글 등록 메서드
insert(w);
}else if(userChoice == 2) {
message = new String("삭제할 댓글의 번호를 입력해주세요.");
userChoice = ScannerUtil.nextInt(sc, message);
ReplyWesternDTO RW = controller.selectOne(userChoice);
while(RW == null) {
System.out.println("땡 오류!!!!!!!!");
userChoice = ScannerUtil.nextInt(sc, message);
RW = controller.selectOne(userChoice);
}
// 삭제 메소드
delete(userChoice);
}else if(userChoice == 3) {
break;
}
}
}
// 입력 메소드
public void insert(WesternDTO w) {
ReplyWesternDTO we = new ReplyWesternDTO();
String message = new String("댓글을 입력해주세요.");
we.setContent(ScannerUtil.nextLine(sc, message));
we.setFoodId(w.getFoodId());
we.setWriterId(userViewer.logInId());
controller.add(we);
}
// 삭제 메소드
public void delete(int id) {
ReplyWesternDTO RW = controller.selectOne(id);
if(RW.getWriterId() == userViewer.logInId()) {
String message = new String("정말로 삭제하시겠습니까? y/n");
String yesno = ScannerUtil.nextLine(sc, message);
if(yesno.equalsIgnoreCase("y")) {
controller.delete(RW);
}
}else {
System.out.println("자신이 작성한 댓글만 삭제 가능합니다.");
}
}
}
|
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.format.number.money;
import java.util.Locale;
import javax.money.MonetaryAmount;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryFormats;
import org.springframework.format.Formatter;
import org.springframework.lang.Nullable;
/**
* Formatter for JSR-354 {@link javax.money.MonetaryAmount} values,
* delegating to {@link javax.money.format.MonetaryAmountFormat#format}
* and {@link javax.money.format.MonetaryAmountFormat#parse}.
*
* @author Juergen Hoeller
* @since 4.2
* @see #getMonetaryAmountFormat
*/
public class MonetaryAmountFormatter implements Formatter<MonetaryAmount> {
@Nullable
private String formatName;
/**
* Create a locale-driven MonetaryAmountFormatter.
*/
public MonetaryAmountFormatter() {
}
/**
* Create a new MonetaryAmountFormatter for the given format name.
* @param formatName the format name, to be resolved by the JSR-354
* provider at runtime
*/
public MonetaryAmountFormatter(String formatName) {
this.formatName = formatName;
}
/**
* Specify the format name, to be resolved by the JSR-354 provider
* at runtime.
* <p>Default is none, obtaining a {@link MonetaryAmountFormat}
* based on the current locale.
*/
public void setFormatName(String formatName) {
this.formatName = formatName;
}
@Override
public String print(MonetaryAmount object, Locale locale) {
return getMonetaryAmountFormat(locale).format(object);
}
@Override
public MonetaryAmount parse(String text, Locale locale) {
return getMonetaryAmountFormat(locale).parse(text);
}
/**
* Obtain a MonetaryAmountFormat for the given locale.
* <p>The default implementation simply calls
* {@link javax.money.format.MonetaryFormats#getAmountFormat}
* with either the configured format name or the given locale.
* @param locale the current locale
* @return the MonetaryAmountFormat (never {@code null})
* @see #setFormatName
*/
protected MonetaryAmountFormat getMonetaryAmountFormat(Locale locale) {
if (this.formatName != null) {
return MonetaryFormats.getAmountFormat(this.formatName);
}
else {
return MonetaryFormats.getAmountFormat(locale);
}
}
}
|
/*
* @(#) IPartnerInfoDAO.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.partnerinfo.dao;
import java.util.List;
import java.util.Map;
import com.esum.appframework.dao.IBaseDAO;
import com.esum.appframework.exception.ApplicationException;
/**
*
* @author heowon@esumtech.com
* @version $Revision: 1.1 $ $Date: 2008/07/31 01:50:04 $
*/
public interface IPartnerInfoDAO extends IBaseDAO {
List partnerInfoDetail(Object object) throws ApplicationException;
List partnerInfoPageList(Object object) throws ApplicationException;
List searchSvcIdPageList(Object object) throws ApplicationException;
Object insertSvcInfo(Object object)throws ApplicationException;
int updateSvcInfo(Object object)throws ApplicationException;
Object deleteSvcInfo(Object object)throws ApplicationException;
List svcInfoDetail(Object object) throws ApplicationException;
Object countTpIdUsingSvcId(Object object)throws ApplicationException;
Map savePartnerInfoExcel(Object object)throws ApplicationException;
Map savePartnerInfoExcel2(Object object)throws ApplicationException;
Map selectParterCountByType(Object object) throws ApplicationException;
}
|
package com.land.back.nomapping;
import java.util.List;
public class ConceptoDinamico {
private int orden;
private String concepto = "";
private List<DiaDinamico> list;
private boolean edit;
public int getOrden() {
return orden;
}
public void setOrden(int orden) {
this.orden = orden;
}
public String getConcepto() {
return concepto;
}
public void setConcepto(String concepto) {
this.concepto = concepto;
}
public List<DiaDinamico> getList() {
return list;
}
public void setList(List<DiaDinamico> list) {
this.list = list;
}
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public void edit() {
if (edit) {
edit = false;
} else {
edit = true;
}
}
}
|
package lets_explore;
public class Jumping_Statement {
public static void main(String args[])
{
// Jumping Statement
// continue
System.out.println("continue");
for(int i=1; i <= 7; i++)
{
if(i == 4)
{
continue; // exits from particular condition.
}
System.out.println("Value is " + i);
}
System.out.println("break");
// break
for(int i=1; i <= 7; i++)
{
if(i == 4)
{
break; // exits from whole loop and not run the code for remaining condition.
}
System.out.println("Value is " + i);
}
}
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.OrderFormLog;
@Repository("orderFormLogDAO")
public class OrderFormLogDAO extends GenericDAO<OrderFormLog> {
}
|
package com.uchain.core;
import com.uchain.core.transaction.Transaction;
@FunctionalInterface
public interface NotificationOnTransaction {
void onTransaction(Transaction trx);
}
|
package com.ipincloud.iotbj.srv.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.ipincloud.iotbj.api.utils.hik.ApiService;
import com.ipincloud.iotbj.srv.dao.RegionDao;
import com.ipincloud.iotbj.srv.domain.Region;
import com.ipincloud.iotbj.srv.service.RegionService;
import com.ipincloud.iotbj.utils.ParaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
//(Region)区域 服务实现类
//generate by redcloud,2020-07-23 11:43:18
@Service("RegionService")
public class RegionServiceImpl implements RegionService {
@Resource
private RegionDao regionDao;
@Value("${hikEnable}")
private boolean hikEnable;
//@param id 主键
//@return 实例对象Region
@Override
public Region queryById(Long id) {
return this.regionDao.queryById(id);
}
//@param jsonObj 调用参数
//@return 影响记录数
@Override
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Integer deletesRegionInst(JSONObject jsonObj) {
Integer delNum1 = this.regionDao.deletesInst(jsonObj);
return delNum1;
}
//@param jsonObj 过滤条件等
//@return 对象Region 树形查询
@Override
public List<Map> regionTree(JSONObject jsonObj) {
if (ParaUtils.notHaveColVal(jsonObj, "parent_id") != null && ParaUtils.notHaveColVal(jsonObj, "parent_id").length() > 0) {
return this.regionDao.queryTreeHp(jsonObj);
} else {
return this.regionDao.queryTreeNp(jsonObj);
}
}
//@param jsonObj 调用参数
//@return 实例对象Region
@Override
public JSONObject addInst(JSONObject jsonObj) {
jsonObj = ParaUtils.removeSurplusCol(jsonObj, "id,title,parent_id,regionIndexCode,indexCode,parentIndexCode");
Region region = regionDao.queryById(jsonObj.getLong("parent_id"));
String parentIndexCode = region.getIndexCode();
jsonObj.put("indexCode", UUID.randomUUID().toString());
jsonObj.put("parentIndexCode", parentIndexCode);
this.regionDao.addInst(jsonObj);
if (hikEnable) {
List<JSONObject> list = new ArrayList();
JSONObject regionObj = new JSONObject();
regionObj.put("clientId", jsonObj.getLong("id"));
regionObj.put("regionCode", jsonObj.getString("indexCode"));
regionObj.put("regionName", jsonObj.getString("title"));
regionObj.put("parentIndexCode", parentIndexCode);
regionObj.put("regionType", 10);
regionObj.put("description", null);
list.add(regionObj);
ApiService.addBatchRegion(list);
}
return jsonObj;
}
//@param jsonObj 调用参数
//@return 影响记录数Region
@Override
public void updateInst(JSONObject jsonObj) {
jsonObj = ParaUtils.removeSurplusCol(jsonObj, "id,title,parent_id,regionIndexCode,indexCode,parentIndexCode");
this.regionDao.updateInst(jsonObj);
if (hikEnable) {
JSONObject region = new JSONObject();
region.put("regionIndexCode", jsonObj.getString("indexCode"));
region.put("regionName", jsonObj.getString("title"));
ApiService.updateRegion(region);
}
}
}
|
package com.tt.rendezvous.motor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.facet.FacetBuilders;
import org.elasticsearch.search.facet.terms.TermsFacet;
import org.jsoup.helper.StringUtil;
public class SimpleElasticSearchFacade {
private static Logger log = Logger
.getLogger(SimpleElasticSearchFacade.class);
ClusterAdmin cluster;
public SimpleElasticSearchFacade() {
try {
cluster = new ClusterAdmin();
cluster.startCluster();
Client client = cluster.getClient();
client.prepareIndex();
} catch (IOException e) {
log.error("Error while creating a new cluster", e);
}
}
public static Map<String, Object> putJsonDocument(String title,
String content, Date postDate, String tags, String author) {
Map<String, Object> jsonDocument = new HashMap<String, Object>();
jsonDocument.put("title", title);
jsonDocument.put(ClusterAdmin.FIELD_TEXT, content);
jsonDocument.put("postDate", postDate);
jsonDocument.put("tags", tags);
jsonDocument.put("author", author);
return jsonDocument;
}
public void addDocument(String text) throws ElasticsearchException,
IOException {
log.debug("Adding a new document " + text);
IndexResponse response = cluster
.getClient()
.prepareIndex(ClusterAdmin.INDEX, ClusterAdmin.TYPE)
.setSource(
putJsonDocument("Yet another document", text,
new Date(), "", "Luiz")).execute().actionGet();
}
public void getAll() {
cluster.getClient().admin().indices().prepareRefresh().execute()
.actionGet();
SearchResponse response = cluster.getClient()
.prepareSearch(ClusterAdmin.INDEX).setTypes(ClusterAdmin.TYPE)
.setSearchType(SearchType.COUNT)
.setQuery(QueryBuilders.matchAllQuery()).setFrom(0).setSize(60)
.setExplain(true).execute().actionGet();
SearchHit[] results = response.getHits().getHits();
System.out.println("Current results: " + results.length);
for (SearchHit hit : results) {
System.out.println("------------------------------");
Map<String, Object> result = hit.getSource();
System.out.println(result);
}
}
public List<String> getFrequentTerms() {
cluster.getClient().admin().indices().prepareRefresh().execute()
.actionGet();
ArrayList<String> terms = new ArrayList<String>();
SearchRequestBuilder requestBuilder = cluster.getClient()
.prepareSearch(ClusterAdmin.INDEX);
SearchResponse response = requestBuilder
.setSearchType(SearchType.DFS_QUERY_AND_FETCH)
.setQuery(QueryBuilders.matchAllQuery())
.addFacet(
FacetBuilders
.termsFacet("f1")
.field(ClusterAdmin.FIELD_TEXT)
.size(500)
.lang("brazilian")
.allTerms(true))
.setExplain(true).execute().actionGet();
TermsFacet f = (TermsFacet) response.getFacets().facetsAsMap().get("f1");
// For each entry
for (TermsFacet.Entry entry : f) {
log.debug("Term: " + entry.getTerm());
log.debug("Count: " + entry.getCount());
String term = entry.getTerm().string();
if(!StringUtil.isNumeric(term) && !EmpericalCleaner.isVerb(term))
terms.add(entry.getTerm().string());
}
return terms;
}
public List<String> search(String word) {
ArrayList<String> texts = new ArrayList<String>();
SearchResponse response = cluster.getClient().prepareSearch(ClusterAdmin.INDEX)
.setTypes(ClusterAdmin.TYPE)
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery(ClusterAdmin.FIELD_TEXT, word))
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchHit[] docs = response.getHits().getHits();
log.info("Total hits "+docs.length + " to "+ClusterAdmin.FIELD_TEXT);
// For each entry
for (SearchHit doc : docs) {
//String text = doc.getSourceAsString();
String text ="";
//log.info(doc.getFields().toString());
//doc.getFields().toString();
//if(doc.field(ClusterAdmin.FIELD_TEXT)!=null)
//text = doc.field(ClusterAdmin.FIELD_TEXT).getValue().toString();
texts.add(doc.getSourceAsString());
}
return texts;
}
}
|
package edu.louisiana.cacs.csce450GProject;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
public class scanner {
static int charClass=0;
static String lexeme="";
static char nextChar=0;
static int nextToken=0;
static final int LETTER=0;
static final int DIGIT=1;
static final int UNKNOWN=99;
static final int EOF=-1;
static final int INT_LIT=10;
static final int IDENT=11;
static final int ASSIGN_OP=20;
static final int ADD_OP=21;
static final int SUB_OP=22;
static final int MULT_OP=23;
static final int DIV_OP=24;
static final int LEFT_PAREN=25;
static final int RIGHT_PAREN=26;
static String fileName = System.getProperty("user.dir")+"/data/sample.txt";
static FileReader inputStream=null;
static LinkedList <String> iptoken = new LinkedList<String>();
public void buildTokenTree(LinkedList <String> inputtokens) throws IOException,FileNotFoundException
{
iptoken = inputtokens;
try {
inputStream=new FileReader(fileName);
file(inputStream);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(inputStream!=null){
try
{
inputStream.close();
}
catch(IOException e)
{
System.out.println("File close error");
}
}
}
}
public static void file(FileReader f)
{
inputStream=f;
try {
getChar();
do{
iptoken.add( lex());
}while(nextToken!=EOF);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void addChar()
{
lexeme=lexeme + nextChar;
}
public static void getChar()throws IOException
{
nextChar=(char)inputStream.read();
if((nextChar)!=EOF)
{
if(Character.isLetter(nextChar))
charClass=LETTER;
else if(Character.isDigit(nextChar))
charClass=DIGIT;
else charClass=UNKNOWN;
}
else charClass=EOF;
}
public static void getNonBlank() throws IOException
{
while(Character.isSpaceChar(nextChar))
{
getChar();
}
}
public static int lookup(char ch)
{
switch(ch)
{
case'(':
addChar();
nextToken=LEFT_PAREN;
break;
case')':
addChar();
nextToken=RIGHT_PAREN;
break;
case'+':
addChar();
nextToken=ADD_OP;
break;
case'-':
addChar();
nextToken=SUB_OP;
break;
case'*':
addChar();
nextToken=MULT_OP;
break;
case'/':
addChar();
nextToken=DIV_OP;
break;
default:
addChar();
nextToken=EOF;
break;
}
return nextToken;
}
public static String lex() throws IOException
{
lexeme="";
getNonBlank();
switch(charClass)
{
case LETTER:
addChar();
getChar();
while(charClass==LETTER||charClass==DIGIT){
addChar();
getChar();
}
nextToken=IDENT;
break;
case DIGIT:
addChar();
getChar();
while(charClass==DIGIT){
addChar();
getChar();
}
nextToken=INT_LIT;
break;
case UNKNOWN:
lookup(nextChar);
getChar();
break;
case EOF:
nextToken=EOF;
lexeme="EOF";
}
return lexeme;
}
}
|
package AccessModifiers2;
import AccessModifiers.first;
public class fourth {
public static void main(String[] args) {
// TODO Auto-generated method stub
first f=new first();
//System.out.println(f.a);//private field
System.out.println(f.d);//public
}
}
|
/*
* 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 com.pmm.sdgc.ws.model;
import com.pmm.sdgc.model.BiometriaCadastrada;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author setinf
*/
public class ModelBiometriaCadastradaWs {
private Boolean biometria;
public static ModelBiometriaCadastradaWs toModelBiometriaCadastradaWs(BiometriaCadastrada biometriaCadastrada){
ModelBiometriaCadastradaWs mbcw = new ModelBiometriaCadastradaWs();
mbcw.setBiometria(biometriaCadastrada.getBiometria());
return mbcw;
}
public Boolean getBiometria() {
return biometria;
}
public void setBiometria(Boolean biometria) {
this.biometria = biometria;
}
}
|
package com.company;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class BMIcalculatorTest extends Calory {
BMIcalculator object = new BMIcalculator();
@Test
public void userGetAllDataAndBmiIsNotANull() {
Assert.assertNotNull(object.calculateBMI());
}
@Test
public void shouldShowThatsHumanisHealth() throws Exception
{
assertTrue(object.isHealth(22));
}
}
|
package com.example.liltyrant.tutorial1;
import android.app.Application;
import android.app.Application;
import com.parse.Parse;
/**
* Created by LilTyrant on 11/9/2015.
*/
public class App extends Application {
@Override public void onCreate() {
super.onCreate();
Parse.initialize(this, cKP6tRnIKNfSdQ5jQaWWAFYhBYvJIlFY8rdK54xP, MuK46LvpMEBhdeQJauC1BfBPTbqyvGDO2YK7jWfg); // Your Application ID and Client Key are defined elsewhere
}
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package edu.psu.cse.siis.ic3;
import java.util.Objects;
public class DataAuthority {
private final String host;
private final String port;
public DataAuthority(String host, String port) {
this.host = host;
this.port = port;
}
public String getHost() {
return this.host;
}
public String getPort() {
return this.port;
}
public boolean isPrecise() {
return !"(.*)".equals(this.host) && !"(.*)".equals(this.port);
}
public String toString() {
return "host " + this.host + ", port " + this.port;
}
public int hashCode() {
return Objects.hash(new Object[]{this.host, this.port});
}
public boolean equals(Object other) {
if(!(other instanceof DataAuthority)) {
return false;
} else {
DataAuthority secondDataAuthority = (DataAuthority)other;
return Objects.equals(this.host, secondDataAuthority.host) && Objects.equals(this.port, secondDataAuthority.port);
}
}
}
|
package com.doohong.shoesfit.controllerTests;
import com.doohong.shoesfit.member.dto.LoginMemberDTO;
import com.doohong.shoesfit.member.dto.MemberDTO;
import com.doohong.shoesfit.target.dto.ShoesDTO;
import com.doohong.shoesfit.target.dto.TargetDTO;
import com.doohong.shoesfit.target.dto.TargetRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.util.ArrayList;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ShoesFitControllerTests {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@Test
public void find_Target_Right_Value() throws Exception {
ShoesDTO shoesDTO1 = new ShoesDTO("나이키", "코르테즈", 265);
ShoesDTO shoesDTO2 = new ShoesDTO("컨버스", "척테일러", 260);
TargetDTO target = new TargetDTO("아디다스", "슈퍼스타");
List<ShoesDTO> shoesList = new ArrayList<>();
shoesList.add(shoesDTO1);
shoesList.add(shoesDTO2);
TargetRequest targetRequest = new TargetRequest(shoesList, target);
mockMvc.perform(post("/events/target")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(targetRequest)))
.andDo(print())
.andExpect(status().isOk())
;
}
@Test
public void find_Target_Same_Value() throws Exception {
ShoesDTO shoesDTO1 = new ShoesDTO("나이키", "코르테즈", 265);
ShoesDTO shoesDTO2 = new ShoesDTO("나이키", "코르테즈", 260);
TargetDTO target = new TargetDTO("아디다스", "슈퍼스타");
List<ShoesDTO> shoesList = new ArrayList<>();
shoesList.add(shoesDTO1);
shoesList.add(shoesDTO2);
TargetRequest targetRequest = new TargetRequest(shoesList, target);
mockMvc.perform(post("/events/target")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(targetRequest)))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("code").value("SS_001"))
;
}
@Test
public void find_Target_Same_Target() throws Exception {
ShoesDTO shoesDTO1 = new ShoesDTO("나이키", "코르테즈", 265);
ShoesDTO shoesDTO2 = new ShoesDTO("아디다스", "슈퍼스타", 260);
TargetDTO target = new TargetDTO("나이키", "코르테즈");
List<ShoesDTO> shoesList = new ArrayList<>();
shoesList.add(shoesDTO1);
shoesList.add(shoesDTO2);
TargetRequest targetRequest = new TargetRequest(shoesList, target);
mockMvc.perform(post("/events/target")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(targetRequest)))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(jsonPath("code").value("TN_001"))
;
}
@Test
public void get_List() throws Exception {
mockMvc.perform(post("/events/list")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content("{}"))
.andDo(print())
.andExpect(status().isOk())
;
}
@Test
public void registration() throws Exception {
MemberDTO memberDTO = MemberDTO.builder().email("wnghd94@gmail.com").password("123").name("박주홍").build();
mockMvc.perform(post("/api/member/registration")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(memberDTO)))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void login_not_found_user() throws Exception {
LoginMemberDTO loginMemberDTO = LoginMemberDTO.builder().username("wnghd96@naver.com").password("123").build();
mockMvc.perform(post("/api/member/login")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(loginMemberDTO)))
.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void login_success() throws Exception {
MemberDTO memberDTO = MemberDTO.builder().email("wnghd95@naver.com").password("123").name("박주홍").build();
mockMvc.perform(post("/api/member/registration")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(memberDTO)))
.andDo(print());
LoginMemberDTO loginMemberDTO = LoginMemberDTO.builder().username("wnghd95@naver.com").password("123").build();
mockMvc.perform(post("/api/member/login")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(loginMemberDTO)))
.andDo(print())
.andExpect(status().isOk());
}
@Test
public void login_differ_password() throws Exception {
MemberDTO memberDTO = MemberDTO.builder().email("wnghd95@naver.com").password("123").name("박주홍").build();
mockMvc.perform(post("/api/member/registration")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(memberDTO)))
.andDo(print());
LoginMemberDTO loginMemberDTO = LoginMemberDTO.builder().username("wnghd95@naver.com").password("1234").build();
mockMvc.perform(post("/api/member/login")
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(objectMapper.writeValueAsString(loginMemberDTO)))
.andDo(print())
.andExpect(status().isBadRequest());
}
}
|
package br.com.amaro.demo.validators;
import br.com.amaro.demo.entities.Product;
import br.com.amaro.demo.forms.ProductRegisterForm;
import br.com.amaro.demo.forms.ProductRegisterListForm;
import br.com.amaro.demo.forms.SearchSimilarProductForm;
import br.com.amaro.demo.forms.SearchSimilarProductListForm;
import br.com.amaro.demo.services.ProductService;
import br.com.amaro.demo.services.TagService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.Errors;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Class responsible for validating the product and vector data list
*
* @see SearchSimilarProductListForm
*
* @author Mariane Muniz
* @version 1.0.0
*/
@Service
public class SearchSimilarProductListFormValidator extends ProductRegisterListFormValidator {
public SearchSimilarProductListFormValidator(final ProductService productService, final TagService tagService) {
super(productService, tagService);
}
/**
* It is the method responsible for validating whether the input data is compatible with the validator.
*
* @param aClass Entry form of the type {@link SearchSimilarProductListForm}
* @return Returns whether or not the form was accepted for validation.
*/
@Override
public boolean supports(final Class<?> aClass) {
return SearchSimilarProductListForm.class.equals(aClass);
}
/**
* Method responsible for redefining the methods that will validate the attributes of the forms.
*
* @param productRegisterListForm form list with products information
* @param errors object that stores the errors found during validation
* @param invalidFormIndex global index of forms with error
*/
@Override
protected void validateFormAttributes(
final ProductRegisterListForm productRegisterListForm,
final Errors errors,
final List<Integer> invalidFormIndex
) {
super.validateFormAttributes(productRegisterListForm, errors, invalidFormIndex);
this.validateTagsVectorCount((SearchSimilarProductListForm) productRegisterListForm, errors, invalidFormIndex);
}
/**
* Method responsible for calling the secondary validation methods of the product identifier. If there is any form
* with invalid identification, a rejection of type 'emptyId' is generated
*
* @param productRegisterListForm form list with products information
* @param errors object that stores the errors found during validation
* @param invalidFormIndex global index of forms with error
*/
@Override
protected void validateIds(
final ProductRegisterListForm productRegisterListForm,
final Errors errors,
final List<Integer> invalidFormIndex) {
final List<Integer> nullIdIndex = new ArrayList<>();
this.validateNullIds(productRegisterListForm, nullIdIndex, invalidFormIndex);
this.validateNotRegisteredIds(productRegisterListForm, nullIdIndex, invalidFormIndex);
/* If there are product forms with invalid identifiers, a rejection is generated with the form
indexes of the type 'emptyId */
if (!CollectionUtils.isEmpty(nullIdIndex)) {
errors.rejectValue(ProductRegisterForm.ID, RegisterFormErrors.EMPTY_ID,
nullIdIndex.toArray(), "Products without id or duplicated");
}
}
/**
* Method responsible for checking which forms have product identifiers not registered in the database.
* If the product not exist in the database, the index of your form is added to the blacklist.
*
* @param productRegisterListForm form list with products information
* @param productFormWithProductRegisteredIndex index of product forms with products not registered in the database
* @param invalidFormIndex global index of forms with error
*/
protected void validateNotRegisteredIds(
final ProductRegisterListForm productRegisterListForm,
final List<Integer> productFormWithProductRegisteredIndex,
final List<Integer> invalidFormIndex
) {
final List<ProductRegisterForm> productList = productRegisterListForm.getProducts();
for(int i = 0; i < productList.size(); i++) {
final ProductRegisterForm productRegisterForm = productList.get(i);
final Integer productId = productRegisterForm.getId();
/* from the product identifier the form is consulted in the database if the product exists.
If the product not exist, it is added to the blacklist. */
if (!ObjectUtils.isEmpty(productId)) {
final Product product = this.productService.findByExternalId(productId);
if (Objects.isNull(product)) {
if (!invalidFormIndex.contains(i)) {
invalidFormIndex.add(i);
}
if (!productFormWithProductRegisteredIndex.contains(i)) {
productFormWithProductRegisteredIndex.add(i);
}
}
}
}
}
/**
* This method is responsible for validating the amount of elements sent in the vector field. If the amount of
* vectors sent is smaller than the amount of base tags, a rejection of the type 'invalidTagsVectorName' is
* generated by the amount of incompatible vectors.
*
* @param searchSimilarProductListForm form with product information
* @param errors object that stores the errors found during validation
* @param invalidFormList global index of forms with error
*/
private void validateTagsVectorCount(
final SearchSimilarProductListForm searchSimilarProductListForm,
final Errors errors,
final List<Integer> invalidFormList
) {
final List<Integer> invalidFormVectorSizeList = new ArrayList<>();
final int availableTagsCount = this.tagService.countTotalTags();
final List<Integer> invalidProductIdList = new ArrayList<>();
final List<SearchSimilarProductForm> searchSimilarProductList = searchSimilarProductListForm.getSimilar();
/* checks if the number of vectors in the form is the same as the number of tags registered in the base. */
for (int i = 0; i < searchSimilarProductList.size(); i++) {
final SearchSimilarProductForm form = searchSimilarProductList.get(i);
final int[] formVector = form.getTagsVector();
if(Objects.isNull(formVector) || formVector.length != availableTagsCount) {
invalidFormList.add(i);
invalidFormVectorSizeList.add(i);
}
}
/* If the number of vectors in the form is different, a rejection is generated with the indexes of the forms */
if (CollectionUtils.isEmpty(invalidProductIdList)) {
final String message = "tagsVector need " + availableTagsCount + " elements in the array";
errors.rejectValue(SearchSimilarProductForm.TAGS_VECTOR, RegisterFormErrors.INVALID_TAGS_VECTOR_NAME,
invalidFormVectorSizeList.toArray(), message);
}
}
}
|
package dao;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import entity.Depart_info;
import entity.Org_info;
import entity.Sign_info;
import entity.Student_info;
public class Sign_infoDAOImpl extends HibernateDaoSupport implements Sign_infoDAO{
@Override
public void save(Sign_info sign) {
// TODO Auto-generated method stub
this.getHibernateTemplate().save(sign);
}
@Override
public void delSign_info(int id) {
// TODO Auto-generated method stub
if(this.findById(id)!=null)
{
this.getHibernateTemplate().delete(findById(id));
}
}
@Override
public void update(Sign_info sign) {
if(this.findById(sign.getSignment_id())!=null)
{
this.getHibernateTemplate().update(sign);
}
}
@Override
public List<Sign_info> findSomeByStuId(int student_id) {
// TODO Auto-generated method stub
String hsql=" from Sign_info sign where sign.student_id='"+student_id+"'";
List<Sign_info> list =(List<Sign_info>)this.getHibernateTemplate().find(hsql);
return list;
}
@Override
public List<Sign_info> findSomeByDepartId(int department_id) {
// TODO Auto-generated method stub
String hsql="from Sign_info sign where sign.department_id='"+department_id+"'";
List<Sign_info> list=(List<Sign_info>)this.getHibernateTemplate().find(hsql);
return list;
}
@Override
public List<Sign_info> findAll() {
// TODO Auto-generated method stub
String queryString ="select sign from Sign_info sign";
List<Sign_info> list =(List<Sign_info>)this.getHibernateTemplate().find(queryString);
return list;
}
@Override
public Sign_info findById(int sign_id) {
// TODO Auto-generated method stub
Sign_info sign =(Sign_info)this.getHibernateTemplate().get(Sign_info.class, sign_id);
return sign;
}
}
|
package cn.vector.service;
import cn.vector.domain.Employee;
import cn.vector.repository.EmployeeCrudRepository;
import cn.vector.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @Author : Huang Vector ( hgw )
* @Date : 2018-6-4 14:23
*/
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired
private EmployeeCrudRepository employeeCrudRepository;
@Transactional
public void updateAge(Integer id, Integer age){
employeeRepository.updateAge(id, age);
}
@Transactional
public void save(List<Employee> employeeList){
employeeCrudRepository.save(employeeList);
}
}
|
package com.chaabene;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class CongratulationsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_congratulations);
}
public void onDoneClick(View v){
Intent intent = new Intent(this, com.chaabene.MainActivity.class);
startActivity(intent);
}
}
|
package de.trispeedys.resourceplanning.repository;
import de.trispeedys.resourceplanning.datasource.DefaultDatasource;
import de.trispeedys.resourceplanning.datasource.EventPositionDatasource;
import de.trispeedys.resourceplanning.entity.Event;
import de.trispeedys.resourceplanning.entity.EventPosition;
import de.trispeedys.resourceplanning.repository.base.AbstractDatabaseRepository;
import de.trispeedys.resourceplanning.repository.base.DatabaseRepository;
import de.trispeedys.resourceplanning.repository.base.RepositoryProvider;
public class EventPositionRepository extends AbstractDatabaseRepository<EventPosition> implements DatabaseRepository<EventPositionRepository>
{
public EventPosition findByEventAndPositionNumber(Event event, int positionNumber)
{
return (EventPosition) dataSource().findSingle(EventPosition.ATTR_EVENT, event,
EventPosition.ATTR_POSITION, RepositoryProvider.getRepository(PositionRepository.class)
.findPositionByPositionNumber(positionNumber));
}
protected DefaultDatasource<EventPosition> createDataSource()
{
return new EventPositionDatasource();
}
}
|
package com.acewill.ordermachine.activity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.acewill.ordermachine.R;
import com.acewill.ordermachine.adapter.MyAdapter;
import com.acewill.ordermachine.eventbus.OnFinishEvent;
import com.acewill.ordermachine.pos.NewPos;
import com.acewill.ordermachine.util.PriceUtil;
import com.acewill.ordermachine.util_new.GsonUtils;
import com.acewill.ordermachine.util_new.ToastUtils;
import com.acewill.ordermachine.widget.DropEditText;
import com.acewill.ordermachine.widget.TitileLayout;
import com.zhy.http.okhttp.callback.StringCallback;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import okhttp3.Call;
/**
* Author:Anch
* Date:2017/11/22 11:53
* Desc:
*/
public class HuiYuanChaXunActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "HuiYuanChaXunActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_huiyuanchaxun);
initTitleLayout();
initView();
initEvent();
}
private GridView gridView;
private ListView listView;
private ListViewAdapter mListViewAdapter;
private LinearLayout container_ly;
private void initView() {
gridView = (GridView) findViewById(R.id.mygridview);
listView = (ListView) findViewById(R.id.mylistview);
member_name = (TextView) findViewById(R.id.member_name);
member_phone = (TextView) findViewById(R.id.member_phone);
member_uno = (TextView) findViewById(R.id.member_uno);
member_gradename = (TextView) findViewById(R.id.member_gradename);
member_birthday = (TextView) findViewById(R.id.member_birthday);
member_registered = (TextView) findViewById(R.id.member_registered);
member_type = (TextView) findViewById(R.id.member_type);
member_balance = (TextView) findViewById(R.id.member_balance);
member_credit = (TextView) findViewById(R.id.member_credit);
tips = (TextView) findViewById(R.id.tips);
container_ly = (LinearLayout) findViewById(R.id.container_ly);
mListViewAdapter = new ListViewAdapter(new ArrayList());
String html = "<font color=\"red\">*</font>提示:会员门店POS地址为:<font color=\"#3aa8d9\">pos.acewill.net</font>,会员商户中心地址为:<font color=\"#3aa8d9\">manage.acewill.net</font>";
tips
.setText(Html.fromHtml(html));
}
private DropEditText member_query_et;
private void initEvent() {
member_query_et = (DropEditText) findViewById(R.id.member_query_et);
findViewById(R.id.btn_search).setOnClickListener(this);
}
private TextView member_name;
private TextView member_phone;
private TextView member_uno;
private TextView member_gradename;
private TextView member_birthday;
private TextView member_registered;
private TextView member_type;
private TextView member_balance;
private TextView member_credit;
private TextView tips;
@Subscribe(threadMode = ThreadMode.MAIN)
public void onFinish(OnFinishEvent event) {
// ToastUtils.showToast(HuiYuanChaXunActivity.this, event.getMsg());
}
private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");// 用于格式化日期,作为日志文件名的一部分
private List<WshAccount> accountList;
private void doMemberLogin(String code) {
Log.e(TAG, "会员支付开始时间:" + format.format(new Date()));
new NewPos().memberLogin(code, new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
e.printStackTrace();
}
@Override
public void onResponse(String response, int id) {
try {
int result = GsonUtils.getIntData("result", response);
if (result == 0) {
WshAccountRes res = GsonUtils
.getSingleBean(response, WshAccountRes.class);
accountList = res.content;
List<CardName> accountNameList = new ArrayList<>();
for (int i = 0; accountList != null && i < accountList.size(); i++) {
if (i == 0)
accountNameList
.add(new CardName(accountList.get(i).getGradeName(), true));
else
accountNameList.add(new CardName(accountList.get(i)
.getGradeName(), false));
}
gridView.setAdapter(new GridViewAdapter(accountNameList));
mListViewAdapter.setData(accountList.get(0).getCoupons());
listView.setAdapter(mListViewAdapter);
refreshUI(accountList.get(0));
//第二步支付
} else {
ToastUtils.showToast(HuiYuanChaXunActivity.this, GsonUtils
.getData("errmsg", response));
}
} catch (Exception e) {
}
}
});
}
@Override
public void onClick(View v) {
String number = member_query_et.getText().toString().trim();
if (TextUtils.isEmpty(number)) {
ToastUtils.showToast(HuiYuanChaXunActivity.this, "请输入会员卡号或手机号");
return;
}
doMemberLogin(number);
}
private class CardName {
private String name;
private boolean isSelect;
public CardName(String name, boolean isSelect) {
this.name = name;
this.isSelect = isSelect;
}
public boolean isSelect() {
return isSelect;
}
public void setSelect(boolean select) {
isSelect = select;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private void refreshUI(WshAccount account) {
member_name.setText(account.getName());
member_uno.setText(account.getUno() + "");
member_phone.setText(account.getPhone());
member_birthday.setText(account.getBirthday());
member_registered.setText(account.getRegistered());
member_gradename.setText(account.getGradeName());
if ("wx".equals(account.getType())) {
member_type.setText("微信会员卡");
} else if ("ph".equals(account.getType())) {
member_type.setText("实体卡");
} else {
member_type.setText(account.getType());
}
member_balance.setText(PriceUtil.divide(account.getBalance() + "", "100").toString());
member_credit.setText(account.getCredit() + "");
mListViewAdapter.setData(account.getCoupons());
mListViewAdapter.notifyDataSetChanged();
if (container_ly.getVisibility() != View.VISIBLE)
container_ly.setVisibility(View.VISIBLE);
}
private class GridViewAdapter<String> extends MyAdapter {
public GridViewAdapter(List dataList) {
super(dataList);
}
@Override
protected View getItemView(final int position, View convertView, ViewGroup parent) {
final Button button = new Button(HuiYuanChaXunActivity.this);
final CardName name = (CardName) dataList.get(position);
button.setText(name.getName());
button.setTextColor(getResources().getColor(R.color.color_white));
if (name.isSelect()) {
button.setBackground(getResources().getDrawable(R.drawable.border_blue_selector));
} else {
button.setBackgroundColor(getResources().getColor(R.color.gray));
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshUI(accountList.get(position));
setSelect(dataList);
notifyDataSetChanged();
}
});
return button;
}
private void setSelect(List<CardName> dataList) {
for (CardName name : dataList)
name.setSelect(!name.isSelect());
}
}
private void initTitleLayout() {
TitileLayout layout = (TitileLayout) findViewById(R.id.title_ly);
layout.setOnBackClickLisener(new TitileLayout.OnBackClickLisener() {
@Override
public void onBackClick() {
finish();
}
});
}
private class ListViewAdapter extends MyAdapter {
public ListViewAdapter(List dataList) {
super(dataList);
}
@Override
protected View getItemView(int position, View convertView, ViewGroup parent) {
MyViewHolder holder;
if (convertView == null) {
convertView = View
.inflate(HuiYuanChaXunActivity.this, R.layout.item_huiyuanguanli, null);
holder = new MyViewHolder();
holder.item_member_quanmingcheng = (TextView) convertView
.findViewById(R.id.item_member_quanmingcheng);
holder.item_member_quanshuliang = (TextView) convertView
.findViewById(R.id.item_member_quanshuliang);
holder.item_member_quanqishishijian = (TextView) convertView
.findViewById(R.id.item_member_quanqishishijian);
holder.item_member_quanguoqishijian = (TextView) convertView
.findViewById(R.id.item_member_quanguoqishijian);
convertView.setTag(holder);
} else {
holder = (MyViewHolder) convertView.getTag();
}
WshAccountCoupon coupon = (WshAccountCoupon) dataList.get(position);
holder.item_member_quanmingcheng.setText(coupon.getTitle());
holder.item_member_quanshuliang.setText(coupon.getCoupon_ids().size() + "");
holder.item_member_quanqishishijian.setText(coupon.getEffective_time());
holder.item_member_quanguoqishijian.setText(coupon.getFailure_time());
return convertView;
}
private class MyViewHolder {
TextView item_member_quanmingcheng;
TextView item_member_quanshuliang;
TextView item_member_quanqishishijian;
TextView item_member_quanguoqishijian;
}
}
}
|
package com.datalinks.android.widgetexample;
import java.util.Random;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
public class WidgetExampleService extends Service{
private static final String APP_TAG = "Datalinks-Widget";
static int counter;
@Override
public void onStart(Intent intent, int startId) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
for (int widgetId : allWidgetIds) {
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(this.getApplicationContext().getPackageName(),R.layout.widgetsimple_layout);
counter++;
Log.d(APP_TAG, "Called with nr "+number+" counter "+counter);
remoteViews.setTextViewText(R.id.update,"Random: " + String.valueOf(number));
remoteViews.setTextViewText(R.id.TextView01,"count: " + String.valueOf(counter));
// remoteViews.setUri(R.id.webView1, "POST", Uri.parse("http://www.nu.nl"));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
|
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// J'appelle ma fonction file.Copy() de la classe Application
Application.fileCopy();
}
}
|
package org.dew.xcomm.messaging;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.jivesoftware.smack.packet.XMPPError;
import org.dew.xcomm.nosql.INoSQLDB;
import org.dew.xcomm.util.ConnectionManager;
import org.dew.xcomm.util.WUtil;
public
class XMessagingManager
{
protected static Logger logger = Logger.getLogger(XMessagingManager.class);
public static
XMessage insert(XMessage message)
throws Exception
{
try {
if(message == null) throw new Exception("message is null");
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
Map<String,Object> mapValues = WUtil.beanToMap(message);
String id = noSQLDB.insert("Message", mapValues);
message.setId(id);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.insert", ex);
}
return message;
}
public static
List<XMessage> find(XMessage messageFilter)
throws Exception
{
logger.debug("XMessagingManager.find(" + messageFilter + ")...");
List<XMessage> listResult = null;
try {
if(messageFilter == null) {
logger.debug("XMessagingManager.find(" + messageFilter + ") -> 0 items");
return new ArrayList<XMessage>(0);
}
// Il thread deve essere sempre esplicitato: '*' in caso di tutti
String thread = messageFilter.getThread();
if(thread == null || thread.length() == 0) {
logger.debug("XMessagingManager.find(" + messageFilter + ") -> 0 items (thread="+ thread + ")");
return new ArrayList<XMessage>(0);
}
if(thread.equals("*")) messageFilter.setThread(null);
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
Map<String,Object> mapFilter = WUtil.beanToMap(messageFilter);
List<Map<String,Object>> listFindResult = noSQLDB.find("Message", mapFilter, null);
if(listFindResult != null) {
listResult = new ArrayList<XMessage>(listFindResult.size());
for(int i = 0; i < listFindResult.size(); i++) {
Map<String,Object> mapMessage = listFindResult.get(i);
XMessage message = WUtil.populateBean(XMessage.class, mapMessage);
if(message == null) {
logger.debug(" [" + i + "] message is null");
continue;
}
if(WUtil.isBlank(message.getPayload())) {
logger.debug(" [" + i + "] payload is blank: " + mapMessage);
continue;
}
listResult.add(message);
}
}
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.find", ex);
throw ex;
}
if(listResult == null) listResult = new ArrayList<XMessage>(0);
logger.debug("XMessagingManager.find(" + messageFilter + ") -> " + WUtil.size(listResult) + " items");
return listResult;
}
public static
String reportRequest(XMessage message)
throws Exception
{
if(message == null) return null;
String to = message.getTo();
if(to == null || to.length() == 0) {
return null;
}
String thread = message.getThread();
if(thread == null) thread = "";
Date dateTime = message.getCreation();
if(dateTime == null) dateTime = new Date();
Integer type = message.getPayloadType();
Map<String,Object> mapData = new HashMap<String,Object>(3);
mapData.put("username", to);
mapData.put("last_req", dateTime);
mapData.put("last_req_thread", thread);
mapData.put("last_req_type", type);
Map<String,Object> mapFilter = new HashMap<String,Object>(1);
mapFilter.put("username", to);
String result = null;
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
result = noSQLDB.upsert("Report", mapData, mapFilter);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.reportRequest", ex);
}
return result;
}
public static
String reportResponse(XMessage message)
throws Exception
{
if(message == null) return null;
String from = message.getFrom();
if(from == null || from.length() == 0) {
return null;
}
String thread = message.getThread();
if(thread == null) thread = "";
Date dateTime = message.getUpdate();
if(dateTime == null) dateTime = new Date();
Integer type = message.getPayloadType();
Map<String,Object> mapData = new HashMap<String,Object>(3);
mapData.put("username", from);
mapData.put("last_res", dateTime);
mapData.put("last_res_thread", thread);
mapData.put("last_res_type", type);
Map<String,Object> mapFilter = new HashMap<String,Object>(1);
mapFilter.put("username", from);
String result = null;
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
result = noSQLDB.upsert("Report", mapData, mapFilter);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.reportResponse", ex);
}
return result;
}
public static
String reportError(XMessage message, XMPPError xmppError)
throws Exception
{
if(message == null) return null;
String from = message.getFrom();
if(from == null || from.length() == 0) {
return null;
}
String thread = message.getThread();
if(thread == null) thread = "";
Date dateTime = message.getUpdate();
if(dateTime == null) dateTime = new Date();
Integer type = message.getPayloadType();
String errorMessage = "";
if(xmppError != null) {
errorMessage = xmppError.getCondition() + " - " + xmppError.getType();
}
Map<String,Object> mapData = new HashMap<String,Object>(3);
mapData.put("username", from);
mapData.put("last_err", dateTime);
mapData.put("last_err_thread", thread);
mapData.put("last_err_type", type);
mapData.put("last_err_msg", errorMessage);
Map<String,Object> mapFilter = new HashMap<String,Object>(1);
mapFilter.put("username", from);
String result = null;
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
result = noSQLDB.upsert("Report", mapData, mapFilter);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.reportError", ex);
}
return result;
}
public static
String reportVoiceRequest(XMessage message)
throws Exception
{
if(message == null) return null;
String from = message.getFrom();
if(from == null || from.length() == 0) {
return null;
}
String thread = message.getThread();
if(thread == null) thread = "";
Date dateTime = message.getUpdate();
if(dateTime == null) dateTime = new Date();
Map<String,Object> mapData = new HashMap<String,Object>(3);
mapData.put("username", from);
mapData.put("last_voice", dateTime);
mapData.put("last_voice_thread", thread);
Map<String,Object> mapFilter = new HashMap<String,Object>(1);
mapFilter.put("username", from);
String result = null;
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
result = noSQLDB.upsert("Report", mapData, mapFilter);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.reportVoiceRequest", ex);
}
return result;
}
public static
boolean insertRejected(XMessage message)
throws Exception
{
try {
if(message == null) return false;
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
Map<String,Object> mapValues = WUtil.beanToMap(message);
String id = noSQLDB.insert("Rejected", mapValues);
message.setId(id);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.insertRejected", ex);
}
return true;
}
public static
boolean canReceive(String username, Integer payloadType)
{
if(username == null || username.length() == 0) {
return false;
}
username = username.trim().toLowerCase();
Map<String,Object> mapFilter = new HashMap<String,Object>(1);
mapFilter.put("username", username);
List<Map<String,Object>> resFind = null;
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
resFind = noSQLDB.find("Report", mapFilter, null);
if(resFind == null || resFind.size() == 0) {
// Se la collezione non e' disponibile NON si puo' fare alcuna valutazione.
// Si rende comunque disponibile di default l'utente.
return true;
}
Map<String,Object> mapReport = resFind.get(0);
Calendar calLastReq = WUtil.toCalendar(mapReport.get("last_req"), null);
Calendar calLastRes = WUtil.toCalendar(mapReport.get("last_res"), null);
Calendar calLastErr = WUtil.toCalendar(mapReport.get("last_err"), null);
Calendar calLastVoi = WUtil.toCalendar(mapReport.get("last_voice"), null);
if(calLastReq == null) {
// Se non e' stata mai registrata alcuna richiesta...
if(calLastVoi != null) {
// ma e' stata registrata una richiesta di voice...
return true;
}
else
if(calLastRes != null) {
// ma e' stato registrato un messaggio di risposta... (Improbabile se non in caso di drop collection)
return true;
}
return false;
}
// calLastReq != null
if(calLastRes != null && !calLastRes.before(calLastReq)) {
// Se e' stata registrata una riposta posteriore alla richiesta...
return true;
}
if(calLastVoi != null && !calLastVoi.before(calLastReq)) {
// Se e' stata registrata una richiesta di voice posteriore alla richiesta...
return true;
}
if(calLastErr != null && !calLastErr.before(calLastReq)) {
// Se e' stato registrato un errore posteriore alla richiesta...
return false;
}
// Se e' stata registrata una richiesta (calLastReq != null), ma non
// sono stati registrati errori, risposte o richieste di voice posteriori...
boolean pushMessage = payloadType != null && payloadType.intValue() > 4;
if(pushMessage) {
// Nel caso di messaggi push si consente l'invio anche in assenza di una
// risposta ad una precedente richiesta.
return true;
}
if(calLastRes != null) {
long lDiff = System.currentTimeMillis() - calLastRes.getTimeInMillis();
if(lDiff > 900000) {
// se questa situazione perdura da piu' di 15 minuti...
return false;
}
}
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.canReceive", ex);
}
// Si reputa disponibile l'utente che comunque ha una coda di messaggi
return true;
}
public static
int removeUpTo(Date dUpTo)
{
if(dUpTo == null) return 0;
int iResult = 0;
Map<String,Object> mapFilter = new HashMap<String,Object>();
mapFilter.put("creation<", dUpTo);
try {
INoSQLDB noSQLDB = ConnectionManager.getDefaultNoSQLDB();
iResult = noSQLDB.delete("Message", mapFilter);
noSQLDB.delete("Rejected", mapFilter);
}
catch(Exception ex) {
logger.error("Eccezione in XMessagingManager.removeUpTo", ex);
}
return iResult;
}
}
|
/*
* Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.dao;
import com.yahoo.cubed.model.Pipeline;
import com.yahoo.cubed.model.PipelineProjection;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
/**
* Pipeline data access object implementation.
*/
public class PipelineDAOImpl extends AbstractEntityDAOImpl<Pipeline> implements PipelineDAO {
/**
* Get the entity/model class: Pipeline.
*/
@Override
public Class<Pipeline> getEntityClass() {
return Pipeline.class;
}
/**
* Save pipeline entity (core implementation).
*/
@Override
protected void saveKernel(Session session, Pipeline model) {
super.saveKernel(session, model);
PipelineProjection.setPipelineId(model.getProjections(), model.getPrimaryIdx());
DAOFactory.pipelineProjectionDAO().save(session, model.getProjections());
}
/**
* Update pipeline entity (core implementation).
*/
@Override
protected void updateKernel(Session session, Pipeline oldModel, Pipeline newModel) {
DAOFactory.pipelineProjectionDAO().update(session, oldModel.getProjections(), newModel.getProjections());
super.updateKernel(session, oldModel, newModel);
}
/**
* Update pipeline entity (method overloading).
*/
@Override
public void update(Session session, Pipeline newModel) {
Pipeline oldModel = this.fetch(session, newModel.getPipelineId());
if (oldModel == null) {
return;
}
super.update(session, oldModel, newModel);
}
/**
* Delete pipeline entity (core implementation).
*/
@Override
public void deleteKernel(Session session, Pipeline model) {
List<PipelineProjection> projections = model.getProjections();
super.deleteKernel(session, model);
if (projections != null) {
PipelineProjection.setPipelineId(projections, model.getPrimaryIdx());
DAOFactory.pipelineProjectionDAO().delete(session, projections);
}
}
/**
* Performs eager fetch.
*/
@Override
public Pipeline fetch(Session session, long id) {
Pipeline pipeline = super.fetch(session, id);
if (pipeline != null) {
Hibernate.initialize(pipeline.getProjections());
}
return pipeline;
}
/**
* Performs lazy fetch.
*/
@Override
public List<Pipeline> fetchAll(Session session) {
return this.fetchAll(session, FetchMode.LAZY);
}
/**
* Fetch all the pipelines.
* If fetch mode is eager, it will fetch the projections for each pipeline.
* If fetch mode is lazy, projections will not be fetched.
*/
@Override
public List<Pipeline> fetchAll(Session session, FetchMode mode) {
List<Pipeline> pipelines = super.fetchAll(session);
if (mode == FetchMode.EAGER) {
if (pipelines != null) {
for (Pipeline pipeline : pipelines) {
Hibernate.initialize(pipeline.getProjections());
}
}
return pipelines;
} else {
// default is LAZY
return Pipeline.simplifyPipelineList(pipelines);
}
}
/**
* Fetch pipeline by name.
*/
@Override
public Pipeline fetchByName(Session session, String name) {
Criteria criteria = session.createCriteria(this.getEntityClass());
criteria.add(Restrictions.eq("pipelineName", name));
Pipeline pipeline = (Pipeline) criteria.uniqueResult();
if (pipeline != null) {
Hibernate.initialize(pipeline.getProjections());
}
return pipeline;
}
/**
* Delete a list of pipelines.
*/
@Override
public void deleteAll(Session session, List<Pipeline> pipelines) {
if (pipelines == null) {
return;
}
for (Pipeline pipeline : pipelines) {
// delete associated pipeline projections if there are any
// pipelines affiliated with funnel groups do not have pipeline-specific projections
if (pipeline != null && pipeline.getProjections() != null) {
DAOFactory.pipelineProjectionDAO().delete(session, pipeline.getProjections());
}
// delete the pipeline
session.delete(pipeline);
}
session.flush();
}
/**
* Save a list of pipelines.
*/
@Override
public void saveAll(Session session, List<Pipeline> pipelines) {
if (pipelines == null) {
return;
}
for (Pipeline pipeline : pipelines) {
// save the pipeline
session.save(pipeline);
// save associated pipeline projections if there are any
// pipelines affiliated with funnel groups do not have pipeline-specific projections
if (pipeline != null && pipeline.getProjections() != null) {
for (PipelineProjection projection : pipeline.getProjections()) {
projection.setPipelineId(pipeline.getPipelineId());
}
DAOFactory.pipelineProjectionDAO().save(session, pipeline.getProjections());
}
}
session.flush();
}
/**
* Update a list of pipelines.
*/
@Override
public void updateAll(Session session, List<Pipeline> oldPipelines, List<Pipeline> newPipelines) {
this.deleteAll(session, oldPipelines);
this.saveAll(session, newPipelines);
}
}
|
package org.wuxinshui.boosters.uuid;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class UUIDUtil {
public static Long generateUidFromString(String msg) throws NoSuchAlgorithmException, UnsupportedEncodingException {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(msg.getBytes("UTF-8"));
BigInteger bigInteger = new BigInteger(1, md5.digest(), 2, 4);
return bigInteger.abs().longValue();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new BigInteger(msg.getBytes(),2,4).abs().longValue();
}
public static Long getUUIDFromString(String msg) {
UUID uuid = UUID.nameUUIDFromBytes(msg.getBytes());
long version = uuid.version();
System.out.println("0x0f:"+0x0f);
System.out.println("version:"+version);
// long node = uuid.node();
// System.out.println("node:"+node);
// long timestamp = uuid.timestamp();
// System.out.println("timestamp:"+timestamp);
long leastSigBits = uuid.getLeastSignificantBits();
System.out.println("leastSigBits:"+leastSigBits);
long mostSigBits = uuid.getMostSignificantBits();
System.out.println("mostSigBits:"+mostSigBits);
return leastSigBits;
}
public static Long fromString(String msg) {
UUID uuid = UUID.fromString(msg);
long version = uuid.version();
System.out.println("0x0f:"+0x0f);
System.out.println("version:"+version);
long node = uuid.node();
System.out.println("node:"+node);
long timestamp = uuid.timestamp();
System.out.println("timestamp:"+timestamp);
long leastSigBits = uuid.getLeastSignificantBits();
System.out.println("leastSigBits:"+leastSigBits);
long mostSigBits = uuid.getMostSignificantBits();
System.out.println("mostSigBits:"+mostSigBits);
return leastSigBits;
}
public static void main(String[] args) {
// String text = "中国移动中国你哥哥";
String text = "28400000-8cf0-11bd-b23e-10b96e4ef00d";
// System.out.println(getUUIDFromString(text));
System.out.println(fromString(text));
}
}
|
package app.repositories;
import org.springframework.data.repository.CrudRepository;
import app.entities.State;
public interface StateRepository extends CrudRepository<State, Long> {
}
|
package com.cs.player;
import java.math.BigDecimal;
/**
* @author Hadi Movaghar
*/
public enum TimeUnit {
DAY(1), WEEK(7), MONTH(30);
private final int timeInDays;
TimeUnit(final int timeInDays) {
this.timeInDays = timeInDays;
}
public int getTimeValue() {
return timeInDays;
}
public static BigDecimal getTimeUnitConversionValue(final TimeUnit fromUnit, final TimeUnit toUnit) {
return BigDecimal.valueOf(toUnit.getTimeValue() * 1.0 / fromUnit.getTimeValue());
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import gifAnimation.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class sketch_029 extends PApplet {
/* mathematics formula */
// inspired https://twitter.com/ru_sack/status/783067897438441472
//
// x=(1+(cos(u/2)sin(v)-sin(u/2)sin(2v)))cos(u)
// y=(1+(cos(u/2)sin(v)-sin(u/2)sin(2v)))sin(u)
// z=2(sin(u/2)sin(v)+cos(u/2)sin(2v))
// 0\u2266u\u22662pi
// 0\u2266v\u22662pi
// \u5909\u6570
GifMaker gifExport;
int gifCount = 90;
boolean isRecord = false;
// \u5909\u6570u\u306e\u6700\u5c0f\u5024
float minU = 0;
// \u5909\u6570u\u306e\u6700\u5927\u5024
float maxU = TWO_PI;
// \u5909\u6570v\u306e\u6700\u5c0f\u5024
float minV = 0;
// \u5909\u6570v\u306e\u6700\u5927\u5024
float maxV = TWO_PI;
// \u5206\u5272\u6570
float div = 200;
// u,v\u306e\u5897\u52a0\u30b9\u30c6\u30c3\u30d7
float stepU = abs(maxU - minU)/div;
float stepV = abs(maxU - minU)/div;
// \u30b9\u30b1\u30fc\u30eb
float scale = 200;
// \u80cc\u666f\u3001\u30d9\u30fc\u30b9\u3001\u30ad\u30fc\u8272
int bgColor;
int keyColor;
int baseColor;
// setup\u95a2\u6570 : \u521d\u56de1\u5ea6\u3060\u3051\u5b9f\u884c\u3055\u308c\u308b
public void setup() {
// \u30a6\u30a3\u30f3\u30c9\u30a6\u30b5\u30a4\u30ba\u3092960px,540px\u306b
colorMode(HSB, 360, 100, 100, 100); // HSB\u3067\u306e\u8272\u6307\u5b9a\u306b\u3059\u308b
// \u63cf\u753b\u3092\u6ed1\u3089\u304b\u306b
//hint(ENABLE_DEPTH_SORT);
sphereDetail(0);
bgColor = color(228, 10, 98);
keyColor = color(209, 57, 51);
baseColor = color(214, 71, 32);
gifInit();
}
// draw\u95a2\u6570 : setup\u95a2\u6570\u5b9f\u884c\u5f8c\u7e70\u308a\u8fd4\u3057\u5b9f\u884c\u3055\u308c\u308b
public void draw() {
background(bgColor);
lights();
ambientLight(0, 0, 20);
translate(width/2, height/2, -500);
float n = sin(frameCount/(float)gifCount * PI);
float fov = map(n,-1,1,0,0.8f); //\u8996\u91ce\u89d2
//perspective(\u8996\u91ce\u89d2\u3001\u7e26\u6a2a\u306e\u6bd4\u7387\u3001\u8fd1\u3044\u9762\u307e\u3067\u306e\u8ddd\u96e2\u3001\u9060\u3044\u9762\u307e\u3067\u306e\u8ddd\u96e2)
perspective(fov, PApplet.parseFloat(width)/PApplet.parseFloat(height), 1.0f, 10000.0f);
rotateX(-frameCount*(TWO_PI/(float)gifCount));
rotateY(frameCount*(TWO_PI/(float)gifCount));
rotateZ(-frameCount*(TWO_PI/(float)gifCount));
stroke(keyColor);
strokeWeight(.5f);
line(0, 0, -3000, 0, 0, 3000);
noFill();
fill(baseColor);
noStroke();
for (float v = minV; v <= maxV; v += stepV) {
for (float u = minU; u <= maxU; u += stepU) {
float x= ((1 + (cos(u / 2) * sin(v) - sin(u / 2) * sin(2 * v))) * cos(u)) * scale;
float y= ((1 + (cos(u / 2) * sin(v) - sin(u / 2) * sin(2 * v))) * sin(u)) * scale;
float z= (2 * (sin(u / 2) * sin(v) + cos(u / 2) * sin(2 * v))) * scale;
pushMatrix();
translate(x, y, z);
// stroke(baseColor);
// point(0,0,0);
fill(baseColor);
sphere(6);
popMatrix();
}
}
gifDraw();
}
public void gifInit(){
if(isRecord == false){
return;
}
gifExport = new GifMaker(this, getClass().getSimpleName() +".gif"); // \u30d5\u30a1\u30a4\u30eb\u540d\u306eGIF\u30a2\u30cb\u30e1\u30fc\u30b7\u30e7\u30f3\u3092\u4f5c\u6210
gifExport.setRepeat(0); // \u30a8\u30f3\u30c9\u30ec\u30b9\u518d\u751f
gifExport.setQuality(8); // \u30af\u30aa\u30ea\u30c6\u30a3(\u30c7\u30d5\u30a9\u30eb\u30c810)
gifExport.setDelay(33); // \u30a2\u30cb\u30e1\u30fc\u30b7\u30e7\u30f3\u306e\u9593\u9694\u309230ms(33fps)\u306b
}
public void gifDraw(){
if(isRecord == false){
return;
}
//GIF\u30a2\u30cb\u30e1\u30fc\u30b7\u30e7\u30f3\u306e\u4fdd\u5b58
if(frameCount <= gifCount){
gifExport.addFrame(); // \u30d5\u30ec\u30fc\u30e0\u3092\u8ffd\u52a0
} else {
gifExport.finish(); // \u7d42\u4e86\u3057\u3066\u30d5\u30a1\u30a4\u30eb\u4fdd\u5b58
exit();
}
}
public void settings() { size(960, 540, P3D); smooth(); }
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "sketch_029" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
package pl.edu.agh.to2.commands;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import pl.edu.agh.to2.models.MarkerState;
import pl.edu.agh.to2.models.Turtle;
import java.util.ArrayDeque;
public class DrawCircle implements Command {
private final static Logger log = LogManager.getLogger(DrawCircle.class);
private AnchorPane pane;
private Turtle turtle;
private ArrayDeque<Circle> circles = new ArrayDeque<>();
private double radius;
public DrawCircle(AnchorPane pane, Turtle turtle, double radius) {
this.pane = pane;
this.turtle = turtle;
this.radius = radius;
}
@Override
public void execute() {
log.debug("Executing draw circle");
Circle circle;
circle = new Circle(turtle.getX(), turtle.getY(), radius, Color.TRANSPARENT);
circle.setStroke(Color.BLACK);
if (turtle.getMarker().getState() == MarkerState.LOWERED){
pane.getChildren().add(circle);
}
circles.addFirst(circle);
}
@Override
public void revert() {
log.debug("Reverting draw circle");
if(!circles.isEmpty()){
pane.getChildren().remove(circles.pollFirst());
} else {
log.warn("Trying to revert unexecuted command draw circle");
}
}
@Override
public String toString() {
return String.format("okrąg %f", radius);
}
}
|
package example.fakecall;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FakeRingingActivity extends AppCompatActivity {
private String networkCarrier;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fake_ringing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TextView fakeName = (TextView)findViewById(R.id.chosenfakename);
TextView fakeNumber = (TextView)findViewById(R.id.chosenfakenumber);
final TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
networkCarrier = tm.getNetworkOperatorName();
TextView titleBar = (TextView)findViewById(R.id.textView1);
if(networkCarrier != null){
titleBar.setText("Incoming call - " + networkCarrier);
}else{
titleBar.setText("Incoming call");
}
String callNumber = getContactNumber();
String callName = getContactName();
fakeName.setText(callName);
fakeNumber.setText(callNumber);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), notification);
mp.start();
Button answerCall = (Button)findViewById(R.id.answercall);
Button rejectCall = (Button)findViewById(R.id.rejectcall);
answerCall.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mp.stop();
}
});
rejectCall.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
mp.stop();
Intent homeIntent= new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
});
}
private String getContactNumber(){
String contact = null;
Intent myIntent = getIntent();
Bundle mIntent = myIntent.getExtras();
if(mIntent != null){
contact = mIntent.getString("myfakenumber");
}
return contact;
}
private String getContactName(){
String contactName = null;
Intent myIntent = getIntent();
Bundle mIntent = myIntent.getExtras();
if(mIntent != null){
contactName = mIntent.getString("myfakename");
}
return contactName;
}
}
|
package bspq21_e4.ParkingManagment.Classes;
import static org.junit.Assert.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.databene.contiperf.PerfTest;
import org.databene.contiperf.Required;
import org.databene.contiperf.junit.ContiPerfRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bspq21_e4.ParkingManagement.server.data.GuestUser;
import bspq21_e4.ParkingManagement.server.data.Parking;
import bspq21_e4.ParkingManagement.server.data.PremiumUser;
import bspq21_e4.ParkingManagement.server.data.Slot;
import bspq21_e4.ParkingManagement.server.data.SlotAvailability;
import junit.framework.JUnit4TestAdapter;
public class PremiumUserTest {
private Parking P1;
private PremiumUser PU1;
private Slot S1;
private static SimpleDateFormat sdfResult = new SimpleDateFormat("HH:mm", Locale.US);
private static double standardFee = 0.04;
final Logger logger = LoggerFactory.getLogger(PremiumUserTest.class);
static int iteration = 0;
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(PremiumUserTest.class);
}
@Before
public void setUp() throws ParseException {
logger.info("Entering setUp: {}", iteration++);
P1 = new Parking(1, "Getxo", 100, 50, 40, 2);
S1 = new Slot(1, 165, 2, SlotAvailability.GREEN, 1);
PU1 = new PremiumUser("jonmaeztu@opendeusto.es", "8534 GHL", 300, S1.getPk(), "PayPal");
logger.info("Leaving setUp");
}
@Test
public void PremiumUserClassTest() { // Test of all the GuestUser functions
assertEquals(PU1.getClass(), PremiumUser.class);
}
@Test
public void getPremiumUserPlateTest() { // Test of all the GuestUser functions
assertEquals("8534 GHL", PU1.getPlate());
}
@Test
public void setPremiumUserPlateTest() {
PU1.setPlate("3785 NAS");
assertEquals("3785 NAS", PU1.getPlate());
}
@Test
public void getPremiumUserEmailTest() { // Test of all the GuestUser functions
assertEquals("jonmaeztu@opendeusto.es", PU1.getEmail());
}
@Test
public void setPremiumUserEmailTest() {
PU1.setEmail("jon.churruca@opendeusto.es");
assertEquals("jon.churruca@opendeusto.es", PU1.getEmail());
}
@Test
public void getguestUserSlotTest() { // Test of all the GuestUser functions
assertEquals(S1.getPk(), PU1.getSlotPk());
}
@Test
public void setguestUserSlotTest() {
Slot S2 = new Slot(2, 170, 2, SlotAvailability.GREEN, 1);
PU1.setSlotPk(2);
assertEquals(S2.getPk(), PU1.getSlotPk());
}
@Test
public void getguestUserPaymentTest() { // Test of all the GuestUser functions
assertEquals("PayPal", PU1.getPaymentMethod());
}
@Test
public void setguestUserPaymentTest() {
PU1.setPaymentMethod("Paypal");
assertEquals("Paypal", PU1.getPaymentMethod());
}
@Test
public void getPremiumUserMonthFeeTest() { // Test of all the GuestUser functions
assertEquals(300, PU1.getMonthfee());
}
@Test
public void setPremiumUserMonthFeeTest() {
PU1.setMonthfee(400);
assertEquals(400, PU1.getMonthfee());
}
}
|
package utilserviceImple.UtilServiceImple;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the utilserviceImple.UtilServiceImple package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _RegistrarSolicitudResponse_QNAME = new QName("http://serviceImpl/", "registrarSolicitudResponse");
private final static QName _ListarClientesResponse_QNAME = new QName("http://serviceImpl/", "listarClientesResponse");
private final static QName _ListarClientes_QNAME = new QName("http://serviceImpl/", "listarClientes");
private final static QName _RegistrarSolicitud_QNAME = new QName("http://serviceImpl/", "registrarSolicitud");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: utilserviceImple.UtilServiceImple
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link ListarClientesResponse }
*
*/
public ListarClientesResponse createListarClientesResponse() {
return new ListarClientesResponse();
}
/**
* Create an instance of {@link RegistrarSolicitudResponse }
*
*/
public RegistrarSolicitudResponse createRegistrarSolicitudResponse() {
return new RegistrarSolicitudResponse();
}
/**
* Create an instance of {@link ListarClientes }
*
*/
public ListarClientes createListarClientes() {
return new ListarClientes();
}
/**
* Create an instance of {@link RegistrarSolicitud }
*
*/
public RegistrarSolicitud createRegistrarSolicitud() {
return new RegistrarSolicitud();
}
/**
* Create an instance of {@link Cliente }
*
*/
public Cliente createCliente() {
return new Cliente();
}
/**
* Create an instance of {@link Solicitud }
*
*/
public Solicitud createSolicitud() {
return new Solicitud();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link RegistrarSolicitudResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://serviceImpl/", name = "registrarSolicitudResponse")
public JAXBElement<RegistrarSolicitudResponse> createRegistrarSolicitudResponse(RegistrarSolicitudResponse value) {
return new JAXBElement<RegistrarSolicitudResponse>(_RegistrarSolicitudResponse_QNAME, RegistrarSolicitudResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ListarClientesResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://serviceImpl/", name = "listarClientesResponse")
public JAXBElement<ListarClientesResponse> createListarClientesResponse(ListarClientesResponse value) {
return new JAXBElement<ListarClientesResponse>(_ListarClientesResponse_QNAME, ListarClientesResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ListarClientes }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://serviceImpl/", name = "listarClientes")
public JAXBElement<ListarClientes> createListarClientes(ListarClientes value) {
return new JAXBElement<ListarClientes>(_ListarClientes_QNAME, ListarClientes.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link RegistrarSolicitud }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://serviceImpl/", name = "registrarSolicitud")
public JAXBElement<RegistrarSolicitud> createRegistrarSolicitud(RegistrarSolicitud value) {
return new JAXBElement<RegistrarSolicitud>(_RegistrarSolicitud_QNAME, RegistrarSolicitud.class, null, value);
}
}
|
package mk.finki.ukim.dians.surveygenerator.surveygeneratorcore.domain.jpamodels;
import lombok.*;
import javax.persistence.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Entity
@Table(schema = "survey_templates", name = "users_survey_templates")
public class UserSurveyTemplate {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "survey_template_id", nullable = false)
private SurveyTemplate surveyTemplate;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
}
|
package com.deepakm.ui;
import com.deepakm.impl.instrument.guitar.FretPosition;
import javax.swing.table.DefaultTableModel;
import java.util.Set;
/**
* Created by dmarathe on 11/14/16.
*/
public class GuitarTableModel extends DefaultTableModel {
public GuitarTableModel(Set<FretPosition> fretPositions) {
Object[][] model = new Object[6][12];
for(FretPosition fretPosition : fretPositions){
model[fretPosition.getStringNumber()-1][fretPosition.getFretPosition()] = fretPosition;
}
setDataVector(model, null);
}
}
|
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
public class SettingsController implements Initializable, IController
{
@FXML
private CheckBox indicatePlayerAttributesCheckBox, showPlayerAttributesCheckBox;
private MasterController masterController;
private String screenName;
@Override
public void setMasterController(MasterController masterController)
{
this.masterController = masterController;
}
@Override
public String getScreenName()
{
return this.screenName;
}
@Override
public void setScreenName(String name)
{
this.screenName = name;
}
@Override
public void initialize(URL location, ResourceBundle resources)
{
}
@FXML
private void handleDiscardChangesClick(ActionEvent ev)
{
this.masterController.changeScreenTo(this.masterController.getPreviousController().getScreenName());
}
@FXML
private void handleSaveChangesClick(ActionEvent e)
{
this.masterController.changeScreenTo(this.masterController.getPreviousController().getScreenName());
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
/* URL
http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=449&sca=50&sfl=wr_hit&stx=1169&sop=and
*/
public class Main1169_주사위던지기1 {
static int n;
static int m;
static int[] arr;
static ArrayList<StringBuilder> list = new ArrayList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new int[n];
switch (m) {
case 1:
fun1(0);
break;
case 2:
fun2(0);
break;
case 3:
fun3(0);
break;
}
for (StringBuilder sb : list) System.out.println(sb.toString());
}
public static void fun1(int loc) {
if (loc == n) {
StringBuilder sb = new StringBuilder();
for (int su : arr) sb.append(su).append(" ");
list.add(sb);
return;
}
for (int i = 1; i <= 6; i++) {
arr[loc] = i;
fun1(loc+1);
}
}
public static void fun2(int loc) {
if (loc == n) {
StringBuilder sb = new StringBuilder();
for (int su : arr) sb.append(su).append(" ");
list.add(sb);
return;
}
for (int i = (loc-1 < 0)? 1:arr[loc-1]; i <= 6; i++) {
arr[loc] = i;
fun2(loc+1);
}
}
public static void fun3(int loc) {
if (loc == n) {
StringBuilder sb = new StringBuilder();
for (int su : arr) sb.append(su).append(" ");
list.add(sb);
return;
}
for (int i = 1; i <= 6; i++) {
if (check(loc, i)) continue;
arr[loc] = i;
fun3(loc+1);
}
}
public static boolean check(int loc, int i) {
boolean check = false;
for (int j = 1; j < n; j++) {
if (check) break;
check = ( (loc-j < 0) ? 0 : arr[loc-j] ) == i;
}
return check;
}
}
|
import java.io.*;
import java.util.*;
class baek__1920 {
static int find(int target, int[] nums) {
int start = -1;
int end = nums.length;
while (start + 1 < end) {
int m = (start + end) / 2;
if (nums[m] <= target) {
start = m;
} else if (nums[m] > target) {
end = m;
}
}
if (start == -1)
return 0;
return nums[start] == target ? 1 : 0;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] temp = br.readLine().split(" ");
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = Integer.parseInt(temp[i]);
}
Arrays.sort(nums);
int m = Integer.parseInt(br.readLine());
temp = br.readLine().split(" ");
int[] targets = new int[m];
for (int i = 0; i < m; i++) {
targets[i] = Integer.parseInt(temp[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < m; i++) {
sb.append(find(targets[i], nums) + "\n");
}
System.out.print(sb);
}
}
|
package HackerRank.Day17;
public class Calculator {
public int power(int a, int b) throws NegativeException {
if (a < 0 || b < 0){
throw new NegativeException("n and p should be non-negative");
}
return (int) Math.pow(a,b);
}
}
|
package com.example;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
public class Criteria3 {
public static void main(String args[]){
Data.prepareData();
Session session = HibernateSessionFactory.getSession();
Criteria crit = session.createCriteria(Product.class);
crit.add(Restrictions.ilike("name","1", MatchMode.END));
List results = crit.list();
displayProductsList(results);
}
public static void displayProductsList(List list){
Iterator iter = list.iterator();
if (!iter.hasNext()){
System.out.println("No products to display.");
return;
}
while (iter.hasNext()){
Product product = (Product) iter.next();
String msg = product.getSupplier().getName() + "\t";
msg += product.getName() + "\t";
msg += product.getPrice() + "\t";
msg += product.getDescription();
System.out.println(msg);
}
}
}
|
package jgame.level.area;
import java.util.Collection;
import jgame.math.Vec2Int;
/**
*
* @author Hector
*/
public interface TileArea
{
public Collection<Vec2Int> getSubtiles(int subtileDimension);
}
|
package kr.hs.dgsw.webshoppingmall.Domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class User {
private Long id;
private String account;
private String password;
private String nickname;
private String gender;
private String imagePath;
private LocalDateTime created;
private LocalDateTime updated;
}
|
package com.epam.university.spring.dao;
import com.epam.university.spring.domain.Event;
public interface EventDao {
Event create(Event event);
void remove(Long id);
Event getByName(String name);
Event getById(Long id);
}
|
package com.curios.textformatter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FormatText {
/**
* All the processing is done under a try catch block so if there is any exceptions it will return the text as it is and print the exception stacktrace.
**/
/**
* Any text enclosed between *s i.e *text* will be bolded
* @param text
* @returns bolded and formatted text as a charsequence
*/
public static CharSequence bold(CharSequence text) {
try{
Pattern pattern = Pattern.compile("\\*(.*?)\\*");
SpannableStringBuilder ssb = new SpannableStringBuilder( text );
if( pattern != null )
{
Matcher matcher = pattern.matcher( text );
int matchesSoFar = 0;
while( matcher.find() )
{
int start = matcher.start() - (matchesSoFar * 2);
int end = matcher.end() - (matchesSoFar * 2);
CharacterStyle span = new StyleSpan(android.graphics.Typeface.BOLD);
ssb.setSpan( span, start + 1, end - 1, 0 );
ssb.delete(start, start + 1);
ssb.delete(end - 2, end -1);
matchesSoFar++;
}
}
return ssb;
}
catch (Exception e){
e.printStackTrace();
return text;
}
}
/**
* Any text enclosed between _s i.e _text_ will be shown in italics
* @param text
* @returns italicized formatted text as a charsequence
*/
public static CharSequence italics(CharSequence text) {
try{
Pattern pattern = Pattern.compile("_(.*?)_");
SpannableStringBuilder ssb = new SpannableStringBuilder( text );
if( pattern != null )
{
Matcher matcher = pattern.matcher( text );
int matchesSoFar = 0;
while( matcher.find() )
{
int start = matcher.start() - (matchesSoFar * 2);
int end = matcher.end() - (matchesSoFar * 2);
CharacterStyle span = new StyleSpan(Typeface.ITALIC);
ssb.setSpan( span, start + 1, end - 1, 0 );
ssb.delete(start, start + 1);
ssb.delete(end - 2, end -1);
matchesSoFar++;
}
}
return ssb;
}
catch (Exception e){
e.printStackTrace();
return text;
}
}
/**
* Any text enclosed between *s i.e * text * will be bolded and any text enclosed within _s will shown in italics
* @param text
* @returns bolded and italicized formatted text as a charsequence
*/
public static CharSequence boldAndItalics(CharSequence text) {
return italics(bold(text));
}
/**
* Any text enclosed between #s i.e * text * will be colored with a background color passed as the argument
* @param text
* @param color : which color to put as background passed as hex color string
* @param isBackground : True then color is set to background of text , if False then the text color is changed
* @returns colored formatted text as a charsequence
*/
public static CharSequence colorText(CharSequence text , String color, boolean isBackground) {
try{
Pattern pattern = Pattern.compile("#(.*?)#");
SpannableStringBuilder ssb = new SpannableStringBuilder( text );
if( pattern != null )
{
Matcher matcher = pattern.matcher( text );
int matchesSoFar = 0;
while( matcher.find() )
{
int start = matcher.start() - (matchesSoFar * 2);
int end = matcher.end() - (matchesSoFar * 2);
Log.d("color","msg: "+color);
CharacterStyle span;
if(isBackground)
span = new BackgroundColorSpan(Color.parseColor(color));
else
span = new ForegroundColorSpan(Color.parseColor(color));
ssb.setSpan( span, start + 1, end - 1, 0 );
ssb.delete(start, start + 1);
ssb.delete(end - 2, end -1);
matchesSoFar++;
}
}
return ssb;
}
catch (Exception e){
e.printStackTrace();
return text;
}
}
}
|
package ru.mstoyan.shiko.testtask.Utils;
import android.graphics.Path;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
/**
* Created by shiko on 09.02.2017.
*/
public class OldPathReader implements SVGReader {
private String filePath = null;
private static final String namespace = null;
private static final String commandsLarge = "MLHVCSQTAZ";
private static final String delimiter = ",";
private static final String numberChars = "0123456789.-+";
private OldPathReader(){}
public OldPathReader(String filePath){
this.filePath = filePath;
}
@Override
public Path getPath() throws IOException, ParseException, NumberFormatException {
Path result = new Path();
String data = getFileContent();
final int length = data.length();
String currentChar;
String prevChar = "";
float x1 = 0,x2 = 0,x3 = 0,y1 = 0,y2 = 0,y3 = 0;
boolean a, b;
int next;
for (int i = 0; i < length; i++){
currentChar = data.substring(i,i+1).toUpperCase();
i++;
switch (currentChar){
case "M":
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.moveTo(x1,y1);
i = next-1;
break;
case "L":
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.lineTo(x1,y1);
i = next-1;
break;
case "H":
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
result.lineTo(x1,y1);
i = next-1;
break;
case "V":
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.lineTo(x1,y1);
i = next-1;
break;
case "C":
next = readFloat(data,i);
x2 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y2 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
x3 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y3 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.cubicTo(x2,y2,x3,y3,x1,y1);
i = next-1;
break;
case "S":
if (prevChar.equals("C") || prevChar.equals("S")){
x2 = x1 + x1 - x3;
y2 = y1 + y1 - y3;
}
next = readFloat(data,i);
x3 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y3 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
if (!prevChar.equals("C") && !prevChar.equals("S")){
x2 = x1 + x1 - x3;
y2 = y1 + y1 - y3;
}
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.cubicTo(x2,y2,x3,y3,x1,y1);
i = next-1;
break;
case "Q":
next = readFloat(data,i);
x2 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y2 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.quadTo(x2,y2,x1,y1);
i = next-1;
break;
case "T":
x2 = x1 + x1 - x2;
y2 = y1 + y1 - y2;
next = readFloat(data,i);
x1 = Float.parseFloat(data.substring(i,next));
checkDelimiter(data,next);
i = next + 1;
next = readFloat(data,i);
y1 = Float.parseFloat(data.substring(i,next));
result.quadTo(x2,y2,x1,y2);
i = next-1;
break;
case "A":
break;
case "Z":
break;
default:
throw new ParseException("Wrong char!",i);
}
prevChar = currentChar;
}
return result;
}
private int readFloat(String str, int beginPos){
final int len = str.length();
while (beginPos < len && numberChars.contains(str.substring(beginPos,beginPos+1))) {
String currChar = str.substring(beginPos,beginPos+1);
beginPos++;
}
return beginPos;
}
private boolean checkDelimiter(String str, int pos){
return true;
}
private boolean checkBoolean(String str, int pos){
return true;
}
private String getFileContent() throws IOException {
StringBuilder strBuilder = new StringBuilder();
File file = new File (filePath);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine())!=null){
strBuilder.append(line);
strBuilder.append('\n');
}
return strBuilder.toString();
}
}
|
package team.groupproject.converters;
import java.util.List;
import java.util.stream.Collectors;
import team.groupproject.dto.MaterialDto;
import team.groupproject.dto.ProductDto;
import team.groupproject.entity.Product;
public class ProductConverter {
public static ProductDto convertToProductDto(Product product) {
List<String> productImagePaths = product.getProductsImages().stream().map(p -> p.getImagePath())
.collect(Collectors.toList());
List<MaterialDto> materialsList = product.getMaterials().stream()
.map(m -> new MaterialDto(m.getId(), m.getName())).collect(Collectors.toList());
return new ProductDto(product.getId(), product.getName(), product.getDescription(), product.getPrice(),
product.getSku(), product.getDiscount(), product.getStock(),
product.getCategory() != null ? product.getCategory().getName() : "",
product.getStyle() != null ? product.getStyle().getName() : "",
productImagePaths, materialsList);
}
}
|
package presentation.controller;
import common.AccountType;
import common.ResultMessage;
/**
* Created by Molloh on 2016/11/5.
*/
public interface LoginViewControllerService {
/**
* 用户账号登录s
* @return 账号登录是否成功,成功返回用户类型AccountType
* @author lienming
* @version 2016-11-27
*/
public AccountType login(String memberName, String password) ;
public ResultMessage logout(String id) ;
}
|
package com.yoke.poseidon.member;
import org.modelmapper.ModelMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* @Author Yoke
* @Date 2019/01/24 下午1:44
*/
@MapperScan(basePackages = "com.yoke.poseidon.member.mapper")
@SpringBootApplication
public class MemberApplication {
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
public static void main(String[] args) {
SpringApplication.run(MemberApplication.class, args);
}
}
|
package br.com.transactions.dto;
import java.math.BigDecimal;
import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SummarySaleDataTransferObject {
@JsonProperty("net_amount_sale")
@NotNull(message = "net_amount_sale is required!")
private BigDecimal netAmountSale;
@JsonProperty("gross_amount_sale")
@NotNull(message = "gross_amount_sale is required!")
private BigDecimal grossAmountSale;
@JsonProperty("merchant_discount_rate")
@NotNull(message = "merchant_discount_rate is required!")
private Double merchantDiscountRate;
@JsonProperty("number_summary_sale")
@NotNull(message = "number_summary_sale is required!")
private Long numberSummarySale;
public SummarySaleDataTransferObject(BigDecimal netAmountSale, BigDecimal grossAmountSale,
Double merchantDiscountRate, Long numberSummarySale) {
this.netAmountSale = netAmountSale;
this.grossAmountSale = grossAmountSale;
this.merchantDiscountRate = merchantDiscountRate;
this.numberSummarySale = numberSummarySale;
}
public BigDecimal getNetAmountSale() {
return netAmountSale;
}
public BigDecimal getGrossAmountSale() {
return grossAmountSale;
}
public Double getMerchantDiscountRate() {
return merchantDiscountRate;
}
public Long getNumberSummarySale() {
return numberSummarySale;
}
}
|
/**
* ErrorEnum
*/
package com.bs.bod.error;
import java.io.Serializable;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
/**
* Java defines two kinds of exceptions:
*
* Checked exceptions: Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the
* API, either in a catch clause or by forwarding it outward with the throws clause.
*
* Unchecked exceptions: RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment.
* There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions.
*
* @author dbs on Dec 26, 2015 10:21:13 PM
* @since V0.0.1
* @version 1.0
* @version 1.1 add {@value #technicalDetail}, {@value #functionalDetail}, {@link #exceptionDetail}
*
*/
public enum ErrorType implements Serializable, Iterable<ErrorType>{
none(BodError.TYPE_NONE, ""),
/**
* java exception or programmatic
*/
exception(BodError.TYPE_EXCEPTION, "Programmatic"),
/**
* technical or resource
*/
technical(BodError.TYPE_TECHNICAL, "Technical"),
/**
* functional or business
*/
functional(BodError.TYPE_FUNCTIONAL, "Functional"),
/**
* java exception or programmatic used to add stacktrace or extra very long message not for end-user consumption
*/
exceptionDetail(BodError.TYPE_EXCEPTION_DETAIL, "Programmatic detailed"),
/**
* technical or resource used to add stacktrace or extra very long message not for end-user consumption
*/
technicalDetail(BodError.TYPE_TECHNICAL_DETAIL, "Technical detailed"),
/**
* functional or business used to add stacktrace or extra very long message not for end-user consumption
*/
functionalDetail(BodError.TYPE_FUNCTIONAL_DETAIL, "Functional detailed");
long mask;
String label;
ErrorType(long mask, String label){
this.mask = mask;
this.label = label;
}
/**
* @return the mask
*/
public long getMask() {
return mask;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
public static ErrorType find(long toSearch){
for (ErrorType npt : ErrorType.values()) {
if((toSearch & npt.mask) == npt.mask)
return npt;
}
return none;
}
public static ErrorType find(String toSearch) {
if (StringUtils.isNotBlank(toSearch))
for (ErrorType npt : ErrorType.values()) {
if ( toSearch.equalsIgnoreCase(npt.name()) || toSearch.equalsIgnoreCase(npt.label))
return npt;
}
return none;
}
@Override
public Iterator<ErrorType> iterator() {
return new Iterator<ErrorType>() {
private int index = 0;
@Override
public boolean hasNext() {
int size = ErrorType.values().length;
if (index >= size) {
index = 0;// reinit
return false; // end iteration
}
return index < size;
}
@Override
public ErrorType next() {
switch (index) {
default:
return ErrorType.values()[index++];
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
/* (non-Javadoc)
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return getLabel();
}
}
|
package com.alexey.vk.view.registration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.alexey.vk.MainActivity;
import com.alexey.vk.R;
import com.alexey.vk.model.OnBackPressedListener;
import com.alexey.vk.view.logged.NewsFragment;
public class RegSecond extends Fragment implements OnBackPressedListener {
Fragment fragment;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View regSecond = inflater.inflate(R.layout.reg_second, container, false);
clickAgree(regSecond);
carbon.widget.Button apply = (carbon.widget.Button) regSecond.findViewById(R.id.reg_apply);
apply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity activity = (MainActivity) getActivity();
if (activity.setUserNameInHeader()) {
activity.createDrawer();
getFragmentManager().beginTransaction()
.replace(R.id.frame, new NewsFragment())
.commit();
}
else Toast.makeText(getContext(),"not", Toast.LENGTH_SHORT).show();
// String number = ((EditText) regSecond.findViewById(R.id.editText2)).getText().toString();
// String countryCode = ((TextView) regSecond.findViewById(R.id.country_code)).getText().toString();
// Bundle bundle = new Bundle();
// bundle.putString("code", countryCode);
// bundle.putString("phone_number", number);
}
});
return regSecond;
}
@Override
public void onBackPressed() {
getFragmentManager().beginTransaction()
.replace(R.id.frame, new RegFirst())
.commit();
}
public void clickAgree(View view) {
final TextView countryCode = (TextView) view.findViewById(R.id.country_code);
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.countries, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner countries = (Spinner) view.findViewById(R.id.countries);
countries.setAdapter(adapter);
countries.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
countryCode.setText("7");
} else if (position == 1) {
countryCode.setText("236");
} else if (position == 2) {
countryCode.setText("35");
} else if (position == 3) {
countryCode.setText("45");
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
|
package com.example.springsecuritywithmongo.Service;
import com.example.springsecuritywithmongo.Domain.MyUserDetails;
import com.example.springsecuritywithmongo.Domain.User;
import com.example.springsecuritywithmongo.Repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
/**
* created by lovedeep in com.example.springsecuritywithmongo.Service
*/
@Service@Qualifier("MongoUserDetail")
public class UserDetailService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUserName(userName);
user.orElseThrow(() -> new UsernameNotFoundException("Not found: " + userName));
return user.map(MyUserDetails::new).get();
}
}
|
package ua.com.rd.pizzaservice.repository.order.db;
import org.springframework.stereotype.Repository;
import ua.com.rd.pizzaservice.domain.address.Address;
import ua.com.rd.pizzaservice.domain.customer.Customer;
import ua.com.rd.pizzaservice.domain.order.Order;
import ua.com.rd.pizzaservice.domain.pizza.Pizza;
import ua.com.rd.pizzaservice.repository.order.OrderRepository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.util.*;
@Repository
public class PostgreSQLOrderRepository implements OrderRepository {
@PersistenceContext
private EntityManager entityManager;
public PostgreSQLOrderRepository() {
}
public PostgreSQLOrderRepository(EntityManager entityManager) {
this.entityManager = entityManager;
}
public EntityManager getEntityManager() {
return entityManager;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Long saveOrder(Order order) {
Address managedOrdersAddress = entityManager.merge(order.getAddress());
order.setAddress(managedOrdersAddress);
Set<Address> managedCustomersAddresses = new HashSet<>();
for (Address address : order.getCustomer().getAddresses()) {
managedCustomersAddresses.add(entityManager.merge(address));
}
order.getCustomer().setAddresses(managedCustomersAddresses);
Customer managedCustomer = entityManager.merge(order.getCustomer());
order.setCustomer(managedCustomer);
entityManager.persist(order);
return order.getId();
}
@Override
public Order getOrderById(Long id) {
TypedQuery<Order> query = entityManager.createQuery(
"SELECT o FROM Order o JOIN FETCH o.pizzas WHERE o.id= :id", Order.class);
query.setParameter("id", id);
List<Order> orders = query.getResultList();
if (orders.size() == 0) {
return null;
}
return orders.get(0);
}
@Override
public void updateOrder(Order order) {
Order managedOrder = entityManager.find(Order.class, order.getId());
Map<Pizza, Integer> managedPizzas = new HashMap<>();
for (Map.Entry<Pizza, Integer> pizzas : order.getPizzas().entrySet()) {
managedPizzas.put(entityManager.find(Pizza.class, pizzas.getKey().getId()), pizzas.getValue());
}
managedOrder.setAddress(entityManager.getReference(Address.class, order.getAddress().getId()));
managedOrder.setPizzas(managedPizzas);
managedOrder.setCustomer(entityManager.getReference(Customer.class, order.getCustomer().getId()));
managedOrder.setCreationDate(order.getCreationDate());
managedOrder.setDoneDate(order.getDoneDate());
managedOrder.setCurrentState(order.getCurrentState());
managedOrder.setFinalPrice(order.getFinalPrice());
entityManager.flush();
}
@Override
public void deleteOrder(Order order) {
Order managedOrder = entityManager.find(Order.class, order.getId());
entityManager.remove(managedOrder);
entityManager.flush();
}
@Override
public Set<Order> getAllOrders() {
return new HashSet<>(entityManager.createQuery("" +
"SELECT o FROM Order o JOIN FETCH o.pizzas",
Order.class).getResultList());
}
@Override
public Long countOfOrders() {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Order.class)));
return entityManager.createQuery(cq).getSingleResult();
}
}
|
public class Cell {
public boolean status;
private int value;
public int coordinateX;
public int coordinateY;
private boolean exit;
private boolean visited;
public Cell() {
}
public Cell(int x, int y) {
this.coordinateX = x;
this.coordinateY = y;
}
public Cell(boolean status, int value, int x, int y) {
this.status = status;
this.value = value;
coordinateX = x;
coordinateY = y;
}
public void exit(boolean exit){
this.exit = exit;
}
public boolean isExit(){
return exit;
}
public void setVisited(boolean visited){
this.visited = visited;
}
public boolean isVisited(){
return visited;
}
public boolean isOpen() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int Value(){
return value;
}
public void setValue(int value){
this.value = value;
}
}
|
package com.beike.entity.onlineorder;
import java.sql.Timestamp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class AbstractEngine {
public static final String json_key_price = "price";
public static final String json_key_discount = "discount";
public static final String json_key_discount_type = "discounttype";
static final Log logger = LogFactory.getLog(AbstractEngine.class);
private Timestamp starttime;
private Timestamp endtime;
public Timestamp getStarttime() {
return starttime;
}
public void setStarttime(Timestamp starttime) {
this.starttime = starttime;
}
public Timestamp getEndtime() {
return endtime;
}
public void setEndtime(Timestamp endtime) {
this.endtime = endtime;
}
private Long engineId;
public Long getEngineId() {
return engineId;
}
public void setEngineId(Long engineId) {
this.engineId = engineId;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
private Long orderId;
//全端计算价格
public abstract String formatJson();
//计算支付价格
public abstract double caculatePay(double subAmount);
//活动信息
public abstract String getPromotionInfo();
//活动说明
private String tip;
private boolean isOnline;
public boolean isOnline() {
return isOnline;
}
public void setOnline(boolean isOnline) {
this.isOnline = isOnline;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
}
|
package com.dian.diabetes.activity.sugar;
import java.util.List;
import com.dian.diabetes.activity.sugar.model.MapModel;
import com.dian.diabetes.dialog.GPopDialog;
import android.content.Context;
/**
* 统计弹出选择框
*/
public class TotalPopDialog extends GPopDialog {
public TotalPopDialog(Context context) {
super(context);
}
@Override
protected void initData(List<MapModel> data) {
MapModel modela = new MapModel("breakfast_pre", "总体");
data.add(modela);
MapModel model = new MapModel("breakfast_pre", "早餐前");
data.add(model);
MapModel model1 = new MapModel("breakfast_after", "早餐后");
data.add(model1);
MapModel model2 = new MapModel("lunch_pre", "中餐前");
data.add(model2);
MapModel model3 = new MapModel("lunch_after", "中餐后");
data.add(model3);
MapModel model4 = new MapModel("dinner_pre", "晚餐前");
data.add(model4);
MapModel model5 = new MapModel("dinner_after", "晚餐后");
data.add(model5);
MapModel model6 = new MapModel("dinner_after", "睡前");
data.add(model6);
}
}
|
package com.javasampleapproach.mysql.hall.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javasampleapproach.mysql.hall.model.Residence;
import com.javasampleapproach.mysql.hall.repo.ResidenceRepository;
import com.javasampleapproach.mysql.model.Admission;
import com.javasampleapproach.mysql.model.Api;
import com.javasampleapproach.mysql.repo.ApiRepository;
@Service
public class ResidenceService {
@Autowired
private ResidenceRepository residencerepo;
public void addresidence(Residence residence){
residencerepo.save(residence);
}
public void deleteresidence(long id) {
residencerepo.delete(id);
}
public void updateresidence(long id, Residence residence) {
residencerepo.save(residence);
}
public Residence getresidence(long id)
{
return (Residence) residencerepo.findOne(id);
}
public List<Residence>getallresidence()
{
List<Residence> residence=new ArrayList<>();
residencerepo.findAll()
.forEach(residence::add);
return residence;
}
}
|
package L5_ExerciciosFuncoes;
public class Ex02_L5 {
public String montarEstrutura(int numerosDeRepeticoes){
StringBuilder estruturaS = new StringBuilder();
for (int i = 0; i <= (numerosDeRepeticoes -1); i++){
for (int j = 0; j < i+1; j++){
estruturaS.append(j + 1).append(" ");
}
estruturaS.append("\n");
}
return String.valueOf(estruturaS);
}
}
|
/* Copyright 2013 François Lolom
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.hotcocoacup.appenginecas.sample;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class MoodleCASLoginServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
MoodleCASAuthenticator auth = new MoodleCASAuthenticator(req.getParameter("serviceurl"), req.getParameter("casurl"));
String response;
try {
MoodleSession authResult = auth.authenticateToMoodle(
req.getParameter("email"), req.getParameter("password")
);
if (authResult == null) {
response = "The email/password does not match";
} else {
response = "Cookie to reinject during the session = " + authResult.toString();
}
} catch (Exception e) {
response = e.getMessage();
}
resp.setContentType("text/plain");
resp.getWriter().println(response);
}
}
|
package com.role.game.util;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.mockito.Mockito;
import com.role.game.exception.DependencyInjectionException;
import com.role.game.io.reader.InputReader;
public class DependencyInjectorTest {
@Test
public void getObject() {
assertNotNull(DependencyInjector.getObject(InputReader.class));
}
@Test(expected = DependencyInjectionException.class)
public void getInvalidObject() {
DependencyInjector.getObject(Mockito.class);
}
}
|
package coinpurse.strategy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import coinpurse.Valuable;
import coinpurse.ValueComparator;
/**
* Find strategy to withdraw a money in the purse.
* @author Tanasorn Tritawisup
*
*/
public class GreedyWithdraw implements WithdrawStrategy {
private Comparator<Valuable> comparator = new ValueComparator();
/**
* Withdraw the amount, using only items that have
* the same currency as the parameter(amount).
* amount must not be null and amount.getValue() > 0.
* @param amount is a money that want to withdraw.
* @param valuables is a list of money.
* @return List of Valuable class for money withdrawn,
* or null if cannot withdraw requested amount.
*/
@Override
public List<Valuable> withdraw(Valuable amount, List<Valuable> valuables) {
double value = amount.getValue();
List<Valuable> withdraw = new ArrayList<Valuable>();
double getBalance = 0;
for(Valuable v : valuables) getBalance += v.getValue();
if (value <= 0 || value > getBalance) return null;
java.util.Collections.sort(valuables);
Collections.sort((List<Valuable>) valuables, comparator);
for (int i = valuables.size() - 1; i >= 0; i--) {
if (value >= valuables.get(i).getValue()) {
value -= valuables.get(i).getValue();
withdraw.add(valuables.get(i));
}
}
if (value != 0) return null;
return withdraw;
}
}
|
package com.wso2.build.rules.dependency_management;
import com.wso2.build.utils.Helper;
import junit.framework.Assert;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.testng.annotations.Test;
import java.net.URL;
/**
* Created by uvindra on 2/26/14.
*/
public class EnforceDependencyManagementParentMojoTest {
/**
*
* Test for rule failure
*/
@Test(expectedExceptions = MojoExecutionException.class)
public void testDependencyManagementNotInParent() throws Exception {
URL parentURL = this.getClass().getResource("/dependency_management/dependency_management_not_in_parent.xml");
EnforceDependencyManagementParentMojo mojo = new EnforceDependencyManagementParentMojo();
MavenProject mavenProject = Helper.getTestParentProject(parentURL);
Assert.assertNotNull(mavenProject);
mojo.injectTestProject(mavenProject);
mojo.execute();
}
/**
*
* Test for rule success
*/
@Test
public void testDependencyManagementInParent() throws Exception {
URL parentURL = this.getClass().getResource("/dependency_management/dependency_management_in_parent.xml");
EnforceDependencyManagementParentMojo mojo = new EnforceDependencyManagementParentMojo();
MavenProject mavenProject = Helper.getTestParentProject(parentURL);
Assert.assertNotNull(mavenProject);
mojo.injectTestProject(mavenProject);
mojo.execute();
}
}
|
import java.util.HashMap;
import java.util.Map;
import com.opensymphony.xwork2.Action;
public class DatabaseJSON {
private Map<String, String> database= new HashMap<String, String>();
public DatabaseJSON() {
// TODO Auto-generated constructor stub
database.put("MySQL", "MySQL");
database.put("Oracle", "Oracle");
database.put("PostgreSQL", "PostgreSQL");
database.put("DB2", "DB2");
database.put("Others", "Others");
}
public String execute() {
// TODO Auto-generated method stub
return Action.SUCCESS;
}
public Map<String, String> getDatabase() {
return database;
}
public void setDatabase(Map<String, String> database) {
this.database = database;
}
}
|
package com.platform.common.handler;
import java.sql.SQLException;
import org.apache.ibatis.type.TypeException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.platform.common.exception.MessageException;
import com.platform.common.page.JsonVo;
@ControllerAdvice
public class ApiExceptionHandler {
// public Logger logger = Logger.getLogger(this.getClass());
@ResponseStatus(value=HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
@ResponseBody
public JsonVo<String> badRequest(Exception e){
JsonVo<String> vo=new JsonVo<String>();
vo.fail(getExceptionMsg(e));
//logger.error(e);
return vo;
}
public static String getExceptionMsg(Exception e){
String msg="操作失败";
if(e.getCause() instanceof SQLException){
SQLException se=(SQLException)e.getCause();
int errorCode=se.getErrorCode();
return se.getLocalizedMessage();
}else if(e.getCause() instanceof TypeException){
return "当前数据类型与数据库类型不一致,操作数据库失败!!";
}else if(e instanceof MessageException){
msg=e.getMessage();
}else {
return msg+":"+e.getMessage();
}
return msg;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.