blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
feeb00eceb18c0dc2f12aee300ba6bc045a86e82
Java
wangweijun123/Mashibing_High_Concurrency
/src/main/java/com/mark/concurrent26/T13_ThreadPoolExecutor.java
UTF-8
237
1.867188
2
[]
no_license
package com.mark.concurrent26; import java.io.IOException; /** * @author MarkShen * 自定义线程池 */ public class T13_ThreadPoolExecutor { public static void main(String[] args) throws InterruptedException, IOException { } }
true
40612f5110f5a7920424cf49abca3ef5f6118267
Java
omaftiyak/javacourse
/lab2/src/main/java/omaftiyak/javacourse/lab2/dao/ConnectionFactory.java
UTF-8
1,758
3.046875
3
[]
no_license
package omaftiyak.javacourse.lab2.dao; import java.io.FileInputStream; import java.io.FileOutputStream; import java.sql.*; import java.util.Properties; /** * Creates DB connections */ public class ConnectionFactory { private static final ConnectionFactory instance = new ConnectionFactory(); private final Driver driver; private final Properties properties; private ConnectionFactory() { try { properties = new Properties(); properties.load(getClass().getResourceAsStream("/app.properties")); Class<?> driverClass = Class.forName(properties.getProperty("libraryapp.jdbc.driverclass")); driver = (Driver) driverClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Could not initialize ConnectionFactory", e); } } public static ConnectionFactory getInstance() { return instance; } public static Connection getCon() throws SQLException { return getInstance().getConnection(); } public static long getLastId(Connection connection) { try (PreparedStatement ps = connection.prepareStatement("select lastval()")) { try (ResultSet rs = ps.executeQuery()) { rs.next(); return rs.getLong(1); } } catch (Exception e) { throw new RuntimeException("Could not get last id", e); } } public Connection getConnection() throws SQLException { return DriverManager.getConnection( properties.getProperty("libraryapp.jdbc.url"), properties.getProperty("libraryapp.jdbc.username"), properties.getProperty("libraryapp.jdbc.password") ); } }
true
cbd88071454b36c158440ba85c76c242445d10cc
Java
francav/mybudget_jee
/mybudget_jee/webapp/src/main/java/br/com/victorpfranca/mybudget/infra/mail/MailSender.java
UTF-8
2,385
2.28125
2
[]
no_license
package br.com.victorpfranca.mybudget.infra.mail; import java.io.Serializable; import java.nio.charset.StandardCharsets; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.ws.rs.core.MediaType; import br.com.victorpfranca.mybudget.infra.App; public class MailSender implements Serializable { private static final long serialVersionUID = 1L; @Resource(mappedName = "java:jboss/mail/meussaldos") private Session mailSession; private String mailContentType; private String mailEncoding; @EJB private App app; @PostConstruct void postConstruct() { this.mailContentType = MediaType.TEXT_HTML; this.mailEncoding = StandardCharsets.UTF_8.displayName(); } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void sendMail(String sMailFrom, String sMailTo, String sSubject, String sMailText) { if (app.isProductionMode()) { try { MimeMessage message = new MimeMessage(mailSession); message.addRecipient(Message.RecipientType.TO, new InternetAddress(sMailTo)); message.setHeader("Content-Type", this.mailContentType + "; charset=\"" + this.mailEncoding + "\""); message.setSubject(sSubject); message.setFrom(sMailFrom); message.setText(sMailText, StandardCharsets.UTF_8.displayName(), "html"); Transport.send(message); } catch (MessagingException e) { throw new EJBException(e); } } } @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void sendMail(String sMailTo, String sSubject, String sMailText) { if (app.isProductionMode()) { try { MimeMessage message = new MimeMessage(mailSession); message.addRecipient(Message.RecipientType.TO, new InternetAddress(sMailTo)); message.setHeader("Content-Type", this.mailContentType + "; charset=\"" + this.mailEncoding + "\""); message.setSubject(sSubject); message.setText(sMailText, StandardCharsets.UTF_8.displayName(), "html"); Transport.send(message); } catch (MessagingException e) { throw new EJBException(e); } } } }
true
14c327616764024fd889f75203057a484a318d8b
Java
yuganksinghal/lucid-the-game
/src/edu/virginia/engine/events/CollisionManager.java
UTF-8
364
2.609375
3
[]
no_license
package edu.virginia.engine.events; public class CollisionManager extends EventDispatcher { @Override public void dispatchEvent(Event event) { super.dispatchEvent(event); CollisionEvent e = (CollisionEvent) event; // System.out.println("Collision between " + ((CollisionEvent) event).o1.getId() + " and " + ((CollisionEvent) event).o2.getId() + "."); } }
true
e12e9d4c4cbf6c7db41f219eddabd3f49c88e993
Java
greysonOuyang/protocol-test-system
/src/main/java/com/yuyi/pts/netty/handler/ProjectConfigHandler.java
UTF-8
6,817
2.40625
2
[]
no_license
package com.yuyi.pts.netty.handler; import com.yuyi.pts.common.constant.ConstantValue; import com.yuyi.pts.common.enums.FieldType; import com.yuyi.pts.common.util.ByteUtils; import com.yuyi.pts.common.util.ScheduledThreadPoolUtil; import com.yuyi.pts.entity.ParamEntity; import com.yuyi.pts.model.protocol.SmartCarProtocol; import com.yuyi.pts.model.vo.InterfaceVo; import com.yuyi.pts.netty.NettyClient; import com.yuyi.pts.service.ResponseService; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit; /** * 根据配置生成信息的处理器 * * @author greyson * @since 2021/4/27 */ @Slf4j @Component @Scope("prototype") @NoArgsConstructor public class ProjectConfigHandler extends ChannelInboundHandlerAdapter { @Autowired SmartCarProtocol protocol; @Autowired ResponseService responseService; InterfaceVo interfaceVo; /** * 模式 client或者 Server */ String mode; public ProjectConfigHandler(InterfaceVo interfaceVo, String mode) { this.interfaceVo = interfaceVo; this.mode = mode; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("连接建立成功"); NettyClient.channelFuture.addListener((ChannelFutureListener) future -> { //如果连接成功 if (future.isSuccess()) { if (ConstantValue.CLIENT.equals(mode)) { byte[] sourceByteArr = buildMsg(); ScheduledThreadPoolUtil.scheduleAtFixedRateByTime(()-> { log.info("接口配置处理器发送消息"); ctx.channel().writeAndFlush(sourceByteArr); },0, 10, 1, TimeUnit.MINUTES); } } }); //添加连接 log.info("接口配置处理器已经激活:" + ctx.channel()); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { log.info("收到请求了"); Map<String, Object> messageMap = new HashMap<String, Object>(); messageMap.put("input", msg); super.channelRead(ctx, msg); byte[] sourceByteArr = buildMsg(); messageMap.put("output", sourceByteArr); responseService.broadcast("/topic/response", messageMap); ctx.channel().writeAndFlush(sourceByteArr); } /** * 根据配置生成要发送的消息 * * @return 字节数据 */ private byte[] buildMsg() { List<ParamEntity> outputList = interfaceVo.getOutput(); byte[] sourceByteArr = buildMessageType(); // 写入数据,组织成对方想要的数据 for (ParamEntity param : outputList) { // 当前字段长度 int currentFieldLength = param.getLength(); String value = param.getValue().trim(); String type1 = param.getType(); Optional<FieldType> first = Arrays.stream(FieldType.values()).filter((item) -> { return item.equals(param.getType()); }).findFirst(); FieldType type = null; if (first.isPresent()) { type =first.get(); } // 发给对方时的字节数, 默认是当前参数自带的length字段 int storeLength = currentFieldLength; byte[] tempBytes = null; // 解析数据转成字节数组bytes if (type == FieldType.Hex) { tempBytes = ByteUtils.hexString2Bytes(value); } else if (type == FieldType.Int) { tempBytes = ByteUtils.decimalStrToHex(value); } else if (type == FieldType.String) { tempBytes = value.getBytes(StandardCharsets.UTF_8); } else if (type == FieldType.ASCII) { tempBytes = ByteUtils.asciiToHex(value); } else if (type == FieldType.Time) { ByteBuf byteBuf = Unpooled.buffer(); byte[] timeByteArr = new byte[7]; String[] timeStr = value.split("-"); for (String str : timeStr) { byte[] bytes = ByteUtils.shortToByte2SmallEnd(ByteUtils.intToShort(Integer.parseInt(str))); if (bytes[1] == 0) { bytes = ByteUtils.storeInBytes(bytes, 1); } byteBuf.writeBytes(bytes); } byteBuf.readBytes(timeByteArr); tempBytes = timeByteArr; } // 计算长度 if (currentFieldLength == -1) { int length = tempBytes.length; // 如果是ascii码形式,计算当前数据长度并赋值给上一个参数的Value sourceByteArr[sourceByteArr.length - 1] = ByteUtils.intToByte(length); storeLength = length; } if (tempBytes != null) { tempBytes = ByteUtils.storeInBytes(tempBytes, storeLength); if (sourceByteArr == null) { sourceByteArr = tempBytes; } else { sourceByteArr = ByteUtils.addByteArrays(sourceByteArr, tempBytes); } } } return sourceByteArr; } /** * 12-18号线的接口需要传输MessageType */ private byte[] buildMessageType() { byte[] sourceByteArr = null; if (interfaceVo.getMessageType() != null) { String interfaceType = interfaceVo.getMessageType(); if (protocol.getLineId() == 14) { sourceByteArr = ByteUtils.storeInBytesLow(ByteUtils.hexString2Bytes(interfaceType), 1); } else { sourceByteArr = ByteUtils.storeInBytesLow(ByteUtils.hexString2Bytes(interfaceType), 2); } } return sourceByteArr; } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { //断开连接 log.debug("与[{}]的连接断开", ctx.channel().remoteAddress()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { log.info("处理消息出现了异常:[{}]", cause.getMessage()); super.exceptionCaught(ctx, cause); } }
true
ee75e143c70842af43e42b4ee075afb1ec723324
Java
runeks/admin-testcase
/admin-testcase/admin-frontend-testcase/src/main/java/no/valg/eva/admin/counting/presentation/view/LateValidationCoversModel.java
UTF-8
1,361
2.328125
2
[]
no_license
package no.valg.eva.admin.counting.presentation.view; import java.util.ArrayList; import no.valg.eva.admin.counting.presentation.PreliminaryCountController; public class LateValidationCoversModel extends ArrayList<ModelRow> { private final PreliminaryCountController ctrl; public LateValidationCoversModel(final PreliminaryCountController ctrl) { this.ctrl = ctrl; add(new ModelRow() { @Override public String getTitle() { return "@count.ballot.electoral_roll"; } @Override public Long getCount() { return (long) ctrl.getCounts().getMarkOffCount(); } @Override public void setCount(Long count) { ; } @Override public boolean isCountInput() { return false; } }); add(new ModelRow() { @Override public String getTitle() { return "@count.ballot.late_validation_covers"; } @Override public Long getCount() { return (long) ctrl.getCount().getLateValidationCovers(); } @Override public void setCount(Long count) { if (count == null) { ctrl.getPreliminaryCount().setLateValidationCovers(null); } else { ctrl.getPreliminaryCount().setLateValidationCovers(count.intValue()); } } @Override public boolean isCountInput() { return true; } }); } public int getTotalMarkOffCount() { return ctrl.getTotalMarkOffCount(); } }
true
19c737e1a4ba79d6f5b008e4af14800a4897bfb3
Java
f-lab-edu/simple_sns
/src/main/java/com/photobook/exception/ExceptionType.java
UTF-8
201
1.960938
2
[]
no_license
package com.photobook.exception; import lombok.Getter; @Getter public class ExceptionType { private final String type; ExceptionType(final String type) { this.type = type; } }
true
5213f0973ab57dccef95d4feabda339a225db934
Java
heralight/generator-android-hipster
/push/templates/app-java/src/main/java/_DefaultPushReceiver.java
UTF-8
594
1.898438
2
[ "Apache-2.0" ]
permissive
package <%= appPackage %>.services.push; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; public class DefaultPushReceiver extends BroadcastReceiver { public DefaultPushReceiver() { } @Override public void onReceive(Context context, Intent intent) { Intent push = new Intent(context, PushIntentService.class); push.putExtras(getResultExtras(true)); context.startService(push); setResultCode(Activity.RESULT_OK); } }
true
4b0da1427726f1740ece2d4ae77ba67c82e4a407
Java
besse/TeamPlay
/client/src/main/java/com/teamplay/Game.java
UTF-8
3,076
2.375
2
[]
no_license
package com.teamplay; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.teamplay.input.InputService; import com.teamplay.input.KeyboardInputService; import com.teamplay.input.MouseInputService; import com.teamplay.managers.GameStateManager; import com.teamplay.managers.ResourceManager; import org.slf4j.LoggerFactory; import org.slf4j.Logger; /** * Main game container. * <p/> * User: jonasbirgersson * Date: 2014-04-02 * Time: 9:22 AM */ public class Game implements ApplicationListener { private final int WIDTH = 320; private final int HEIGHT = 240; private SpriteBatch spriteBatch; private GameStateManager gameStateManager; private OrthographicCamera camera; private OrthographicCamera hudCamera; private ResourceManager resourceManager; private static final Logger LOGGER = LoggerFactory.getLogger(Game.class); private InputService inputService; public Game(){ } @Override public void create() { resourceManager = new ResourceManager(); spriteBatch = new SpriteBatch(); BitmapFont font = new BitmapFont(); font.setColor(Color.GREEN); LOGGER.debug("Screen width: " + Gdx.graphics.getWidth()); camera = new OrthographicCamera(); camera.setToOrtho(false, WIDTH, HEIGHT); hudCamera = new OrthographicCamera(); hudCamera.setToOrtho(false, WIDTH, HEIGHT); inputService = new KeyboardInputService(); //inputService = new MouseInputService(camera); Gdx.input.setInputProcessor(inputService); gameStateManager = new GameStateManager(this); } @Override public void resize(int i, int i2) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void render() { Gdx.gl.glClearColor(1, 1, 1, 1); Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); gameStateManager.update(Gdx.graphics.getDeltaTime()); gameStateManager.draw(); } @Override public void pause() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void resume() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void dispose() { //To change body of implemented methods use File | Settings | File Templates. } public SpriteBatch getSpriteBatch() { return spriteBatch; } public OrthographicCamera getCamera() { return camera; } public OrthographicCamera getHudCamera() { return hudCamera; } public ResourceManager getResourceManager(){ return resourceManager; } public InputService getInputService() { return inputService; } }
true
c278f791e94a6d1220600ecb0d256e9e6af35739
Java
moustafatammam/PostAssessment
/presentation/src/main/java/com/projects/android/presentation/viewModel/DeletePostViewModel.java
UTF-8
1,761
2.40625
2
[]
no_license
package com.projects.android.presentation.viewModel; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.projects.android.domain.useCases.impl.DeletePostUseCase; import com.projects.android.presentation.mapper.PresenterMapperImpl; import com.projects.android.presentation.model.PresenterPost; import javax.inject.Inject; import io.reactivex.observers.DisposableCompletableObserver; public class DeletePostViewModel extends ViewModel { private DeletePostUseCase mDeletePostUseCase; private PresenterMapperImpl mPresenterMapperImpl; private MutableLiveData<String> deletePostCompletableLiveData = new MutableLiveData<>(); @Inject public DeletePostViewModel(DeletePostUseCase mDeletePostUseCase, PresenterMapperImpl mPresenterMapperImpl) { this.mDeletePostUseCase = mDeletePostUseCase; this.mPresenterMapperImpl = mPresenterMapperImpl; } public LiveData<String> deletePost(PresenterPost presenterPost){ mDeletePostUseCase.execute(new DeletePostCompletable(), mPresenterMapperImpl.mapFromPresenterModel(presenterPost)); return deletePostCompletableLiveData; } @Override protected void onCleared() { mDeletePostUseCase.dispose(); super.onCleared(); } class DeletePostCompletable extends DisposableCompletableObserver{ @Override public void onComplete() { String deleteToastMsg = "Post was deleted successfully"; deletePostCompletableLiveData.postValue(deleteToastMsg); } @Override public void onError(Throwable e) { Log.e("DeletePostViewModel", e.getMessage()); } } }
true
4c5f1bf43d2b19f318362a882d15429b1fdb2544
Java
me4bruno/OffLike
/src/main/java/org/offlike/server/Controller.java
UTF-8
720
2.046875
2
[]
no_license
package org.offlike.server; import org.joda.time.DateTime; import org.offlike.server.data.Campaign; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.google.common.collect.ImmutableMap; @org.springframework.stereotype.Controller public class Controller { @RequestMapping("/") public ModelAndView hello(){ return new ModelAndView("index", ImmutableMap.<String, Object>of("name", "Test User", "Datum", new DateTime())); } @RequestMapping("/test.json") @ResponseBody public Campaign test(){ Campaign camp = new Campaign(); camp.setTitle("test"); return camp; } }
true
30584b848b2a7bd3f45e63e186fbead651a51eef
Java
kaylau/simple_demo_code
/demo_scan/src/main/java/com/kay/demo/qrcode/utils/LogUtil.java
UTF-8
7,190
2.28125
2
[]
no_license
package com.kay.demo.qrcode.utils; import android.text.TextUtils; import android.util.Log; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class LogUtil { public static final boolean DEBUG = true; /** * 日志输出格式: 时间 +日志内容 时间格式: "yyyy-MM-dd HH:mm:ss" * 文件日志内容输出格式 : 文件名---函数名---输出内容 */ public static void e(String fileName, String funName, String msg) { if (fileIsExist()) { writeLogFromSDCard(fileName, funName, msg); } if (DEBUG) { if (!TextUtils.isEmpty(msg)) { fileName = subStrTAG(fileName); Log.e(fileName, getFunctionName()); Log.e(fileName, "-----pay--" + fileName + "--" + msg); } } } public static void i(String fileName, String funName, String msg) { if (fileIsExist()) { writeLogFromSDCard(fileName, funName, msg); } if (DEBUG) { if (!TextUtils.isEmpty(msg)) { fileName = subStrTAG(fileName); Log.i(fileName, getFunctionName()); Log.i(fileName, "-----pay--" + fileName + "--" + msg); } } } /** * 日志输出格式: 时间 +日志内容 时间格式: "yyyy-MM-dd HH:mm:ss" * 文件日志内容输出格式 : 文件名---函数名---输出内容 */ public static void e2cp(String fileName, String funName, String msg) { if (fileIsExist()) { writeLogFromSDCard("", "", msg); } fileName = subStrTAG(fileName); Log.e(fileName, getFunctionName()); Log.e(fileName, "-----pay--" + fileName + "--" + msg); } public static void d(String tag, String msg) { if (fileIsExist()) { writeLogFromSDCard(tag, "", msg); } if (DEBUG) { if (!TextUtils.isEmpty(msg)) { tag = subStrTAG(tag); Log.d(tag, getFunctionName()); Log.d(tag, "-----pay--" + tag + "--" + msg); } } } /** * 输出到控制台 * * @param msg */ public static void e(String tag, String msg) { if (fileIsExist()) { writeLogFromSDCard(tag, "", msg); } if (DEBUG) { if (!TextUtils.isEmpty(msg)) { tag = subStrTAG(tag); Log.e(tag, getFunctionName()); Log.e(tag, "-----pay--" + tag + "--" + msg); } } } public static void i(String tag, String msg) { if (fileIsExist()) { writeLogFromSDCard("", "", msg); } if (DEBUG) { if (!TextUtils.isEmpty(msg)) { tag = subStrTAG(tag); Log.i(tag, getFunctionName()); Log.i(tag, "-----pay--" + tag + "--" + msg); } } } /** * 判断outdebug文件是否存在 **/ private static boolean fileIsExist() { String sDStateString = android.os.Environment.getExternalStorageState(); if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) { try { File SDFile = android.os.Environment.getExternalStorageDirectory(); File logDir = new File(SDFile.getAbsolutePath() + File.separator + Config.PLATFORMID_FOLDER); File logFlagFile = new File(SDFile.getAbsolutePath() + File.separator + Config.PLATFORMID_FOLDER + File.separator + "outdebug"); File logFile = new File(SDFile.getAbsolutePath() + File.separator + Config.PLATFORMID_FOLDER + File.separator + "outdebuginfo.log"); if (!logDir.exists()) { logDir.mkdir(); return false; } if (!logFlagFile.exists()) { if (logFile.exists()) { logFile.delete(); } return false; } } catch (Exception e) { return false; } } return true; } /** * Log info 写入SD卡 */ private static void writeLogFromSDCard(String fileName, String funName, String msg) { String sDStateString = android.os.Environment.getExternalStorageState(); String date_msg; if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) { try { File SDFile = android.os.Environment.getExternalStorageDirectory(); File myDir = new File(SDFile.getAbsolutePath() + File.separator + Config.PLATFORMID_FOLDER); File myFile = new File(SDFile.getAbsolutePath() + File.separator + Config.PLATFORMID_FOLDER + File.separator + "outdebuginfo.log"); if (!myDir.exists()) { myDir.mkdir(); myFile.createNewFile(); } else if (!myFile.exists()) { myFile.createNewFile(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); Date date = new Date(); String dateString = sdf.format(date); if (TextUtils.isEmpty(msg)) { date_msg = dateString + "(" + date.getTime() + ")" + " " + fileName + "---" + funName + "\r\n"; } else { date_msg = dateString + "(" + date.getTime() + ")" + " " + fileName + "---" + funName + "---" + msg + "\r\n"; } BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(myFile, true))); outputStream.write(date_msg); outputStream.close(); } catch (Exception e) { } } } private static String getFunctionName() { StackTraceElement[] sts = Thread.currentThread().getStackTrace(); if (sts != null) { for (StackTraceElement st : sts) { if (st.isNativeMethod()) { continue; } if (st.getClassName().equals(Thread.class.getName())) { continue; } if (st.getClassName().equals(LogUtil.class.getName())) { continue; } // return "[ Thread:" + Thread.currentThread().getName() + ", at " + st.getClassName() + "." + st.getMethodName() // + "(" + st.getFileName() + ":" + st.getLineNumber() + ")" + " ]"; return "[" + st.getMethodName() + "(" + st.getFileName() + ":" + st.getLineNumber() + ")" + "]"; } } return null; } private static String subStrTAG(String tag) { if (TextUtils.isEmpty(tag)) { tag = "LogTAG"; } if (tag.length() >= 23) { tag = tag.substring(0, 20); } return tag; } }
true
e22372ca184c6519dc4b5066469ed69ba6954e03
Java
cy576013581/swallow
/src/main/java/com/cy/example/entity/system/SysMenuEntity.java
UTF-8
405
1.804688
2
[]
no_license
package com.cy.example.entity.system; import com.baomidou.mybatisplus.annotations.TableName; import com.cy.example.entity.SuperEntity; import lombok.Data; import java.io.Serializable; @TableName("sys_menu") @Data public class SysMenuEntity extends SuperEntity<SysMenuEntity> implements Serializable{ private String c_url; private String c_menuName; private String c_node; }
true
dbdc12c8d216fcf9edda807f2779f1aac5d5052f
Java
mario1980miranda/testes-unitarios
/src/test/java/br/ce/wcaquino/builders/LocacaoBuilder.java
UTF-8
1,462
2.546875
3
[]
no_license
package br.ce.wcaquino.builders; import static br.ce.wcaquino.builders.FilmeBuilder.umFilme; import static br.ce.wcaquino.builders.UsuarioBuilder.umUsuario; import java.util.Arrays; import java.util.Date; import br.ce.wcaquino.entidades.Locacao; import br.ce.wcaquino.entidades.Usuario; import br.ce.wcaquino.utils.DataUtils; public class LocacaoBuilder { private Locacao locacao; private LocacaoBuilder(){} public static LocacaoBuilder umaLocacao() { LocacaoBuilder builder = new LocacaoBuilder(); inicializaLocacaoPadrao(builder); return builder; } private static void inicializaLocacaoPadrao(LocacaoBuilder builder) { builder.locacao = new Locacao(); builder.locacao.setUsuario(umUsuario().agora()); builder.locacao.setFilmes(Arrays.asList(umFilme().agora())); builder.locacao.setDataLocacao(new Date()); builder.locacao.setDataRetorno(DataUtils.obterDataComDiferencaDias(1)); builder.locacao.setValor(4.0); } public LocacaoBuilder comDataRetorno(Date data) { locacao.setDataRetorno(data); return this; } public LocacaoBuilder comUsuario(Usuario usuario) { locacao.setUsuario(usuario); return this; } public LocacaoBuilder comDataEntregaAtrasada() { locacao.setDataLocacao(DataUtils.obterDataComDiferencaDias(-4)); locacao.setDataRetorno(DataUtils.obterDataComDiferencaDias(-2)); return this; } public Locacao agora() { return locacao; } }
true
a6e90b000dd816fb0ac9eb5a2c96fdd895c6f4ba
Java
ACS106129/sort-sort-sort
/src/sort/InsertionSort.java
UTF-8
1,663
3.28125
3
[ "MIT" ]
permissive
package sort; import sort.base.*; public class InsertionSort extends SortSystem { public <T extends Number> T[] numberSort(T[] arr, String order) throws RuntimeException { if (order == SortOrder.Ascending || order == SortOrder.Descending) { store(arr); for (int i = 1; i < arr.length; i++) { T key = arr[i]; int j = i - 1; while (j >= 0 && (order == SortOrder.Ascending ? numberCompare(arr[j], key) > 0 : numberCompare(arr[j], key) < 0)) { arr[j + 1] = arr[j]; j--; arr[j + 1] = key; store(arr, j + 1, j + 2); } } return arr; } return null; } @Override public String[] stringSort(String[] arr, String order, boolean isCaseSensitive) throws RuntimeException { if (order == SortOrder.Ascending || order == SortOrder.Descending) { store(arr); for (int i = 1; i < arr.length; i++) { String key = arr[i]; int j = i - 1; while (j >= 0 && (order == SortOrder.Ascending ? stringCompare(arr[j], key, isCaseSensitive) > 0 : stringCompare(arr[j], key, isCaseSensitive) < 0)) { arr[j + 1] = arr[j]; j--; arr[j + 1] = key; store(arr, j + 1, j + 2); } } return arr; } return null; } @Override public String getSortType() { return SortType.Insertion; } }
true
09ad678095471160f2cbc8bb27b485819304212f
Java
alecindro/cuidebemapp
/src/main/java/br/com/cuidebemapp/model/Schedulemail.java
UTF-8
3,774
2.0625
2
[]
no_license
/* * 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 br.com.cuidebemapp.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author alecindro */ @Entity @Table(name = "schedulemail") @XmlRootElement public class Schedulemail implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idschedulemail") private Long idschedulemail; @Basic(optional = false) @Column(name = "diasemana") private String diasemana; @Basic(optional = false) @Column(name = "hora") private String hora; @Basic(optional = false) @Column(name = "enabled") private boolean enabled; @JoinColumn(name = "idpaciente", referencedColumnName = "idpaciente") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Paciente paciente; @JoinColumn(name = "idresponsavel", referencedColumnName = "idresponsavel") @ManyToOne(optional = false, fetch = FetchType.LAZY) private Responsavel responsavel; public Schedulemail() { } public Schedulemail(Long idschedulemail) { this.idschedulemail = idschedulemail; } public Schedulemail(Long idschedulemail, String diasemana, String hora, boolean enabled) { this.idschedulemail = idschedulemail; this.diasemana = diasemana; this.hora = hora; this.enabled = enabled; } public Long getIdschedulemail() { return idschedulemail; } public void setIdschedulemail(Long idschedulemail) { this.idschedulemail = idschedulemail; } public String getDiasemana() { return diasemana; } public void setDiasemana(String diasemana) { this.diasemana = diasemana; } public String getHora() { return hora; } public void setHora(String hora) { this.hora = hora; } public boolean getEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Paciente getPaciente() { return paciente; } public void setPaciente(Paciente paciente) { this.paciente = paciente; } public Responsavel getResponsavel() { return responsavel; } public void setResponsavel(Responsavel responsavel) { this.responsavel = responsavel; } @Override public int hashCode() { int hash = 0; hash += (idschedulemail != null ? idschedulemail.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Schedulemail)) { return false; } Schedulemail other = (Schedulemail) object; if ((this.idschedulemail == null && other.idschedulemail != null) || (this.idschedulemail != null && !this.idschedulemail.equals(other.idschedulemail))) { return false; } return true; } @Override public String toString() { return "br.com.cuidebemapp.model.Schedulemail[ idschedulemail=" + idschedulemail + " ]"; } }
true
695d886b9fd9ff550e7b83f3d52cf9632b6acf3c
Java
starichat/onlinexam
/dao/src/main/java/com/starichat/onlineexam/dao/OptionsMapper.java
UTF-8
448
1.75
2
[]
no_license
package com.starichat.onlineexam.dao; import com.starichat.onlineexam.pojo.Options; public interface OptionsMapper { int deleteByPrimaryKey(Integer optionsId); int insert(Options record); int insertSelective(Options record); Options selectByPrimaryKey(Integer optionsId); int updateByPrimaryKeySelective(Options record); int updateByPrimaryKeyWithBLOBs(Options record); int updateByPrimaryKey(Options record); }
true
134f99298e4f41c7555e169a7e5c72d440ca8ee8
Java
coneseo/twelvebooks
/src/main/java/com/twelvebooks/twelvebook/dto/SearchResultDTO.java
UTF-8
292
1.539063
2
[]
no_license
package com.twelvebooks.twelvebook.dto; import lombok.Getter; import lombok.Setter; import java.util.List; import java.util.Map; @Getter @Setter public class SearchResultDTO { private List<SearchBookDTO> documents; // private MetaDTO meta; private Map<String, Object> meta; }
true
94524cbe78b18dc0bb3f29c5aa659ebd26a3f2c5
Java
TanjaStanic/BSEP_XML
/MegaTravel/src/main/java/project/besp/MegaTravel/repository/AuthRepository.java
UTF-8
380
1.96875
2
[]
no_license
package project.besp.MegaTravel.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import project.besp.MegaTravel.model.Authority; @Repository public interface AuthRepository extends JpaRepository<Authority,Long> { Authority findOneById(Long id); Authority findOneByName(String name); }
true
83e71c7038c85b8f8b4f082cfea2bb5148f4d15d
Java
SDIBTACM/OnlineJudgeBackend
/src/main/java/cn/edu/sdtbu/cache/RedisCacheStoreImpl.java
UTF-8
2,627
2.296875
2
[]
no_license
package cn.edu.sdtbu.cache; import cn.edu.sdtbu.manager.RedisManager; import cn.edu.sdtbu.model.enums.CacheStoreType; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Pageable; import org.springframework.lang.NonNull; import org.springframework.stereotype.Service; import redis.clients.jedis.Tuple; import javax.annotation.Resource; import javax.validation.constraints.NotNull; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author bestsort * @version 1.0 * @date 2020-04-22 15:56 */ @Slf4j @Service public class RedisCacheStoreImpl extends AbstractCacheStore<String, String> implements CacheStore<String, String> { @Resource RedisManager manager; @Override public Optional<String> getInternal(String key) { return Optional.ofNullable(manager.get(key)); } @Override public void sortedListAdd(String listName, Map<String, Double> scoreValMap) { manager.sortedListAdd(listName, scoreValMap); } @Override public void sortedListAdd(String listName, String value, double score) { manager.sortedListAdd(listName, value, score); } @Override public Set<Tuple> fetchRanksByPage(String listName, Pageable pageable, boolean less) { return manager.fetchRanksByPage(listName, pageable, less); } @Override public void putInternal(@NotNull String key, @NotNull String value, long timeout, @NotNull TimeUnit timeUnit) { manager.put(key, value, timeout, timeUnit); } @Override public void inc(@NonNull String key, int stepLength) { log.debug("inc : [ {} ],step is {}", key, stepLength); manager.inc(key, stepLength); } @Override public Long totalElementOfList(String key) { return manager.totalElementOfList(key); } @Override public CacheStoreType getCacheType() { return CacheStoreType.REDIS; } @Override public void delete(String key) { manager.delete(key); } @Override public void delete(Collection<String> collection) { for (String s : collection) { delete(s); } } @Override public Map<String, String> fetchAll(String prefix) { return manager.fetchAll(prefix); } @Override public Long ttl(String key) { return manager.ttl(key); } @Override public Long zRank(String key, String member, boolean less) { return manager.zRank(key, member, less); } @Override public void clearCachePool() { } }
true
28f5e1ee7e3c927c44f40a9c2f8545d5c307a626
Java
IdoFree/java-wx-tools
/weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceBind.java
UTF-8
725
1.921875
2
[ "Apache-2.0" ]
permissive
package me.chanjar.weixin.mp.bean.device; import com.google.gson.annotations.SerializedName; /** * Created by keungtung on 10/12/2016. */ public class WxDeviceBind extends AbstractDeviceBean { private String ticket; @SerializedName("device_id") private String deviceId; @SerializedName("openid") private String openId; public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } }
true
18774a85692a260a4e87134645e5837be293bb79
Java
zhangchenxu110/lite-spring
/src/main/java/com.litespring/bean/factory/support/BeanDefinitionValueResolver.java
UTF-8
3,796
2.671875
3
[]
no_license
package com.litespring.bean.factory.support; import com.litespring.bean.BeanDefinition; import com.litespring.bean.BeansException; import com.litespring.bean.factory.BeanCreationException; import com.litespring.bean.factory.FactoryBean; import com.litespring.bean.factory.config.RuntimeBeanReference; import com.litespring.bean.factory.config.TypedStringValue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author 张晨旭 * @DATE 2018/8/27 */ public class BeanDefinitionValueResolver { protected final Log logger = LogFactory.getLog(getClass()); //依赖BeanFactory private final AbstractBeanFactory beanFactory; public BeanDefinitionValueResolver(AbstractBeanFactory beanFactory) { this.beanFactory = beanFactory; } /** * 当传入的对象是RuntimeBeanReference 就要通过BeanID转换成实例。 * * @param value * @return */ public Object resolveValueIfNecessary(Object value) { //第2个参数 // <aop:pointcut id="placeOrder" expression="execution(* org.litespring.service.v5.*.placeOrder(..))" /> // placeOrder是由上面注入到BeanDefinition中 这里通过beanID获取AspectJExpressionPoint实例的。 if (value instanceof RuntimeBeanReference) { RuntimeBeanReference ref = (RuntimeBeanReference) value; String beanID = ref.getBeanId(); Object bean = this.beanFactory.getBean(beanID); return bean; } else if (value instanceof TypedStringValue) { return ((TypedStringValue) value).getValue(); } else if (value instanceof BeanDefinition) { // 如果这个要注入的属性是BeanDefinition类型 // (也就是AOP时 将通知类的方法(MethodLocatingFactory --getObject-- Advice) 切面(AspectJExpressionPoint) 通知类(通知类 普通BD) // 这三个抽象成了BeanDefinition(准确说是1 3),需要获取这些BeanDefinition这种属性实例 BeanDefinition bd = (BeanDefinition) value; String innerBeanName = "(inner bean)" + bd.getBeanClassName() + "#" + Integer.toHexString(System.identityHashCode(bd)); return resolveInnerBean(innerBeanName, bd); } else { throw new RuntimeException("the value " + value + " has not implemented"); } } private Object resolveInnerBean(String innerBeanName, BeanDefinition innerBd) { try { //获取通知类方法和通知类 这两种BeanDefinition的实例(获取一个bean的实例 会先调用构造方法设置属性 再populateBean设置属性) Object innerBean = this.beanFactory.createBean(innerBd); //对于通知方法(第一个参数) 也就是MethodLocatingFactory(实现了BeanFactoryAware和FactoryBean(获取方法)) // 可以Method if (innerBean instanceof FactoryBean) { try { return ((FactoryBean<?>) innerBean).getObject(); } catch (Exception e) { throw new BeanCreationException(innerBeanName, "FactoryBean threw exception on object creation", e); } } else {//对于通知类 也就是AspectInstanceFactory (实现了BeanFactoryAware(设置BeanFactory)) return innerBean; } } catch (BeansException ex) { throw new BeanCreationException( innerBeanName, "Cannot create inner bean '" + innerBeanName + "' " + (innerBd != null && innerBd.getBeanClassName() != null ? "of type [" + innerBd.getBeanClassName() + "] " : "") , ex); } } }
true
50accff4713f2283da13a741e580f1cfec986398
Java
DeveloperZJQ/scalavsjava
/src/main/java/designpatterns/flyweight/demo1/ConcreteFlyweight.java
UTF-8
607
3.46875
3
[ "Apache-2.0" ]
permissive
package designpatterns.flyweight.demo1; /** * 具体实现享元类 * * @author happy * @since 2021-05-08 */ public class ConcreteFlyweight implements Flyweight { private final String key; public ConcreteFlyweight(String key) { this.key = key; System.out.println("具体享元" + key + "被创建!"); } @Override public void operation(UnsharedConcreteFlyweight unsharedConcreteFlyweight) { System.out.println("具体享元" + key + "被调用!"); System.out.println("非享元" + unsharedConcreteFlyweight.getInfo() + "被调用!"); } }
true
4aaa563f633df1fa0d08cd142f4640e64b34c291
Java
AndreiBorac/Learner2g
/057-parts/export/java/zs42/parts/ConvenientUI.java
UTF-8
2,671
2.9375
3
[ "BSD-2-Clause" ]
permissive
/*** * ConvenientUI.java * copyright (c) 2012 by andrei borac ***/ package zs42.parts; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ConvenientUI { public static void launchTextField(final String title, final F1<Void, String> action) { try { SwingUtilities.invokeAndWait ((new Runnable() { public void run() { final JTextField textfield = (new JTextField()); final JFrame frame = (new JFrame(title)); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.getContentPane().add(textfield); frame.setSize(500, 50); frame.setVisible(true); textfield.addKeyListener ((new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { String text = textfield.getText(); action.invoke(text); textfield.setText(""); } } })); } })); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw (new RuntimeException(e)); } } public static JTextArea launchScrollingTextArea(final String title) { final JTextArea[] textarea_shadow = (new JTextArea[1]); try { SwingUtilities.invokeAndWait ((new Runnable() { public void run() { final JTextArea textarea = (new JTextArea()); textarea.setEditable(false); textarea.setFont((new Font(Font.MONOSPACED, Font.BOLD, 14))); final JScrollPane scrollpane = (new JScrollPane(textarea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)); scrollpane.setViewportBorder((new javax.swing.border.LineBorder(Color.WHITE, 5))); final JFrame frame = (new JFrame(title)); frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE); frame.getContentPane().add(scrollpane); frame.setSize(800, 600); frame.setVisible(true); textarea_shadow[0] = textarea; } })); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw (new RuntimeException(e)); } return textarea_shadow[0]; } }
true
bf8d5949c28d0aa39b120e5229e83a7bdcbebf73
Java
icterguru/DevelopingProgrammingLanguages
/src/limp/Parser.java
UTF-8
22,544
2.8125
3
[]
no_license
/* * 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 limp; /** * // http://en.cppreference.com/w/cpp/language/operator_precedence * @author seyuu_000 */ public class Parser extends Types { Lexer lexer; Lexeme current; public Parser(String filename) { lexer = new Lexer(filename); current = null; } public boolean check(String type) { return type.equals(current.type); } public Lexeme advance() { Lexeme old = current; current = lexer.lex(); return old; } public Lexeme match(String type) { if (check(type)) { return advance(); } System.out.println("Parse error: looking for " + type + " found " + "\"" + current.type + "\"" + " insead."); System.out.println("\t Error on line number: " + Integer.toString(current.lineError)); System.exit(0); return null; } public Lexeme parse() { Lexeme tree; advance(); tree = program(); match(ENDofFILE); return tree; } /* Program * * * */ public Lexeme program() { Lexeme tree = new Lexeme(LIST); optNewline(); tree.left = globalDefineList(); Lexeme tmp = new Lexeme(LIST); tmp.left = funcCallStart(); optNewline(); tree.right = tmp; return tree; } public Lexeme globalDefine() { Lexeme tree; if (defineVariablePending()) { tree = defineVariable(); } else if (defineObjectPending()) { tree = defineObject(); } else { tree = defineFunction(); } return tree; } public Lexeme globalDefineList() { Lexeme tree = new Lexeme(LIST); tree.left = globalDefine(); // // // newline(); if (globalDefinePending()) { tree.right = globalDefineList(); } return tree; } public Lexeme newline() { match(NEWLINE); if (newlinePending()) { newline(); } return null; } public Lexeme optNewline() { if (newlinePending()) { newline(); } return null; } /* Primary * * * */ public Lexeme primary() { Lexeme tree; if (literalPending()) { tree = literal(); } else if (varExpressionPending()) { tree = varExpression(); } else if (powStatementPending()) { tree = powStatement(); } else if (getChrStatementPending()) { tree = getChrStatement(); } else if (strimStatementPending()) { tree = strimStatement(); } else if (toIntStatementPending()) { tree = toIntStatement(); } else if (toStringStatementPending()) { tree = toStringStatement(); } else if (isDigitStatementPending()) { tree = isDigitStatement(); } else if (lengthStatementPending()) { tree = lengthStatement(); } else if (check(OPAREN)) { tree = match(OPAREN); tree.left = null; tree.right = expression(); match(CPAREN); } else if (check(MINUS)){ // unary minus and plus tree = match(MINUS); tree.type = UMINUS; tree.left = null; tree.right = primary(); } else { //if (check (PLUS)){ // unary minus and plus tree = match(PLUS); tree.type = UPLUS; tree.left = null; tree.right = primary(); } return tree; } public Lexeme literal() { Lexeme tree; tree = advance(); return tree; // // must be a literal pending or we would not have gotten here // use advance instead of match since we don't know exactly // which literal is pending } /* Lists * * * */ public Lexeme paramList() { Lexeme tree = new Lexeme(LIST); tree.left = match(VARIABLE); if (check(COMMA)) { match(COMMA); if (paramListPending()) { tree.right = paramList(); } } return tree; } public Lexeme optParamList() { Lexeme tree = null; if (paramListPending()) { tree = paramList(); } return tree; } public Lexeme expressionList() { Lexeme tree = new Lexeme(LIST); tree.left = expression(); if (check(COMMA)) { match(COMMA); if (expressionListPending()) { tree.right = expressionList(); } } return tree; } public Lexeme optExpressionList() { Lexeme tree = null; if (expressionListPending()) { tree = expressionList(); } return tree; } /* Variables * * * */ public Lexeme varExpression() { Lexeme tree; tree = match(VARIABLE); if (check(OPAREN)) { Lexeme tmp = funcCall(); tmp.left = tree; tree = tmp; } return tree; } public Lexeme defineStatement() { Lexeme tree; if (defineVariablePending()) { tree = defineVariable(); } else { tree = defineFunction(); } return tree; } public Lexeme defineVariable() { Lexeme tree = new Lexeme(VAR_DEF); match(LOCAL); tree.left = match(VARIABLE); match(ASSIGN); tree.right = expression(); return tree; } public Lexeme defineVariableList() { Lexeme tree = new Lexeme(LIST); tree.left = defineVariable(); newline(); if (defineVariablePending()) { tree.right = defineVariableList(); } return tree; } /* Operators * * * */ public Lexeme operator() { Lexeme tree; tree = advance(); return tree; } /* Expressions * * * */ //public Lexeme expression() { // Lexeme tree; // tree = expression1(); // while (operatorCommaPending()) { // Lexeme tmp = operator(); // tmp.left = tree; // tmp.right = expression(); // tree = tmp; // } // return tree; //} public Lexeme expression() { Lexeme tree; tree = expression1(); if (operatorAssignmentPending()){ // = Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression(); tree = tmp; } return tree; } public Lexeme expression1() { Lexeme tree; tree = expression2(); while (operatorLogicalOrPending()){ // || Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression1(); tree = tmp; } return tree; } public Lexeme expression2() { Lexeme tree; tree = expression3(); while (operatorLogicalAndPending()){ // && Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression2(); tree = tmp; } return tree; } public Lexeme expression3() { Lexeme tree; tree = expression4(); while (operatorEqualityPending()){ // == Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression3(); tree = tmp; } return tree; } public Lexeme expression4() { Lexeme tree; tree = expression5(); while (operatorRelationalPending()){ // >, >=, <, <=, != Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression4(); tree = tmp; } return tree; } public Lexeme expression5() { Lexeme tree; tree = expression6(); while (operatorAdditivePending()){ // binary + or - Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression5(); tree = tmp; } return tree; } public Lexeme expression6() { Lexeme tree; tree = expression7(); while (operatorMultiplicativePending()){ // * and / Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression6(); tree = tmp; } return tree; } public Lexeme expression7() { Lexeme tree; tree = expression8(); if (operatorUnaryPending()){ // unary + or - Lexeme tmp = operator(); tmp.left = tree; tmp.right = expression7(); tree = tmp; } return tree; } public Lexeme expression8() { Lexeme tree; tree = primary(); while (operatorPrimaryPending()){ // checks for . Lexeme tmp = operator(); tmp.left = tree; tmp.right = primary(); tree = tmp; } return tree; } /* Statements * * * */ public Lexeme block() { Lexeme tree; newline(); tree = statementList(); return tree; } public Lexeme statement() { // ************* Lexeme tree = null; //if (varExpressionPending()) { // tree = varExpression(); if (expressionPending()) { tree = expression(); } else if (ifStatementPending()) { tree = ifStatement(); } else if (iterStatementPending()) { tree = loopStatement(); } else if (definitionPending()){ tree = defineStatement(); } else if (flowStatementPending()) { tree = flowStatement(); } else if (printStatementPending()) { tree = printStatement(); } return tree; } public Lexeme statementList() { // ************* Lexeme tree = new Lexeme(LIST); tree.left = statement(); newline(); if (statementPending()) { tree.right = statementList(); } // // right side of tree will be null // return tree; } public Lexeme flowStatement() { Lexeme tree; if (returnStatementPending()) { tree = match(RETURN); tree.right = expression(); } else { tree = advance(); } return tree; } public Lexeme printStatement() { Lexeme tree; tree = match(PRINT); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } public Lexeme powStatement() { Lexeme tree; tree = match(POWER); match(OPAREN); tree.left = expression(); match(COMMA); tree.right = expression(); match(CPAREN); return tree; } public Lexeme getChrStatement() { Lexeme tree; tree = match(GETCHR); match(OPAREN); tree.left = expression(); match(COMMA); tree.right = expression(); match(CPAREN); return tree; } public Lexeme strimStatement() { Lexeme tree; tree = match(STRIM); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } public Lexeme toIntStatement() { Lexeme tree; tree = match(TOINT); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } public Lexeme toStringStatement() { Lexeme tree; tree = match(TOSTRING); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } public Lexeme isDigitStatement() { Lexeme tree; tree = match(ISDIGIT); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } public Lexeme lengthStatement() { Lexeme tree; tree = match(LENGTH); match(OPAREN); tree.right = expression(); match(CPAREN); return tree; } /* Conditionals * * * */ public Lexeme ifStatement() { Lexeme tree; tree = match(IF); match(OPAREN); tree.left = expression(); match(CPAREN); Lexeme block = new Lexeme(BLOCK); block.left = block(); if (elseStatementPending()) { match(ELSE); if (ifStatementPending()) { block.right = ifStatement(); newline(); } else { Lexeme block2 = new Lexeme(BLOCK); block2.left = block(); block.right = block2; } } tree.right = block; match(END); return tree; } /* Iteration * * * */ public Lexeme loopStatement() { Lexeme tree; if (whileStatementPending()) { tree = whileStatement(); } else { tree = repeatStatement(); } return tree; } public Lexeme whileStatement() { Lexeme tree; tree = match(WHILE); match(OPAREN); tree.left = expression(); match(CPAREN); Lexeme block = new Lexeme(BLOCK); block.left = block(); tree.right = block; match(END); return tree; } public Lexeme repeatStatement() { Lexeme tree; tree = match(REPEAT); match(OPAREN); tree.left = expression(); match(CPAREN); Lexeme block = new Lexeme(BLOCK); block.left = block(); tree.right = block; match(END); return tree; } /* Functions * * * */ public Lexeme defineFunction() { Lexeme tree = new Lexeme(FUNC_DEF); match(FUNCTION); tree.left = match(VARIABLE); match(OPAREN); Lexeme tmp1 = new Lexeme(LIST); Lexeme tmp2 = new Lexeme(BLOCK); tmp1.left = optParamList(); match(CPAREN); tmp2.left = block(); tmp1.right = tmp2; tree.right = tmp1; match(END); return tree; } public Lexeme defineFunctionList() { Lexeme tree = new Lexeme(LIST); tree.left = defineFunction(); newline(); if (check(FUNCTION)) { tree.right = defineFunctionList(); } return tree; } public Lexeme funcCall() { Lexeme tree = new Lexeme(FUNC_CALL); // // Needs to be fixed, the final call to a function requires a variable // name but is not given in this function as the function varExpression // takes care of that instead. // match(OPAREN); tree.right = optExpressionList(); match(CPAREN); return tree; } public Lexeme funcCallStart() { Lexeme tree = new Lexeme(FUNC_CALL); tree.left = match(VARIABLE); match(OPAREN); tree.right = optExpressionList(); match(CPAREN); return tree; } /* Objects * * * */ public Lexeme defineObject() { Lexeme tree = new Lexeme(FUNC_DEF); match(OBJECT); tree.left = match(VARIABLE); match(OPAREN); Lexeme tmp1 = new Lexeme(LIST); tmp1.left = optParamList(); match(CPAREN); Lexeme tmp2 = new Lexeme(BLOCK); // // need a newline, because not a block // newline(); // // object fields (optional) if (defineVariablePending()) { tmp2.left = defineVariableList(); } Lexeme tmp3 = new Lexeme(BLOCK); // // object methods (mandatory) tmp3.left = defineFunctionList(); // // // Lexeme tmp4 = new Lexeme(LIST); tmp4.left = match(THIS); tmp1.right = tmp2; tmp2.right = tmp3; tmp3.right = tmp4; tree.right = tmp1; // // // newline(); match(END); return tree; } public Lexeme defineObjectList() { Lexeme tree = new Lexeme(LIST); tree.left = defineObject(); newline(); if (defineObjectPending()) { tree.right = defineObjectList(); } return tree; } // pending functions public boolean globalDefinePending() { return check(LOCAL) || check(FUNCTION) || check(OBJECT); } public boolean newlinePending() { return check(NEWLINE); } public boolean operatorPending() { return check(PLUS) || check(MINUS) || check(UMINUS) || check(TIMES) || check(DIVIDES) || check(MODULUS) || check(EQ) || check(NEQ) || check(GT) || check(LT) || check(GE) || check(LE) || check(ASSIGN) || check(AND) || check(OR) || check(NOT) || check(DOT); } public boolean literalPending() { return check(INTEGER) || check(STRING) || check(NULL); } public boolean primaryPending() { return literalPending() || varExpressionPending() || getChrStatementPending() || strimStatementPending() || toIntStatementPending() || toStringStatementPending() || isDigitStatementPending() || lengthStatementPending() || powStatementPending() || check(OPAREN) || check(MINUS); } public boolean expressionPending() { return primaryPending(); } public boolean statementPending() { return varExpressionPending() || ifStatementPending() || iterStatementPending() || definitionPending() || flowStatementPending() || printStatementPending(); } public boolean statementListPending() { return statementPending(); } public boolean ifStatementPending() { return check(IF); } public boolean iterStatementPending() { return check(WHILE) || check(REPEAT); } public boolean whileStatementPending() { return check(WHILE); } public boolean definitionPending() { return check(LOCAL) || check(FUNCTION); } // // Object // public boolean defineObjectPending() { return check(OBJECT); } public boolean defineVariablePending() { return check(LOCAL); } public boolean varExpressionPending() { return check(VARIABLE); } public boolean paramListPending() { return check(VARIABLE); } public boolean defineFunctionPending() { return check(FUNCTION); } public boolean expressionListPending() { return expressionPending(); } public boolean funcCallPending() { return check(OPAREN); } public boolean returnStatementPending() { return check(RETURN); } public boolean operatorPrimaryPending() { return check(DOT); // // Parenthesis operators cause an error when added here // if (a) -> causes an error } public boolean operatorUnaryPending() { return check(UMINUS) || check(UPLUS); } public boolean operatorMultiplicativePending() { return check(TIMES) || check(DIVIDES) || check(MODULUS); } public boolean operatorAdditivePending() { return check(PLUS) || check(MINUS); } public boolean operatorRelationalPending() { return check(LT) || check(GT) || check(LE) || check(GE); } public boolean operatorEqualityPending() { return check(EQ) || check(NEQ); } public boolean operatorLogicalAndPending() { return check(AND); } public boolean operatorLogicalOrPending() { return check(OR); } public boolean operatorAssignmentPending() { return check(ASSIGN); } public boolean flowStatementPending() { return check(PASS) || check(BREAK) || check(RETURN); } public boolean printStatementPending() { return check(PRINT); } public boolean getChrStatementPending() { return check(GETCHR); } public boolean strimStatementPending() { return check(STRIM); } public boolean toIntStatementPending() { return check(TOINT); } public boolean toStringStatementPending() { return check(TOSTRING); } public boolean isDigitStatementPending() { return check(ISDIGIT); } public boolean lengthStatementPending() { return check(LENGTH); } public boolean powStatementPending() { return check(POWER); } public boolean elseStatementPending() { return check(ELSE); } }
true
75126c5f4b98e01d28bc1735cc3715512006ff0d
Java
Vignesh-24/Training
/NetCart/src/main/java/com/model/Customer.java
UTF-8
1,856
2.3125
2
[]
no_license
package com.model; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int customerno; private String customername; private String customeraddress; private String customeremail; private String customerphone; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "uid", referencedColumnName = "uid") private Users user; public int getCustomerno() { return customerno; } public void setCustomerno(int customerno) { this.customerno = customerno; } public String getCustomername() { return customername; } public void setCustomername(String customername) { this.customername = customername; } public String getCustomeraddress() { return customeraddress; } public void setCustomeraddress(String customeraddress) { this.customeraddress = customeraddress; } public String getCustomeremail() { return customeremail; } public void setCustomeremail(String customeremail) { this.customeremail = customeremail; } public String getCustomerphone() { return customerphone; } public void setCustomerphone(String customerphone) { this.customerphone = customerphone; } @Override public String toString() { return "CustomerMasterDTO [customerno=" + customerno + ", customername=" + customername + ", customeraddress=" + customeraddress + ", customeremail=" + customeremail + ", customerphone=" + customerphone + "]"; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } }
true
4e5be4699a087644b73afec2504561de3d11c648
Java
kaakaa/ppt-museum-webapp
/src/main/java/org/kaakaa/pptmuseum/event/db/resource/GetResource.java
UTF-8
939
2.09375
2
[]
no_license
package org.kaakaa.pptmuseum.event.db.resource; import org.kaakaa.pptmuseum.db.ResourceType; import org.kaakaa.pptmuseum.db.document.Resource; import org.kaakaa.pptmuseum.event.Event; import org.kaakaa.pptmuseum.event.EventException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import spark.Request; /** * Created by kaakaa on 16/03/24. */ public class GetResource implements Event<Resource> { private final Request request; private final ResourceType type; Logger logger = LoggerFactory.getLogger(getClass()); public GetResource(Request rq, ResourceType type) { this.request = rq; this.type = type; } @Override public Resource execute() throws EventException { beforeLogging(logger); Resource result = mongoDBClient.getResource(this.request.params(":id"), type); afterLogging(logger); return result; } }
true
c231266eadf19f2f84f9b76d8672087193a60504
Java
AnnabelQA/Javacore
/src/main/java/kitcenter/runners/classwork/lesson10/StringToPrimitiveAndBack.java
UTF-8
531
3.109375
3
[]
no_license
package kitcenter.runners.classwork.lesson10; /** * Created by annabilous on 5/27/17. */ public class StringToPrimitiveAndBack { public static void main(String[] args) { String integer = "11"; Integer resultInt = Integer.valueOf(integer); int y = Integer.parseInt(integer); System.out.println("Here is int: " + y); Integer newInt = new Integer(y); String s = String.valueOf(newInt); System.out.println(s); // String integer = String.valueOf(y); } }
true
cc5c1bfc0e2f3506f8e63cb3b0e2d926de4f8ae8
Java
pauljoyce/Scratch
/src/main/java/thread/FutureTest.java
UTF-8
1,397
3.4375
3
[]
no_license
package thread; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * 获取线程执行结果,非阻塞 * @Author: mengchao * @Date: 2020/12/5 22:11 */ public class FutureTest { public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(5); ExecutorService watchService = Executors.newFixedThreadPool(5); List<String> list = Arrays.asList("this", "is", "a", "word"); for (int i = 0; i < 5; i++) { Future<String> future= (Future<String>) service.submit(() -> { list.get(0); }); watchService.submit(()->{ while (!future.isDone()) { System.out.println("waiting..."); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } try { future.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }); } service.shutdown(); watchService.shutdown(); } }
true
6fbba781a0534e32cdf90e0ae9fbebb13d1b0be2
Java
ivovieiraJunior/Programacao-Orientado-Objeto
/ExercicioSementrs3/src/model/Livro.java
UTF-8
1,387
2.546875
3
[]
no_license
package model; public class Livro { private int id_livro; private String titulo; private String autor; private String editora; private int anoLancamento; private String categoria; private int disponivel; public Livro(String titulo2, String editora2, String autor2, String categoria2, int ano) { this.titulo = titulo2; this.editora = editora2; this.autor = autor2; this.categoria = categoria2; this.anoLancamento = ano; this.disponivel = 1; } public Livro() { } public int getId_livro() { return id_livro; } public void setId_livro(int id_livro) { this.id_livro = id_livro; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public String getEditora() { return editora; } public void setEditora(String editora) { this.editora = editora; } public int getAnoLancamento() { return anoLancamento; } public void setAnoLancamento(int anoLancamento) { this.anoLancamento = anoLancamento; } public String getCategoria() { return categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public int getDisponivel() { return disponivel; } public void setDisponivel(int disponivel) { this.disponivel = disponivel; } }
true
e1ef8a0d1cc6b0bcffa2205dd1b3f1a766aa61ea
Java
yujiantong/sz-bip
/bip/src/main/java/com/bofide/bip/service/CustomerTraceRecodeService.java
UTF-8
9,980
1.851563
2
[]
no_license
package com.bofide.bip.service; import java.util.Map; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.bofide.bip.common.po.RoleType; import com.bofide.bip.mapper.CustomerAssignMapper; import com.bofide.bip.mapper.CustomerMapper; import com.bofide.bip.mapper.CustomerTraceRecodeMapper; import com.bofide.bip.mapper.OperationRecordMapper; import com.bofide.bip.mapper.UserMapper; import com.bofide.bip.po.Customer; import com.bofide.bip.po.CustomerAssign; import com.bofide.bip.po.RenewalingCustomer; import com.bofide.bip.po.User; import com.bofide.bip.mapper.RenewalingCustomerMapper; import com.bofide.bip.po.CustomerTraceRecode; import com.bofide.common.util.DealStringUtil; /** *潜客跟踪服务类 * * @author huliangqing * */ @Service(value = "customerTraceRecordService") public class CustomerTraceRecodeService { @Resource(name = "customerTraceRecodeMapper") private CustomerTraceRecodeMapper customerTraceRecodeMapper; @Resource(name = "customerAssignMapper") private CustomerAssignMapper customerAssignMapper; @Resource(name = "renewalingCustomerMapper") private RenewalingCustomerMapper renewalingCustomerMapper; @Resource(name = "operationRecordMapper") private OperationRecordMapper operationRecordMapper; @Resource(name = "userMapper") private UserMapper userMapper; @Resource(name = "customerMapper") private CustomerMapper customerMapper; @Resource(name = "userService") private UserService userService; @Resource(name = "customerService") private CustomerService customerService; /** * 跟踪处理信息插入 * @param customer 跟踪处理信息 * @param userId 用户Id * @param traceFlag 跟踪标志,1 表示跟踪, 2表示跟踪完成 * @param virtualJqxdqr * @throws Exception */ public void insert(CustomerTraceRecode customerTraceRecode,Integer userId,Integer storeId, Integer traceFlag,Integer roleId,Map<String,Object> mapht,Integer applyStatu) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("customerId", customerTraceRecode.getCustomerId()); map.put("userId", userId); CustomerAssign customerAssign = customerAssignMapper.findAssignRecode3(map); //获取相减后天数 int cyts = (int)((new Date().getTime()-customerAssign.getAcceptDate().getTime())/(24*60*60*1000)); customerTraceRecode.setCyts(cyts); if(customerTraceRecode.getInviteDate() != null){ customerTraceRecode.setInvite(1); } RenewalingCustomer renewalingCustomer = renewalingCustomerMapper.findCustomerInfoByCustomerId(customerTraceRecode.getCustomerId()); if(renewalingCustomer != null){ customerTraceRecode.setCurrentNeedTraceDate(renewalingCustomer.getWillingTraceDate()); } int i = customerTraceRecodeMapper.insert(customerTraceRecode); if(i>0){ Map<String,Object> rcMap = new HashMap<>(); Map<String,Object> rcMap2 = new HashMap<>(); rcMap.put("customerId", customerTraceRecode.getCustomerId()); //更新潜客(小池子)应跟踪时间 rcMap.put("willingTraceDate", customerTraceRecode.getNextTraceDate()); //更新潜客表(小池子)的末次跟踪日期 rcMap.put("lastTraceDate", new Date()); //更新潜客表(小池子)的末次跟踪结果 rcMap.put("lastTraceResult", customerTraceRecode.getTraceContext()); //更新潜客表(小池子)的客户级别 rcMap.put("customerLevel", customerTraceRecode.getCustomerLevel()); //更新潜客表(小池子)的邀约日期 rcMap.put("inviteDate", customerTraceRecode.getInviteDate()); if(customerTraceRecode.getPrincipalId()!=null && !"".equals(customerTraceRecode.getPrincipalId()) && customerTraceRecode.getPrincipal()!=null && !"".equals(customerTraceRecode.getPrincipal())){ //更新潜客表(小池子)的负责人Id rcMap.put("principalId", customerTraceRecode.getPrincipalId()); //更新潜客表(小池子)的负责人 rcMap.put("principal", customerTraceRecode.getPrincipal()); } //如果该跟踪记录有接通就统计起来 Integer sfjt = customerTraceRecode.getSfjt(); Customer customer = customerMapper.findCustomerById(customerTraceRecode.getCustomerId()); Integer gotThroughNum = customer.getGotThroughNum(); if(sfjt == null){ sfjt = 0; } gotThroughNum += sfjt; rcMap.put("gotThroughNum", gotThroughNum); rcMap.put("sfgyx", customerTraceRecode.getSfgyx()); renewalingCustomerMapper.updateSelectiveByCustomerId(rcMap); rcMap2.put("gotThroughNum", gotThroughNum); rcMap2.put("customerId", customerTraceRecode.getCustomerId()); rcMap2.put("sfgyx", customerTraceRecode.getSfgyx()); customerMapper.updateCustomerInfo(rcMap2); //更新自己和上级的跟踪状态 String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String nextTraceDate = new SimpleDateFormat("yyyy-MM-dd").format(customerTraceRecode.getNextTraceDate()); if(currentDate.equals(nextTraceDate)){ //跟踪状态为4表示,在跟踪时,录入的下次应跟踪日期为当天 customerAssignMapper.updateTraceStatu(customerTraceRecode.getCustomerId(), userId,4); }else{ customerAssignMapper.updateTraceStatu(customerTraceRecode.getCustomerId(), userId,2); } //更新潜客(大池子)的客户级别 customerMapper.updateCustomerLevel(customerTraceRecode.getCustomerId(), customerTraceRecode.getCustomerLevel()); Map<String,Object> traceMap = new HashMap<>(); traceMap.put("userId", userId); traceMap.put("customerId", customerTraceRecode.getCustomerId()); traceMap.put("operationFlag", 9); //插入一条操作记录表示跟踪过一次 operationRecordMapper.insert(traceMap); if(customerTraceRecode.getInviteDate() != null){ //更新自己的邀约状态 customerAssignMapper.updateAssignInviteStatu( customerTraceRecode.getCustomerId(), userId, customerTraceRecode.getCustomerTraceId()); //更新小池子里面的是否邀约 renewalingCustomerMapper.updateIsInvite(customerTraceRecode.getCustomerId()); } if(traceFlag != null && traceFlag == 2){ CustomerAssign assign = new CustomerAssign(); assign.setCustomerId(customerTraceRecode.getCustomerId()); assign.setUserId(userId); assign.setReturnStatu(1); //续保专员的分配信息 CustomerAssign commissionerAssign = new CustomerAssign(); commissionerAssign.setCustomerId(customerTraceRecode.getCustomerId()); //如果负责人有填写则优先分配该负责人,否则就随机分配 Integer renewalType = customer.getRenewalType(); Integer id = null; User user = null; Integer xbzyRoleId = RoleType.XBZY; if(customer != null){ id = customer.getPrincipalId(); } if(id != null){ //检查这个负责人是否正常状态 boolean isNormal = userService.findCheckUserStatu(id); if(isNormal == true){ commissionerAssign.setUserId(id); }else{ user = userService.findAssignCustomerUser(xbzyRoleId, storeId,renewalType); commissionerAssign.setUserId(user.getId()); } }else{ user = userService.findAssignCustomerUser(xbzyRoleId, storeId,renewalType); commissionerAssign.setUserId(user.getId()); } commissionerAssign.setAssignDate(new Date()); commissionerAssign.setAcceptStatu(1); commissionerAssign.setReturnStatu(1); String operation = "跟踪完成"; User operatorUser = userService.findUserById(userId); String lastTraceResult = DealStringUtil.dealLastTraceResult(operation, operatorUser.getUserName()); customerService.insertNewAssign(assign,commissionerAssign,storeId,operatorUser.getUserName(), lastTraceResult,customer.getPrincipalId(),customer.getPrincipal(),roleId); }else if(traceFlag != null && traceFlag == 3){ Integer customerId = customer.getCustomerId(); String htyyxz = (String)mapht.get("htyyxz"); String userName = (String)mapht.get("userName"); String returnReason = (String)mapht.get("returnReason"); Integer principalId = customer.getPrincipalId(); String principal = customer.getPrincipal(); String operation = ""; if(applyStatu==null){ operation = "申请回退"; }else if(applyStatu==1){ operation = "申请失销"; }else if(applyStatu==2){ operation = "申请睡眠"; } String dealReturnReason = DealStringUtil.dealTraceRecordReason(operation, returnReason, userName); String lastTraceResult = DealStringUtil.dealLastTraceResult(operation, userName); customerService.updateReturnStatu(customerId, userId, null, dealReturnReason, userName, storeId, lastTraceResult, principalId, principal, htyyxz,applyStatu); } } } /** * 根据潜客id查询对应潜客的跟踪记录条数 * @param customerId 跟踪处理信息 * @return * @throws Exception */ public int findTraceCount(Integer customerId) throws Exception { return customerTraceRecodeMapper.findTraceCount(customerId); } /** * 根据潜客id查询潜客失销原因 * @param customerId 潜客id * @return * @throws Exception */ public String findLostReasonByCustomerId(Integer customerId) throws Exception { return customerTraceRecodeMapper.findLostReasonByCustomerId(customerId); } /** * 根据潜客ID和用户ID查询当前跟踪次数 * @param param * @return * @throws Exception */ public List<Map<String, Object>> findGzCount(Map<String, Object> param) throws Exception{ List<Map<String, Object>> lists = customerTraceRecodeMapper.findGzCount(param); return lists; } public CustomerTraceRecode findByCustomerTraceId(Integer customerTraceId) throws Exception{ return customerTraceRecodeMapper.selectByPrimaryKey(customerTraceId); } public int findExistInviteDate(Map<String, Object> param) throws Exception{ return customerTraceRecodeMapper.findRecordByInviteDate(param); } }
true
1f38489fa1d6028bb5aef7e57a2e771db12b2761
Java
mridho/Mangrover
/Mangrover/app/src/main/java/com/example/android/mangrover/app/bluetooth_room.java
UTF-8
12,025
2.03125
2
[ "Apache-2.0" ]
permissive
//Partially Copyrighted to : /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.mangrover.app; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.Set; public class bluetooth_room extends Activity { private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Debugging private static final String TAG = "bluetooth_room"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; //working button Button Back; Button scanButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bluetooth_room); //List of Active Button scanButton = (Button) findViewById(R.id.button_scan); Back = (Button) findViewById(R.id.button_back); createListeners(); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) { findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) { mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); } //Connecting to Device if (getConnectionState() == BluetoothSerialService.STATE_NONE) { // Launch the DeviceListActivity/bluetooth_room to see devices and do scan Intent serverIntent = new Intent(this, bluetooth_room.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } else if (getConnectionState() == BluetoothSerialService.STATE_CONNECTED) { mSerialService.stop(); mSerialService.start(); } } public int getConnectionState() { return mSerialService.getState(); } private static BluetoothSerialService mSerialService = null; @Override protected void onDestroy() { super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) { mBtAdapter.cancelDiscovery(); } // Unregister broadcast listeners this.unregisterReceiver(mReceiver); } /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() { if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); } // Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); } // The on-click listener for all devices in the ListViews private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { String noDevicesPaired = getResources().getText(R.string.none_paired).toString(); String noDevicesFound = getResources().getText(R.string.none_found).toString(); // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); String info = ((TextView) v).getText().toString(); if ( (!info.equals(noDevicesPaired)) && (!info.equals(noDevicesFound)) ){ if (info.length() >= 17) { // Get the device MAC address, which is the last 17 chars in the View String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); } else { setResult(Activity.RESULT_CANCELED); } finish(); } } }; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } } }; //-------------Button's Procedure--------------------------------------------------------------------- //trigger Main Activity private void startMainActivity() { Intent intent = new Intent(this, MyActivity.class); startActivity(intent); } //Prosedur CreateListener() private void createListeners(){ Back.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { startMainActivity(); } }); // Initialize the button to perform device discovery scanButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { doDiscovery(); view.setVisibility(View.GONE); } }); } /** * Set to true to add debugging code and logging. */ public static final boolean DEBUG = true; // Intent request codes private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; /** * The tag we use when logging, so that our messages can be distinguished * from other messages in the log. Public because it's used by several * classes. */ public static final String LOG_TAG = "Mangrover"; public void onActivityResult(int requestCode, int resultCode, Intent data) { if(DEBUG) Log.d(LOG_TAG, "onActivityResult " + resultCode); switch (requestCode) { case REQUEST_CONNECT_DEVICE: // When DeviceListActivity/bluetooth_room returns with a device to connect if (resultCode == Activity.RESULT_OK) { // Get the device MAC address String address = data.getExtras() .getString(bluetooth_room.EXTRA_DEVICE_ADDRESS); // Get the BLuetoothDevice object BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); // Attempt to connect to the device mSerialService.connect(device); } break; /*case REQUEST_ENABLE_BT: // When the request to enable Bluetooth returns if (resultCode != Activity.RESULT_OK) { Log.d(LOG_TAG, "BT not enabled"); finishDialogNoBluetooth(); }*/ } } //-------------------------------------------------------------------------------------------------- //Bagian tombol menu dan setting @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.bluetooth_room, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } //-------------------------------------------------------------------------------------------------- }
true
848426433efbd2daf1359cab1815459768b4d1c2
Java
dobybros/GroovyCloud
/core/src/main/java/script/groovy/runtime/ClassAnnotationGlobalHandler.java
UTF-8
629
1.953125
2
[]
no_license
package script.groovy.runtime; import java.lang.annotation.Annotation; import java.util.Map; public abstract class ClassAnnotationGlobalHandler { public abstract Class<? extends Annotation> handleAnnotationClass(GroovyRuntime groovyRuntime); public abstract void handleAnnotatedClasses(Map<String, Class<?>> annotatedClassMap, GroovyRuntime groovyRuntime); public abstract void handleAnnotatedClassesInjectBean(GroovyRuntime groovyRuntime); public boolean isBean() { return true; } public Object getKey() { return this.getClass(); } public void handlerShutdown() { } }
true
a479fa533395edf3fb67f3f5ea35702afe274dea
Java
ataulm/a11y-time
/app/src/main/java/com/ataulm/a11y/character/Species.java
UTF-8
180
1.601563
2
[]
no_license
package com.ataulm.a11y.character; enum Species { HUMAN, DOG, VAMPIRE_DEMON, WIZARD, CANDY_PERSON, RAINICORN, LUMPY_SPACE_PERSON, MO, LICH }
true
4eb33f07ef5d03dc303dc008385511fe3f05122c
Java
zzastrow2015/finalProject
/model/Settings.java
UTF-8
1,193
3.3125
3
[]
no_license
package model; public class Settings { public static int screenWidth = 400; public static int screenHeight = 400; public static int sizeX = screenWidth / 16; public static int sizeY = screenHeight / 16; private boolean limitedBorders; private int amountObstacles; private int delayTime; //Sets the difficulty, if there's borders, and if there's obstacles based on what was passed from the controller. public Settings(String difficulty, boolean limitedBorders, boolean obstacles){ delayTime = 120; //delayTime determines how long of a delay should take place before the snake is updated. if(difficulty.toUpperCase().equals("EASY")){ delayTime = 120; } else if(difficulty.toUpperCase().equals("MEDIUM")){ delayTime = 100; } else if(difficulty.toUpperCase().equals("HARD")){ delayTime = 80; } else if(difficulty.toUpperCase().equals("VERY_HARD")){ delayTime = 60; } this.limitedBorders = limitedBorders; amountObstacles = obstacles ? 10 : 0; } public int getDelayTime(){ return delayTime; } public int getAmountObstacles(){ return amountObstacles; } public boolean isBorderLimited(){ return limitedBorders; } }
true
ae3d8cebd1b6c8dab7b24fa3e4f90c5359a08181
Java
lzk-github/web2-maven
/src/main/java/com/kaishengit/service/AccService.java
UTF-8
4,630
2.40625
2
[]
no_license
package com.kaishengit.service; import java.sql.Timestamp; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import com.kaishengit.dao.AccDao; import com.kaishengit.dao.CompanyDao; import com.kaishengit.entity.Acc; import com.kaishengit.entity.Company; import com.kaishengit.exception.ServiceException; import com.kaishengit.util.Config; import com.kaishengit.util.Page; public class AccService { private AccDao ad = new AccDao(); private CompanyDao cd = new CompanyDao(); public void save(String name, String idNo, String tel, String companyId, String dept) throws RuntimeException { Acc acc = ad.findByIdNo(idNo); if (acc == null) { acc = new Acc(); acc.setName(name); acc.setIdNo(idNo); acc.setTel(tel); acc.setCompanyId(Integer.parseInt(companyId)); acc.setDept(dept); acc.setPassword(DigestUtils.md5Hex(Config.get("password.salt") + "123456")); ad.save(acc); } else { throw new RuntimeException("身份证号已存在!保存失败"); } } public Page<Acc> findByPageNo(int pageNo) { // 先找到总数据条目数 int total = ad.findTotalCount(); // 获取开始数据 Page<Acc> page = new Page<>(pageNo, total); List<Acc> list = ad.findByPage(page.getStart(), page.getPageSize()); page.setItems(list); return page; } public Page<Acc> findByParams(int pageNo, String attr, String value) throws RuntimeException { if (StringUtils.isNotEmpty(attr) && attr.equals("company_id")) { if (StringUtils.isNotEmpty(value)) { Company com = cd.findByCompanyName(value); if (com != null) { value = String.valueOf(com.getId()); } else { throw new RuntimeException("没有该公司信息!"); } } } int count = ad.findCountByParams(attr, value); Page<Acc> page = new Page<>(pageNo, count); int start = page.getStart(); int pageSize = page.getPageSize(); List<Acc> list = ad.findByMultiParams(attr, value, start, pageSize); page.setItems(list); return page; /* * if(StringUtils.isEmpty(attr) || StringUtils.isEmpty(value)) { return * findByPageNo(pageNo); } * //如果选择通过公司名字查询list列表,那么先要找到公司的这个名字对应Acc表中的id,目的只返回Acc对象 * if(attr.equals("company_id")) { Company company = * cd.findByCompanyName(value); if(company == null) { return null; } * else { int id = company.getId(); value = String.valueOf(id); } } */ // 现在有3个参数,pageNo,key=列名,value=列名对应的值,根据这3个参数组成sql语句,去数据库中 // 查List<Acc>列表,然后把这个list放到page里,用page.setItems(); // TODO List<Acc> accs = ad.findByParams(pageNo,attr,value); // 应该先找到在满足attr=value的时候有多少条数据,然后根据page类得到limit ?, ?(start,pagesize) /* * int count = ad.findCountByParams(attr,value); Page<Acc> page = new * Page<>(pageNo,count); int start = page.getStart(); List<Acc> accs = * ad.findByParams(attr, value, start,page.getPageSize()); * page.setItems(accs); return page; */ } public void delAccById(int id) { Acc acc = ad.findById(id); if (acc != null) { ad.delById(id); } else { throw new RuntimeException("该id没有对应数据!"); } } public Acc findById(int id) { Acc acc = ad.findById(id); if (acc == null) { throw new RuntimeException("没有此id数据"); } else { return acc; } } public void edit(String id,String companyId, String dept) { if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(companyId) && StringUtils.isNotEmpty(dept)) { if(StringUtils.isNumeric(id) && StringUtils.isNumeric(companyId)) { Acc acc = ad.findById(Integer.parseInt(id)); if(acc != null) { acc.setCompanyId(Integer.parseInt(companyId)); acc.setDept(dept); ad.update(acc); } else { throw new RuntimeException("没有该id对应的数据!"); } } else { throw new RuntimeException("请传入正确的公司id!"); } } else { throw new RuntimeException("请传入正确的参数(公司/部门)!"); } } public Acc login(String name, String password,String remoteIp) { Acc acc = ad.findByName(name); if(password != null) { password = DigestUtils.md5Hex(Config.get("password.salt") + password); } if(acc != null && acc.getPassword().equals(password)) { acc.setLastLoginTime(new Timestamp(System.currentTimeMillis())); acc.setLastLoginIp(remoteIp); ad.update(acc); return acc; } else { throw new ServiceException("账号或密码错误!"); } } }
true
60be089194dd3a78d742bda4ec9080fab7360886
Java
Auch-Auch/avito_source
/sources/com/yandex/mapkit/traffic/TrafficLevel.java
UTF-8
2,256
2.46875
2
[]
no_license
package com.yandex.mapkit.traffic; import androidx.annotation.NonNull; import com.yandex.runtime.NativeObject; import com.yandex.runtime.bindings.Archive; import com.yandex.runtime.bindings.Serializable; import java.nio.ByteBuffer; public class TrafficLevel implements Serializable { private TrafficColor color; private boolean color__is_initialized = false; private int level; private boolean level__is_initialized = false; private NativeObject nativeObject; public TrafficLevel() { } private native TrafficColor getColor__Native(); private native int getLevel__Native(); public static String getNativeName() { return "yandex::maps::mapkit::traffic::TrafficLevel"; } private native NativeObject init(TrafficColor trafficColor, int i); private static native NativeObject loadNative(ByteBuffer byteBuffer); private native ByteBuffer saveNative(); @NonNull public synchronized TrafficColor getColor() { if (!this.color__is_initialized) { this.color = getColor__Native(); this.color__is_initialized = true; } return this.color; } public synchronized int getLevel() { if (!this.level__is_initialized) { this.level = getLevel__Native(); this.level__is_initialized = true; } return this.level; } @Override // com.yandex.runtime.bindings.Serializable public void serialize(Archive archive) { if (archive.isReader()) { this.nativeObject = loadNative(archive.add((ByteBuffer) null)); return; } ByteBuffer.allocateDirect(10); archive.add(saveNative()); } public TrafficLevel(@NonNull TrafficColor trafficColor, int i) { if (trafficColor != null) { this.nativeObject = init(trafficColor, i); this.color = trafficColor; this.color__is_initialized = true; this.level = i; this.level__is_initialized = true; return; } throw new IllegalArgumentException("Required field \"color\" cannot be null"); } private TrafficLevel(NativeObject nativeObject2) { this.nativeObject = nativeObject2; } }
true
555b4d50aaf76ec97c8bf78c947fa5d5567a002a
Java
InfinityRaider/InfinityLib
/src/main/java/com/infinityraider/infinitylib/crafting/dynamictexture/ShapelessDynamicTextureRecipe.java
UTF-8
3,403
2.171875
2
[ "MIT" ]
permissive
package com.infinityraider.infinitylib.crafting.dynamictexture; import com.google.common.collect.ImmutableList; import com.google.gson.JsonObject; import com.infinityraider.infinitylib.crafting.IInfIngredientSerializer; import com.infinityraider.infinitylib.crafting.IInfRecipeSerializer; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.inventory.CraftingContainer; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.crafting.RecipeSerializer; import net.minecraft.world.item.crafting.ShapelessRecipe; import net.minecraft.world.level.Level; import net.minecraftforge.registries.ForgeRegistryEntry; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class ShapelessDynamicTextureRecipe extends ShapelessRecipe { public static final String ID = "crafting_shapeless_dynamic_texture"; public static final IInfRecipeSerializer<ShapelessDynamicTextureRecipe> SERIALIZER = new Serializer(); public ShapelessDynamicTextureRecipe(ShapelessRecipe parent) { super(parent.getId(), parent.getGroup(), parent.getResultItem(), parent.getIngredients()); } @Override @Nonnull public RecipeSerializer<?> getSerializer() { return SERIALIZER; } @Override @Nonnull public ItemStack getResultItem() { return ItemStack.EMPTY; } @Override public boolean isSpecial() { return true; } @Override public boolean matches(@Nonnull CraftingContainer inv, @Nonnull Level world) { // TODO return super.matches(inv, world); } @Override @Nonnull public ItemStack assemble(@Nonnull CraftingContainer inv) { // TODO return super.assemble(inv); } public static class Serializer extends ForgeRegistryEntry<RecipeSerializer<?>> implements IInfRecipeSerializer<ShapelessDynamicTextureRecipe> { private Serializer() {} @Nonnull @Override public String getInternalName() { return ID; } @Override public boolean isEnabled() { return true; } @Nonnull @Override public ShapelessDynamicTextureRecipe fromJson(@Nonnull ResourceLocation recipeId, @Nonnull JsonObject json) { return this.convert(RecipeSerializer.SHAPELESS_RECIPE.fromJson(recipeId, json)); } @Nullable @Override public ShapelessDynamicTextureRecipe fromNetwork(@Nonnull ResourceLocation recipeId, @Nonnull FriendlyByteBuf buffer) { return this.convert(RecipeSerializer.SHAPELESS_RECIPE.fromNetwork(recipeId, buffer)); } protected ShapelessDynamicTextureRecipe convert(@Nullable ShapelessRecipe recipe) { return recipe == null ? null : new ShapelessDynamicTextureRecipe(recipe); } @Override public void toNetwork(@Nonnull FriendlyByteBuf buffer, @Nonnull ShapelessDynamicTextureRecipe recipe) { RecipeSerializer.SHAPELESS_RECIPE.toNetwork(buffer, recipe); } @Override public ImmutableList<IInfIngredientSerializer<?>> getIngredientSerializers() { return ImmutableList.of( DynamicTextureIngredient.SERIALIZER, DynamicTextureParentIngredient.SERIALIZER ); } } }
true
470575f6f6f2c7215b1e9c4e9d61025bfb26c637
Java
matthew-cheney/cpc-templates
/java/GoatRope.java
UTF-8
518
3.21875
3
[]
no_license
import java.util.Scanner; public class GoatRope { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); int x1 = sc.nextInt(); int y1 = sc.nextInt(); int x2 = sc.nextInt(); int y2 = sc.nextInt(); int answer = 0; // do your work here, store result in variable 'answer' // 'x', 'y', 'x1', 'y1', 'x2', 'y2' are integers System.out.println(answer); } }
true
913203fab1f7714515ba6c47af63cd1ef44e52c5
Java
carlosalejandroqm/ProyectoBases
/src/co/edu/ufps/cancha/controller/CajeroServlet.java
UTF-8
6,204
2.34375
2
[]
no_license
package co.edu.ufps.cancha.controller; import java.io.IOException; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import co.edu.ufps.cancha.dao.CajeroDAO; import co.edu.ufps.cancha.dao.CargoDAO; import co.edu.ufps.cancha.dao.EmpleadoDAO; import co.edu.ufps.cancha.dao.UsuarioDAO; import co.edu.ufps.cancha.entities.Administrador; import co.edu.ufps.cancha.entities.Cajero; import co.edu.ufps.cancha.entities.Cargo; import co.edu.ufps.cancha.entities.Empleado; import co.edu.ufps.cancha.entities.Usuario; /** * Servlet implementation class CajeroServlet */ @WebServlet("/CajeroServlet") public class CajeroServlet extends HttpServlet { private static final long serialVersionUID = 1L; private CajeroDAO cajeroDao = new CajeroDAO(); private EmpleadoDAO eDao = new EmpleadoDAO(); /** * @see HttpServlet#HttpServlet() */ public CajeroServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); System.out.println(action); try { switch (action) { case "new": showNewForm(request, response); break; case "register": insert(request, response); break; case "delete": delete(request, response); break; case "showedit": showEditForm(request, response); break; case "editar": update(request, response); break; default: list(request, response); break; } } catch (SQLException ex) { throw new ServletException(ex); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } private void showNewForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher("registro.jsp"); dispatcher.forward(request, response); } private void insert(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ParseException, ServletException { RequestDispatcher dispatcher = null; UsuarioDAO uDao = new UsuarioDAO(); CargoDAO cDao = new CargoDAO(); Cargo cg = cDao.find(2); Usuario us = new Usuario(null, request.getParameter("usuario"), request.getParameter("pass"), cg); Empleado em =new Empleado(null, request.getParameter("dni"), request.getParameter("nombre"), request.getParameter("apellido"), request.getParameter("correo"), Integer.parseInt(request.getParameter("horas")), Integer.parseInt(request.getParameter("telefono")), null, null, cg, us); if (!uDao.existeUsuario(us.getNombre())) { uDao.insert(us); eDao.insert(em); Empleado e = eDao.encontrarEmpleado(em); Cajero cajero = new Cajero(e.getIdEmpleado()); eDao.update(e); cajeroDao.insert(cajero); dispatcher = request.getRequestDispatcher("mostrar.jsp"); }else { dispatcher = request.getRequestDispatcher("mostrar.jsp"); request.setAttribute("error", "El cajero ya existe"); } dispatcher.forward(request, response); } private void list(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { List<Cajero> list = cajeroDao.list(); List<Empleado> listEm = new ArrayList<>(); for(Cajero c: list) { listEm.add(eDao.find(c.getIdEmpleado())); } request.setAttribute("list", listEm); RequestDispatcher dispatcher = request.getRequestDispatcher("mostrar.jsp"); dispatcher.forward(request, response); } private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException { Integer id = Integer.parseInt(request.getParameter("id")); Cajero cajero = cajeroDao.find(id); RequestDispatcher dispatcher = request.getRequestDispatcher("editar.jsp"); request.setAttribute("cajero", cajero); dispatcher.forward(request, response); } private void update(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ParseException, ServletException { RequestDispatcher dispatcher = null; Integer id = Integer.parseInt(request.getParameter("id")); Cajero cajero = cajeroDao.find(id); if (cajero != null) { Empleado e= eDao.find(cajero.getIdEmpleado()); e.setDni(request.getParameter("dni")); e.setNombre(request.getParameter("nombre")); e.setApellido(request.getParameter("apellido")); e.setCorreo(request.getParameter("correo")); e.setHorasExtra(Integer.parseInt(request.getParameter("horas"))); e.setTelefono(Integer.parseInt(request.getParameter("telefono"))); e.setCargoBean(e.getCargoBean()); e.setUsuario(e.getUsuario()); dispatcher = request.getRequestDispatcher("mostrar.jsp"); } else { dispatcher = request.getRequestDispatcher("mostrar.jsp"); request.setAttribute("error", "El cajero no existe"); } dispatcher.forward(request, response); } private void delete(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { Integer id = Integer.parseInt(request.getParameter("id")); Cajero cajero = cajeroDao.find(id); Empleado empleado = eDao.find(cajero.getIdEmpleado()); eDao.delete(empleado); cajeroDao.delete(cajero); RequestDispatcher dispatcher = request.getRequestDispatcher("EmpleadoServlet?action=mostrar"); dispatcher.forward(request, response); } }
true
b835ae142fa7b981da6ea83eca1ddf84eccf0fba
Java
yuehuihui1212/yizhigou-parent
/yizhigou-search-interface/src/main/java/com/yizhigou/search/service/ItemSearchService.java
UTF-8
480
1.640625
2
[]
no_license
package com.yizhigou.search.service; import com.yizhigou.pojo.TbItem; import java.util.List; import java.util.Map; /** * @Author: yuehuihui * @Description: * @Date: created in 14:36 2018/5/13 * @Modified By: **/ public interface ItemSearchService { public Map<String, Object> search(Map searchMap); //向索引库导入数据 public void importData(List<TbItem> list); //根据goodsID删除索引库 public void deleteByGoodsId(List goodsIdList); }
true
c185b50f9643a32ade6b1979d5abb3b81615a3e1
Java
CPP849/Virtual-Bank---Java-Edition
/virtualBank/src/virtualBank/VirtualBank.java
UTF-8
6,892
3.375
3
[]
no_license
package virtualBank; import java.util.Scanner; public class VirtualBank { static boolean init = false; static String firstName = ""; static String lastName = ""; static int balance = 0; static int loanOwe = 0; public static void main(String[] args) { intro(); } public static void mainMenu() { clearScreen(); System.out.println(" ██╗░░░██╗██╗██████╗░████████╗██╗░░░██╗░█████╗░██╗░░░░░  ██████╗░░█████╗░███╗░░██╗██╗░░██╗"); System.out.println(" ██║░░░██║██║██╔══██╗╚══██╔══╝██║░░░██║██╔══██╗██║░░░░░  ██╔══██╗██╔══██╗████╗░██║██║░██╔╝"); System.out.println(" ╚██╗░██╔╝██║██████╔╝░░░██║░░░██║░░░██║███████║██║░░░░░  ██████╦╝███████║██╔██╗██║█████═╝░"); System.out.println(" ░╚████╔╝░██║██╔══██╗░░░██║░░░██║░░░██║██╔══██║██║░░░░░  ██╔══██╗██╔══██║██║╚████║██╔═██╗░"); System.out.println(" ░░╚██╔╝░░██║██║░░██║░░░██║░░░╚██████╔╝██║░░██║███████╗  ██████╦╝██║░░██║██║░╚███║██║░╚██╗"); System.out.println(" ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░░╚═════╝░╚═╝░░╚═╝╚══════╝  ╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░╚═╝"); System.out.println("\n\n\n\n\n\n Main Menu\n "); System.out.println(" 01) Create an Account"); System.out.println(" 02) Show Account"); System.out.println(" 03) Deposit Money"); System.out.println(" 04) Withdraw Money"); System.out.println(" 05) DELETE ACCOUNT"); System.out.print("\n\n\n Type the option number: "); @SuppressWarnings("resource") Scanner choiceS = new Scanner(System.in); int choice = choiceS.nextInt(); if (choice == 1) { createAccount(); } else if (choice == 2) { showAccount(); } else if (choice == 3) { deposit(); } else if (choice == 4) { withdraw(); } else if (choice == 5) { deleteAccount(); } else { mainMenu(); } } public static void createAccount() { if (init == true) { mainMenu(); } else { @SuppressWarnings("resource") Scanner firstNameS = new Scanner(System.in); @SuppressWarnings("resource") Scanner lastNameS = new Scanner(System.in); clearScreen(); System.out.print("What is your first name? "); firstName = firstNameS.next(); System.out.print("What is your last name? "); lastName = lastNameS.next(); boolean init = true; mainMenu(); } } public static void showAccount() { @SuppressWarnings("resource") Scanner nullS = new Scanner(System.in); clearScreen(); System.out.println("Full Name: " + firstName + " " + lastName); System.out.println("Balance: " + balance); System.out.println("Loans: " + loanOwe); System.out.print("\n Press \"y\" to leave "); nullS.next(); mainMenu(); } public static void deposit() { clearScreen(); @SuppressWarnings("resource") Scanner depositS = new Scanner(System.in); System.out.println("How much would you like to deposit? "); int depositAmount = depositS.nextInt(); balance = balance + depositAmount; mainMenu(); } public static void withdraw() { clearScreen(); @SuppressWarnings("resource") Scanner withdrawS = new Scanner(System.in); System.out.println("How much would you like to deposit? "); int withdrawAmount = withdrawS.nextInt(); balance = balance - withdrawAmount; mainMenu(); } public static void deleteAccount() { @SuppressWarnings("resource") Scanner choiceS = new Scanner(System.in); clearScreen(); System.out.println("Are you sure you want to delete your account? \"y\" or \"n\": "); String choice = choiceS.next(); if (choice == "y") { boolean init = false; String firstName = ""; String lastName = ""; int balance = 0; } else { deleteAccount(); } } public static void intro() { @SuppressWarnings("resource") Scanner nullS = new Scanner(System.in); clearScreen(); System.out.println(" ██╗░░░██╗██╗██████╗░████████╗██╗░░░██╗░█████╗░██╗░░░░░  ██████╗░░█████╗░███╗░░██╗██╗░░██╗"); System.out.println(" ██║░░░██║██║██╔══██╗╚══██╔══╝██║░░░██║██╔══██╗██║░░░░░  ██╔══██╗██╔══██╗████╗░██║██║░██╔╝"); System.out.println(" ╚██╗░██╔╝██║██████╔╝░░░██║░░░██║░░░██║███████║██║░░░░░  ██████╦╝███████║██╔██╗██║█████═╝░"); System.out.println(" ░╚████╔╝░██║██╔══██╗░░░██║░░░██║░░░██║██╔══██║██║░░░░░  ██╔══██╗██╔══██║██║╚████║██╔═██╗░"); System.out.println(" ░░╚██╔╝░░██║██║░░██║░░░██║░░░╚██████╔╝██║░░██║███████╗  ██████╦╝██║░░██║██║░╚███║██║░╚██╗"); System.out.println(" ░░░╚═╝░░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░░╚═════╝░╚═╝░░╚═╝╚══════╝  ╚═════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═╝░░╚═╝"); System.out.print("\n\n\n Enter \"y\" to get enter: "); String non = nullS.next(); mainMenu(); } public static void clearScreen() { System.out.print("\033[H\033[2J"); System.out.flush(); } }
true
9ad0bb8bc0e40c38648017cefbc52999e37fda61
Java
lai1245199086/cj.studio.ecm
/cj.studio.ecm.net/src/cj/studio/ecm/net/nio/netty/http/HttpServerDiverter.java
UTF-8
963
2.171875
2
[]
no_license
package cj.studio.ecm.net.nio.netty.http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cj.studio.ecm.frame.Circuit; import cj.studio.ecm.frame.Frame; import cj.studio.ecm.graph.CircuitException; import cj.studio.ecm.graph.IPin; import cj.studio.ecm.graph.IPlug; import cj.studio.ecm.graph.ISink; public class HttpServerDiverter implements ISink { Logger logger=LoggerFactory.getLogger(HttpHandlerBinder.class); @Override public void flow(Frame frame,Circuit circuit, IPlug plug) throws CircuitException { // Send the uppercase string back. //logger.debug(frame+" "+plug.fullName()+" "+frame.head("senderType")+" "+plug.circuit().attribute("req")+" "+plug.circuit().attribute("ctx")); if (plug.owner().startsWith("input_")) { IPin out = plug.branch("output"); out.flow(frame, circuit); return; } if ("input".equals(plug.owner())) { IPin sp = plug.branch("feedback"); sp.flow(frame,circuit); return; } } }
true
f67227823a162f18722304077cae05999fe335cb
Java
SpearKitty/YGO-Combo-Simulator
/src/com/spkitty/frame/JCBoxArray.java
UTF-8
916
2.734375
3
[ "MIT" ]
permissive
package com.spkitty.frame; import java.awt.GridLayout; import javax.swing.JCheckBox; import javax.swing.JPanel; public class JCBoxArray extends JPanel{ /** * umu */ private static final long serialVersionUID = 1L; private JCheckBox[] boxes; public JCBoxArray(int size, int init_wid) { this.setLayout(new GridLayout((size / init_wid) + 1, init_wid)); boxes = new JCheckBox[size]; } public boolean loadStrings(String[] items) { if(items.length > boxes.length) return false; for(int i = 0; i < items.length; i++) { boxes[i] = new JCheckBox(items[i]); this.add(boxes[i]); } return true; } public boolean[] getSelection() { if(boxes.length == 0) return null; boolean[] results = new boolean[boxes.length]; for(int i = 0; i < boxes.length; i++) try { results[i] = boxes[i].isSelected(); }catch(Exception e) { return results; } return results; } }
true
e53aed1817472e3484a3cd4ef88b884be3522bcc
Java
vipin19794/FundooNotesApi
/Fundoonotes/src/main/java/com/bridgeLabz/fundoonotes/model/CollaboratorModel.java
UTF-8
1,030
2.34375
2
[]
no_license
package com.bridgeLabz.fundoonotes.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "Collaborator") public class CollaboratorModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "collaborator_id") private Long cId; @Column(name = "collaborator_mail") private String collaborator; @ManyToOne @JoinColumn(name = "note_id") private NoteModel notes; public Long getcId() { return cId; } public void setcId(Long cId) { this.cId = cId; } public String getCollaborator() { return collaborator; } public void setCollaborator(String collaborator) { this.collaborator = collaborator; } public NoteModel getNotes() { return notes; } public void setNotes(NoteModel notes) { this.notes = notes; } }
true
64297039ba6e921958052f85817adea9c410b291
Java
vickailiu/UGuide
/app/src/main/java/com/kai/uguide/SelectImageActivity.java
UTF-8
21,612
1.570313
2
[]
no_license
package com.kai.uguide; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.TypedArray; import android.graphics.Color; import android.location.Location; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.TypedValue; import android.view.View; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.astuetz.viewpager.extensions.FixedTabsView; import com.astuetz.viewpager.extensions.TabsAdapter; import com.getbase.floatingactionbutton.AddFloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionButton; import com.getbase.floatingactionbutton.FloatingActionsMenu; import com.github.ksoichiro.android.observablescrollview.ObservableScrollView; import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks; import com.github.ksoichiro.android.observablescrollview.ScrollState; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.kai.uguide.fragment.CurrentWeatherFragment; import com.kai.uguide.fragment.WeatherFragment; import com.kai.uguide.utils.FileUtils; import com.kai.uguide.viewpageradapter.ExamplePagerAdapter; import com.kai.uguide.viewpageradapter.FixedIconTabsAdapter; import com.nineoldandroids.view.ViewHelper; import com.nineoldandroids.view.ViewPropertyAnimator; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class SelectImageActivity extends ActionBarActivity implements ObservableScrollViewCallbacks, WeatherFragment.WeatherEventListener { static final int REQUEST_IMAGE_CAPTURE = 1; static final int REQUEST_IMAGE_GALLERY = 2; private static final float MAX_TEXT_SCALE_DELTA = 0.3f; private static final boolean TOOLBAR_IS_STICKY = false; private final int MAP_ZOOM = 16; private View mToolbar; private View mImageView; private View mOverlayView; private ObservableScrollView mScrollView; private TextView mTitleView; private int deviceHeightHalf; private int lastScrollY; private RelativeLayout introView; private LinearLayout.LayoutParams introParams; private int sectionViewMaxHeight; private int sectionViewMinHeight; private View weatherView; private View text_overlay; private RelativeLayout.LayoutParams text_overlay_params; private FloatingActionsMenu mFab; private AddFloatingActionButton mAddbutton; private FloatingActionButton profileButton; private FloatingActionButton cameraButton; private FloatingActionButton galleryeButton; private int mActionBarSize; private int mFlexibleSpaceShowFabOffset; private int mFlexibleSpaceImageHeight; private int mFabMargin; private int mToolbarColor; private boolean mFabIsShown; // Google Map private MapFragment mapFragment; private View mapView; private GoogleMap googleMap; private Marker marker; private LinearLayout.LayoutParams mapParams; private ViewPager mPager; private FixedTabsView mFixedTabs; private PagerAdapter mPagerAdapter; private TabsAdapter mFixedTabsAdapter; private String mCurrentPhotoPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_image); initializeScrollView(); initializeFloatingActionButton(); try { initializeMap(); } catch (Exception e) { e.printStackTrace(); } initializeViews(); initializeWeatherFrag(); } @Override protected void onResume() { super.onResume(); initializeMap(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode != RESULT_OK)//result is not correct return; //TODO: keep here for future options // if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { // galleryAddPic(); // } if ((resultCode == RESULT_OK) && (requestCode == REQUEST_IMAGE_GALLERY)) { Uri uri = null; if (data != null) { uri = data.getData(); mCurrentPhotoPath = FileUtils.getPath(this, uri); } } Intent i = new Intent(this, CropImageActivity.class); i.putExtra("filePath", mCurrentPhotoPath); startActivity(i); } @Override public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) { // Translate overlay and image float flexibleRange = mFlexibleSpaceImageHeight - mActionBarSize; int minOverlayTransitionY = mActionBarSize - mOverlayView.getHeight(); ViewHelper.setTranslationY(mOverlayView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY))); ViewHelper.setTranslationY(mImageView, Math.max(minOverlayTransitionY, Math.min(0, -scrollY / 2))); // Change alpha of overlay ViewHelper.setAlpha(mOverlayView, Math.max(0, Math.min(1, (float) scrollY / flexibleRange))); ViewHelper.setAlpha(weatherView, 1 - Math.max(0, Math.min(1, (float) scrollY / flexibleRange * 2))); // Scale title text float scale = 1 + Math.max(0, Math.min(MAX_TEXT_SCALE_DELTA, (flexibleRange - scrollY) / flexibleRange)); ViewHelper.setPivotX(mTitleView, 0); ViewHelper.setPivotY(mTitleView, 0); ViewHelper.setScaleX(mTitleView, scale); ViewHelper.setScaleY(mTitleView, scale); // Translate title text int maxTitleTranslationY = (int) (mFlexibleSpaceImageHeight - mTitleView.getHeight() * scale); int titleTranslationY = maxTitleTranslationY - scrollY; if (TOOLBAR_IS_STICKY) { titleTranslationY = Math.max(0, titleTranslationY); } ViewHelper.setTranslationY(mTitleView, titleTranslationY); // Translate FAB mFab.collapse(); int maxFabTranslationY = mFlexibleSpaceImageHeight;// - mFab.getHeight() / 2; int fabTranslationY = Math.max(mActionBarSize,// - mFab.getHeight() / 2, Math.min(maxFabTranslationY, -scrollY + mFlexibleSpaceImageHeight));// - mFab.getHeight() / 2)); ViewHelper.setTranslationX(mFab, mOverlayView.getWidth() - mFabMargin - mFab.getWidth()); ViewHelper.setTranslationY(mFab, fabTranslationY - mFab.getHeight() + 56); // Show/hide FAB // if (ViewHelper.getTranslationY(mFab) < mFlexibleSpaceShowFabOffset) { // hideFab(); // } else { // showFab(); // } if (TOOLBAR_IS_STICKY) { // Change alpha of toolbar background if (-scrollY + mFlexibleSpaceImageHeight <= mActionBarSize) { setBackgroundAlpha(mToolbar, 1, mToolbarColor); } else { setBackgroundAlpha(mToolbar, 0, mToolbarColor); } } else { // Translate Toolbar if (scrollY < mFlexibleSpaceImageHeight) { ViewHelper.setTranslationY(mToolbar, 0); } else { ViewHelper.setTranslationY(mToolbar, -scrollY); } } updateView(introView, introParams, scrollY); //updateView(mapView, mapParams, scrollY - lastScrollY); lastScrollY = scrollY; } private void updateView(View view, LinearLayout.LayoutParams params, int scroll) { int startScroll = 0; int range = (int) getResources().getDimension(R.dimen.sectionViewMaxHeight) - (int) getResources().getDimension(R.dimen.sectionViewMinHeight); double factor = 1.0 * Math.abs(scroll - (startScroll + range))/ range; if (factor > 1) return; params.height = (int)getResources().getDimension(R.dimen.sectionViewMinHeight) + (int) (range * (1 - factor));// * factor)); // if (delta > 0) // params.height = (int)getResources().getDimension(R.dimen.sectionViewMinHeight) // + delta; // if (delta < 0) // params.height = (int)getResources().getDimension(R.dimen.sectionViewMaxHeight) // - delta; view.setLayoutParams(params); text_overlay_params.height = (int) (factor * 100.0); text_overlay.setLayoutParams(text_overlay_params); } private void initializeScrollView() { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); mFlexibleSpaceImageHeight = getResources().getDimensionPixelSize(R.dimen.flexible_space_image_height); mFlexibleSpaceShowFabOffset = getResources().getDimensionPixelSize(R.dimen.flexible_space_show_fab_offset); mActionBarSize = getActionBarSize(); mToolbarColor = getResources().getColor(R.color.primary); mToolbar = findViewById(R.id.toolbar); if (!TOOLBAR_IS_STICKY) { mToolbar.setBackgroundColor(Color.TRANSPARENT); } mImageView = findViewById(R.id.image); mOverlayView = findViewById(R.id.overlay); mScrollView = (ObservableScrollView) findViewById(R.id.scroll); mScrollView.setScrollViewCallbacks(this); mTitleView = (TextView) findViewById(R.id.title); mTitleView.setText("Singapore"); setTitle(null); ViewTreeObserver vto = mScrollView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { mScrollView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { mScrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } //mScrollView.scrollTo(0, mFlexibleSpaceImageHeight - mActionBarSize); // If you'd like to start from scrollY == 0, don't write like this: //mScrollView.scrollTo(0, 0); // The initial scrollY is 0, so it won't invoke onScrollChanged(). // To do this, use the following: onScrollChanged(0, false, false); // You can also achieve it with the following codes. // This causes scroll change from 1 to 0. //mScrollView.scrollTo(0, 1); //mScrollView.scrollTo(0, 0); } }); } private void initializeFloatingActionButton() { mFab = (FloatingActionsMenu) findViewById(R.id.fab); mAddbutton = (AddFloatingActionButton) findViewById(R.id.fab_expand_menu_button); profileButton = (FloatingActionButton) findViewById(R.id.profile); cameraButton = (FloatingActionButton) findViewById(R.id.camera); galleryeButton = (FloatingActionButton) findViewById(R.id.gallery); profileButton.setIcon(R.drawable.ic_profile); cameraButton.setIcon(R.drawable.ic_camera_b); galleryeButton.setIcon(R.drawable.ic_gallery); // mAddbutton.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // } // }); mAddbutton.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { mFab.collapse(); Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, REQUEST_IMAGE_GALLERY); return true; } }); profileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFab.collapse(); // Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); // intent.addCategory(Intent.CATEGORY_OPENABLE); // intent.setType("image/*"); // startActivityForResult(intent, REQUEST_IMAGE_GALLERY); } }); cameraButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFab.collapse(); Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File double foo = 1; } // Continue only if the File was successfully created if (photoFile != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } } }); galleryeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mFab.collapse(); Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, REQUEST_IMAGE_GALLERY); } }); mFabMargin = getResources().getDimensionPixelSize(R.dimen.margin_standard); // ViewHelper.setScaleX(mFab, 0); // ViewHelper.setScaleY(mFab, 0); } private void initializeMap() { if (googleMap == null) { mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)); googleMap = mapFragment.getMap(); mapView = (RelativeLayout) findViewById(R.id.mapView); mapParams = (LinearLayout.LayoutParams) mapView.getLayoutParams(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } googleMap.setMyLocationEnabled(true); // false to disable googleMap.getUiSettings().setMyLocationButtonEnabled(false); googleMap.getUiSettings().setRotateGesturesEnabled(false); googleMap.getUiSettings().setZoomGesturesEnabled(false); googleMap.getUiSettings().setScrollGesturesEnabled(false); googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { @Override public void onMyLocationChange(Location arg0) { LatLng pos = new LatLng(arg0.getLatitude(), arg0.getLongitude()); if (marker != null) marker.remove(); marker = googleMap.addMarker( new MarkerOptions().position(pos).title("You are here!").flat(true)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, MAP_ZOOM)); } }); } } private void initializeViews() { deviceHeightHalf = (int) (getResources().getDisplayMetrics().heightPixels / 2); introView = (RelativeLayout) findViewById(R.id.textView); introParams = (LinearLayout.LayoutParams) introView.getLayoutParams(); initViewPager(4, 0xFFFFFFFF, 0xFF000000); mFixedTabs = (FixedTabsView) findViewById(R.id.fixed_icon_tabs); mFixedTabsAdapter = new FixedIconTabsAdapter(this); mFixedTabs.setAdapter(mFixedTabsAdapter); mFixedTabs.setViewPager(mPager); text_overlay = findViewById(R.id.text_overlay); text_overlay_params = (RelativeLayout.LayoutParams) text_overlay.getLayoutParams(); } private void initializeWeatherFrag() { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.setTransitionStyle(R.style.fragmentAnim); CurrentWeatherFragment cf = CurrentWeatherFragment.newInstance(); ft.add(R.id.currentWeatherFrag, cf, "currentWeather") ; ft.commit(); weatherView = findViewById(R.id.currentWeatherFrag); } private void initViewPager(int pageCount, int backgroundColor, int textColor) { mPager = (ViewPager) findViewById(R.id.pager); mPagerAdapter = new ExamplePagerAdapter(this, pageCount, backgroundColor, textColor); mPager.setAdapter(mPagerAdapter); mPager.setCurrentItem(1); mPager.setPageMargin(1); } private int getActionBarSize() { TypedValue typedValue = new TypedValue(); int[] textSizeAttr = new int[]{R.attr.actionBarSize}; int indexOfAttrTextSize = 0; TypedArray a = obtainStyledAttributes(typedValue.data, textSizeAttr); int actionBarSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1); a.recycle(); return actionBarSize; } private void showFab() { if (!mFabIsShown) { ViewPropertyAnimator.animate(mFab).cancel(); ViewPropertyAnimator.animate(mFab).scaleX(1).scaleY(1).setDuration(200).start(); mFabIsShown = true; } } private void hideFab() { if (mFabIsShown) { ViewPropertyAnimator.animate(mFab).cancel(); ViewPropertyAnimator.animate(mFab).scaleX(0).scaleY(0).setDuration(200).start(); mFabIsShown = false; } } private void setBackgroundAlpha(View view, float alpha, int baseColor) { int a = Math.min(255, Math.max(0, (int) (alpha * 255))) << 24; int rgb = 0x00ffffff & baseColor; view.setBackgroundColor(a + rgb); } public void on_camera_click(View view) { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File double foo = 1; } // Continue only if the File was successfully created if (photoFile != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); } } } public void on_gallery_click(View view) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("image/*"); startActivityForResult(intent, REQUEST_IMAGE_GALLERY); } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; // File storageDir = Environment.getExternalStoragePublicDirectory( // Environment.DIRECTORY_PICTURES); File storageDir; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { storageDir = getExternalFilesDir(null); } else { storageDir = getFilesDir(); } File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = "file:" + image.getAbsolutePath(); mCurrentPhotoPath = image.getAbsolutePath(); return image; } private void galleryAddPic() { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(mCurrentPhotoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent); } @Override public void onDownMotionEvent() { } @Override public void onUpOrCancelMotionEvent(ScrollState scrollState) { } @Override public void requestCompleted() { } }
true
493d6e4dab7b71634777e87140475f85fef3a28f
Java
jt120/jdk7-8demo
/src/puzzle/PrivateFieldMatter.java
UTF-8
249
2.53125
3
[]
no_license
package puzzle; public class PrivateFieldMatter { public static void main(String[] args) { System.out.println(new Derived().name); } } class Base { public String name = "aaa"; } class Derived extends Base { // private String name = "bbb"; }
true
e5088a1687ee27841923c179e04344ca5a686307
Java
kaskaczmarczyk/Excercices-in-Java
/Zad09PPCwiczenia08.java
UTF-8
627
2.953125
3
[]
no_license
package CwiczeniaZPolskoJaponskiej; /** * Created by Kasia on 2017-05-26. */ public class Zad09PPCwiczenia08 { public static void main(String[] args) { int n = 0; //n to wyraz ciagu Fibonacciego System.out.println(obliczaCiagFibonacciego(20)); } static int obliczaCiagFibonacciego(int n) { int wynik = 0; if (n == 0) { return 0; } if (n == 1) { return 1; } if (n > 1) { wynik = obliczaCiagFibonacciego(n - 1) + obliczaCiagFibonacciego(n - 2); return wynik; } return -1; } }
true
9ce558c9a62912c1d80cfa81bd719303ba528336
Java
parmaraakash7/IVCRM
/REST API/src/main/java/ivgroup/master/database/dto/company/CompanyInsert.java
UTF-8
10,238
2.15625
2
[]
no_license
package ivgroup.master.database.dto.company; import java.sql.Timestamp; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.PastOrPresent; import com.fasterxml.jackson.annotation.JsonFormat; public class CompanyInsert { @NotNull(message = "AddressLine1 cannot be NULL") private String addressLine1; @NotNull(message = "AddressLine2 cannot be NULL") private String addressLine2; @NotNull(message = "AddressLine3 cannot be NULL") private String addressLine3; @NotNull(message = "Pincode cannot be NULL") private Long pincode; @NotNull(message = "CityID cannot be NULL") private Long cityID; @NotNull(message = "StateID cannot be NULL") private Long stateID; @NotNull(message = "CountryID cannot be NULL") private Long countryID; @NotNull(message = "Latitude cannot be NULL") private String latitude; @NotNull(message = "Longitude cannot be NULL") private String longitude; @NotNull(message = "CompanyCode cannot be NULL") private String companyCode; @NotNull(message = "CompanyName cannot be NULL") private String companyName; @NotNull(message = "OwnerContactId cannot be NULL") private Long ownerContactId; @NotNull(message = "CompanyRegionName cannot be NULL") private String companyRegionName; @NotNull(message = "CompanyRegionCode cannot be NULL") private String companyRegionCode; @NotNull(message = "CompanyRegionDescription cannot be NULL") private String companyRegionDescription; @NotNull(message = "CompanyAreaName cannot be NULL") private String companyAreaName; @NotNull(message = "CompanyAreaCode cannot be NULL") private String companyAreaCode; @NotNull(message = "CompanyAreaDescription cannot be NULL") private String companyAreaDescription; @NotNull(message = "CompanyBranchName cannot be NULL") private String companyBranchName; @NotNull(message = "CompanyBranchCode cannot be NULL") private String companyBranchCode; @NotNull(message = "CompanyBranchType cannot be NULL") private Integer companyBranchType; @NotNull(message = "ExecutiveName cannot be NULL") private String executiveName; @NotNull(message = "LoginID cannot be NULL") @Email(message="Please Enter Valid EmailId") private String loginID; @NotNull(message = "Password cannot be NULL") private String password; @NotNull(message = "ContactNumber cannot be NULL") private String contactNumber; @NotNull(message = "CreatedOn cannot be NULL") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "IST") @PastOrPresent Timestamp createdOn; @NotNull(message = "CreatedBy cannot be NULL") private Long createdBy; @NotNull(message = "DeviceType cannot be NULL") private Integer deviceType; public CompanyInsert() { } public CompanyInsert(@NotNull(message = "AddressLine1 cannot be NULL") String addressLine1, @NotNull(message = "AddressLine2 cannot be NULL") String addressLine2, @NotNull(message = "AddressLine3 cannot be NULL") String addressLine3, @NotNull(message = "Pincode cannot be NULL") Long pincode, @NotNull(message = "CityID cannot be NULL") Long cityID, @NotNull(message = "StateID cannot be NULL") Long stateID, @NotNull(message = "CountryID cannot be NULL") Long countryID, @NotNull(message = "Latitude cannot be NULL") String latitude, @NotNull(message = "Longitude cannot be NULL") String longitude, @NotNull(message = "CompanyCode cannot be NULL") String companyCode, @NotNull(message = "CompanyName cannot be NULL") String companyName, @NotNull(message = "OwnerContactId cannot be NULL") Long ownerContactId, @NotNull(message = "CompanyRegionName cannot be NULL") String companyRegionName, @NotNull(message = "CompanyRegionCode cannot be NULL") String companyRegionCode, @NotNull(message = "CompanyRegionDescription cannot be NULL") String companyRegionDescription, @NotNull(message = "CompanyAreaName cannot be NULL") String companyAreaName, @NotNull(message = "CompanyAreaCode cannot be NULL") String companyAreaCode, @NotNull(message = "CompanyAreaDescription cannot be NULL") String companyAreaDescription, @NotNull(message = "CompanyBranchName cannot be NULL") String companyBranchName, @NotNull(message = "CompanyBranchCode cannot be NULL") String companyBranchCode, @NotNull(message = "CompanyBranchType cannot be NULL") Integer companyBranchType, @NotNull(message = "ExecutiveName cannot be NULL") String executiveName, @NotNull(message = "LoginID cannot be NULL") String loginID, @NotNull(message = "Password cannot be NULL") String password, @NotNull(message = "ContactNumber cannot be NULL") String contactNumber, @NotNull(message = "CreatedOn cannot be NULL") @PastOrPresent Timestamp createdOn, @NotNull(message = "CreatedBy cannot be NULL") Long createdBy, @NotNull(message = "DeviceType cannot be NULL") Integer deviceType) { super(); this.addressLine1 = addressLine1; this.addressLine2 = addressLine2; this.addressLine3 = addressLine3; this.pincode = pincode; this.cityID = cityID; this.stateID = stateID; this.countryID = countryID; this.latitude = latitude; this.longitude = longitude; this.companyCode = companyCode; this.companyName = companyName; this.ownerContactId = ownerContactId; this.companyRegionName = companyRegionName; this.companyRegionCode = companyRegionCode; this.companyRegionDescription = companyRegionDescription; this.companyAreaName = companyAreaName; this.companyAreaCode = companyAreaCode; this.companyAreaDescription = companyAreaDescription; this.companyBranchName = companyBranchName; this.companyBranchCode = companyBranchCode; this.companyBranchType = companyBranchType; this.executiveName = executiveName; this.loginID = loginID; this.password = password; this.contactNumber = contactNumber; this.createdOn = createdOn; this.createdBy = createdBy; this.deviceType = deviceType; } public String getAddressLine1() { return addressLine1; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public String getAddressLine2() { return addressLine2; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public String getAddressLine3() { return addressLine3; } public void setAddressLine3(String addressLine3) { this.addressLine3 = addressLine3; } public Long getPincode() { return pincode; } public void setPincode(Long pincode) { this.pincode = pincode; } public Long getCityID() { return cityID; } public void setCityID(Long cityID) { this.cityID = cityID; } public Long getStateID() { return stateID; } public void setStateID(Long stateID) { this.stateID = stateID; } public Long getCountryID() { return countryID; } public void setCountryID(Long countryID) { this.countryID = countryID; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Long getOwnerContactId() { return ownerContactId; } public void setOwnerContactId(Long ownerContactId) { this.ownerContactId = ownerContactId; } public String getCompanyRegionName() { return companyRegionName; } public void setCompanyRegionName(String companyRegionName) { this.companyRegionName = companyRegionName; } public String getCompanyRegionCode() { return companyRegionCode; } public void setCompanyRegionCode(String companyRegionCode) { this.companyRegionCode = companyRegionCode; } public String getCompanyRegionDescription() { return companyRegionDescription; } public void setCompanyRegionDescription(String companyRegionDescription) { this.companyRegionDescription = companyRegionDescription; } public String getCompanyAreaName() { return companyAreaName; } public void setCompanyAreaName(String companyAreaName) { this.companyAreaName = companyAreaName; } public String getCompanyAreaCode() { return companyAreaCode; } public void setCompanyAreaCode(String companyAreaCode) { this.companyAreaCode = companyAreaCode; } public String getCompanyAreaDescription() { return companyAreaDescription; } public void setCompanyAreaDescription(String companyAreaDescription) { this.companyAreaDescription = companyAreaDescription; } public String getCompanyBranchName() { return companyBranchName; } public void setCompanyBranchName(String companyBranchName) { this.companyBranchName = companyBranchName; } public String getCompanyBranchCode() { return companyBranchCode; } public void setCompanyBranchCode(String companyBranchCode) { this.companyBranchCode = companyBranchCode; } public Integer getCompanyBranchType() { return companyBranchType; } public void setCompanyBranchType(Integer companyBranchType) { this.companyBranchType = companyBranchType; } public String getExecutiveName() { return executiveName; } public void setExecutiveName(String executiveName) { this.executiveName = executiveName; } public String getLoginID() { return loginID; } public void setLoginID(String loginID) { this.loginID = loginID; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public Timestamp getCreatedOn() { return createdOn; } public void setCreatedOn(Timestamp createdOn) { this.createdOn = createdOn; } public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } public Integer getDeviceType() { return deviceType; } public void setDeviceType(Integer deviceType) { this.deviceType = deviceType; } }
true
d57e7255ed93885d822234f5ffa0385b60614baf
Java
dawoodchouhan/ThatGuyFrontend
/src/main/java/com/niit/thatguyfrontend/controller/SupplierController.java
UTF-8
2,229
2.265625
2
[]
no_license
package com.niit.thatguyfrontend.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.niit.thatguy.dao.SupplierDAO; import com.niit.thatguybackend.model.Supplier; @Controller public class SupplierController { private static Logger log=LoggerFactory.getLogger(SupplierController.class); @Autowired private Supplier supplier; @Autowired private SupplierDAO supplierDAO; @RequestMapping(value="/suppliers",method=RequestMethod.GET) public String listSuppliers(Model model){ log.debug("starting of the method supplier list"); model.addAttribute("supplier",supplier); model.addAttribute("supplierList",this.supplierDAO.list()); log.debug("Ending of the method supplier list"); return "supplier"; } @RequestMapping(value="/supplier/add",method=RequestMethod.POST) public String addSupplier(@ModelAttribute("supplier")Supplier supplier){ log.debug("starting of the method add supplier"); supplierDAO.save(supplier); log.debug("Ending of the method add supplier"); return "supplier"; } @RequestMapping("supplier/remove/{id}") public ModelAndView deleteSupplier(@PathVariable("id")String id)throws Exception{ boolean flag=supplierDAO.delete(id); ModelAndView mv=new ModelAndView("supplier"); String msg="Operation Successful"; if(flag!=true) { msg="Operation Failed"; } mv.addObject("msg",msg); return mv; } @RequestMapping("supplier/edit/{id}") public String editSupplier(@ModelAttribute("supplier")Supplier supplier){ log.debug("Start of the method Edit Supplier"); supplierDAO.saveOrUpdate(supplier); log.debug("End of the method Edit Supplier"); return "supplier"; } }
true
3c5cab3476cf3b7790c65effb7cb16a66bb2ee76
Java
hakansgithub/WhiteHackers
/src/molecularTeleportation/SignUpLogin.java
UTF-8
1,162
2.625
3
[]
no_license
package molecularTeleportation; public class SignUpLogin { private String userName; private String password; private int age; private int ssn; public String getUserName () { return userName; } public String getPassword () { return password; } public int getAge () { return age; } public int getSsn () { return ssn; } public void setUserName (String userName) { this.userName = userName; } public void setPassword (String password) { this.password = password; } public void setAge (int age) { this.age = age; } public void setSsn (int ssn) { this.ssn = ssn; } public String signUp (String userName, String password, int age, int ssn) { this.userName = userName; this.password = password; this.age = age; this.ssn = ssn; if (age >= 21 && age < 70) { } else { } return ""; } public String LogIn (String userName, String password) { this.userName = userName; this.password = password; return ""; } }
true
2253ba881bf0023b75683858e7742b879cff4303
Java
TimeTurnerr/Musical_Structure
/app/src/main/java/com/example/desmond/musicalstructure/song.java
UTF-8
537
2.703125
3
[]
no_license
package com.example.desmond.musicalstructure; public class song { private String mSongName; private String mArtistName; private int mimageView; public song(String SongName, String ArtistName, int imageView ) { mSongName = SongName; mArtistName = ArtistName; mimageView = imageView; } public String getSongName() { return mSongName; } public String getArtistName() { return mArtistName; } public int getImageResourceID() { return mimageView; } }
true
9832059ceb7f3d43a7859b63611a1fa3908d053f
Java
TU-Berlin-DIMA/resense
/resense-dashboard/src/main/java/de/tuberlin/dima/resense/SensorServiceImpl.java
UTF-8
1,492
2.359375
2
[ "Apache-2.0" ]
permissive
package de.tuberlin.dima.resense; import org.springframework.stereotype.Service; import java.io.IOException; import java.util.List; import java.util.Arrays; @Service public class SensorServiceImpl implements SensorService { @Override public void replay(String sensorId, String experimentId) { this.executeCommand(sensorId, experimentId, "-startSensors"); } @Override public void stopReplay(String sensorId, String experimentId) { this.executeCommand(sensorId, experimentId, "-stopSensors"); } @Override public void record(String sensorId, String experimentId) { this.executeCommand(sensorId, experimentId, "-recordSensors"); } @Override public void stopRecording(String sensorId, String experimentId) { this.executeCommand(sensorId, experimentId, "-stopRecordingSensors"); } private void executeCommand(String sensorId, String experimentId, String actionType) { List<String> commands = Arrays.asList( "java", "-jar", "master-node/target/master-node-1.0-jar-with-dependencies.jar", "-experiment", experimentId, actionType, sensorId ); ProcessBuilder processBuilder = new ProcessBuilder(commands); try { Process process = processBuilder.start(); } catch (IOException ioe) { // TODO: handle exceptions better } } }
true
574b9617df967bed037f9fda2ae4c05493ef230c
Java
oNguyenDucManh/Dictionary-ViRu
/app/src/main/java/dictionary/viet/russia/viru/NextDictUtils/CLog.java
UTF-8
838
2.015625
2
[]
no_license
package dictionary.viet.russia.viru.NextDictUtils; import android.util.Log; /** * Created by manhi on 26/12/2015. */ public class CLog { public static boolean DEBUG = true; public static int w(String tag, String msg) { if (DEBUG) return Log.w(tag, msg); return -1; } public static int d(String tag, String msg) { if (DEBUG) return Log.d(tag, msg); return -1; } public static int e(String tag, String msg) { if (DEBUG) return Log.e(tag, msg); return -1; } public static int v(String tag, String msg) { if (DEBUG) return Log.v(tag, msg); return -1; } public static int i(String tag, String msg) { if (DEBUG) return Log.i(tag, msg); return -1; } }
true
6b85e2da0ee632d962688ceb1aa324f7a206661e
Java
kholmatov/ibag
/app/src/main/java/com/tinyminds/ibag/FilesActivity.java
UTF-8
4,276
2.03125
2
[]
no_license
package com.tinyminds.ibag; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class FilesActivity extends AppCompatActivity { private List<File> mListFiles; private FileAdapter mAdapter; SharedPreferences shared; @SuppressLint("SourceLockedOrientationActivity") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_files); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Электронная библиотека"); setSupportActionBar(toolbar); // add back arrow to toolbar if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } ListView files = findViewById(R.id.files); mListFiles = new ArrayList<File>(); mAdapter = new FileAdapter(this, mListFiles); files.setAdapter(mAdapter); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(getAssets().open("file.xml")); Element root = doc.getDocumentElement(); root.normalize(); shared = getSharedPreferences("tinyminds", Context.MODE_PRIVATE); Integer level = Integer.parseInt(shared.getString("level", "1")); String result = (1 <= level && 4 >= level) ? shared.getString("level", "1") : "1"; NodeList nList = doc.getElementsByTagName("book_"+result); for (int i = 0; i < nList.getLength(); i++) { Node node = nList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element2 = (Element) node; Integer id = Integer.parseInt(getValue("id", element2)); String name = getValue("name", element2); String weight = getValue("weight", element2); String file = getValue("file", element2); mListFiles.add(new File(id, name, file, weight)); } } } catch (Exception e) { e.printStackTrace(); } files.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent mainIntent = new Intent(getApplicationContext(), PdfActivity.class); mainIntent.putExtra("title", mListFiles.get(position).getTitle()); mainIntent.putExtra("file", mListFiles.get(position).getFile()); startActivity(mainIntent); } }); mAdapter.notifyDataSetChanged(); } private static String getValue(String tag, Element element) { NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = nodeList.item(0); return node.getNodeValue(); } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle arrow click here if (item.getItemId() == android.R.id.home) { finish(); // close this activity and return to preview activity (if there is any) } return super.onOptionsItemSelected(item); } }
true
067a68169519ffc88b8a31992f39e52d2f992f97
Java
chamerling/petals-dsb
/modules/dsb-notification-commons/src/main/java/org/petalslink/dsb/notification/commons/api/client/simple/SubscriptionManagerClient.java
UTF-8
301
1.617188
2
[]
no_license
/** * */ package org.petalslink.dsb.notification.commons.api.client.simple; import org.petalslink.dsb.notification.commons.NotificationException; /** * @author chamerling * */ public interface SubscriptionManagerClient { boolean unsubscribe(String uuid) throws NotificationException; }
true
b2f7cb06488ede20810dfdca2f7952783e731c72
Java
SvetlanaMelekhova/Appliances
/src/by/htp/task08/main/Main.java
UTF-8
1,154
2.21875
2
[]
no_license
package by.htp.task08.main; import by.htp.task08.controller.Controller; import by.htp.task08.service.ApplianceService; import by.htp.task08.service.ServiceException; import by.htp.task08.service.ServiceProvider; import by.htp.task08.service.UserService; import by.htp.task08.view.View; public class Main { public static void main(String[] args) throws ServiceException { String command; String response; Controller controller = new Controller(); command = "login login=polk password=12345"; response = controller.doAction(command); View.print(response); View.splitActions(); command = "addProduct Oven : BRAND=ATLANT, PRICE=250, POWER_CONSUMPTION=6000, WEIGHT=13, CAPACITY=34, DEPTH=70, HEIGHT=50, WIDTH=80"; response = controller.doAction(command); View.print(response); View.splitActions(); command = "findProduct Speaker CORD_LENGTH=3"; response = controller.doAction(command); View.print(response); View.splitActions(); command = "findProduct Laptop BATTERY_CAPACITY=3"; response = controller.doAction(command); View.print(response); View.splitActions(); } }
true
59fb75c9c4d25bb3fd386062e3b32b3b9cba97ea
Java
wtfc/springboot-shyt
/wang/src/main/java/com/jc/oa/shyt/web/ToaShytCustomerController.java
UTF-8
13,038
1.984375
2
[]
no_license
package com.jc.oa.shyt.web; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.jc.foundation.domain.PageManager; import com.jc.foundation.web.BaseController; import com.jc.system.CustomException; import com.jc.system.common.util.GlobalContext; import com.jc.system.common.util.MessageUtils; import com.jc.system.common.util.StringUtil; import com.jc.system.security.domain.User; import com.jc.system.security.service.IUserService; import com.jc.system.security.service.impl.UserServiceImpl; import com.jc.system.security.util.ActionLog; import com.jc.oa.shyt.domain.CustomerPeople; import com.jc.oa.shyt.domain.CustomerPeoples; import com.jc.oa.shyt.domain.Customer; import com.jc.oa.shyt.domain.Visit; import com.jc.oa.shyt.service.ICustomerPeopleService; import com.jc.oa.shyt.service.ICustomerService; import com.jc.oa.shyt.service.IVisitService; /** * @author mrb * @version 客户信息表 */ @Controller @RequestMapping(value="/shyt/toaShytCustomer") public class ToaShytCustomerController extends BaseController{ @Autowired private ICustomerService toaShytCustomerService; @Autowired private IUserService userService; @Autowired private IVisitService visitService; @Autowired private ICustomerPeopleService customerPeopleService; public ToaShytCustomerController(){ } /** * 保存方法 * @param TimeSet timeSet 实体类 * @param BindingResult result 校验结果 * @return success 是否成功, errorMessage错误信息 * @throws Exception * @author */ @RequestMapping(value = "save.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="save",operateDescribe="对客户信息表进行发起操作") public Map<String,Object> save(Customer toaShytCustomer,CustomerPeoples customerPeople,BindingResult result, HttpServletRequest request) throws Exception{ Map<String, Object> resultMap = validateBean(result); if (resultMap.size() > 0) { return resultMap; } // 验证token resultMap = validateToken(request); if (resultMap.size() > 0) { return resultMap; } if(!"false".equals(resultMap.get("success"))){ toaShytCustomerService.savePeople(toaShytCustomer, customerPeople); resultMap.put("success", "true"); resultMap.put(GlobalContext.RESULT_SUCCESSMESSAGE, MessageUtils.getMessage("JC_SYS_001")); resultMap.put(GlobalContext.SESSION_TOKEN, getToken(request)); } return resultMap; } /** * 修改方法 * @param TimeSet timeSet 实体类 * @return Integer 更新的数目 * @author */ @RequestMapping(value="update.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="update",operateDescribe="对客户信息表进行更新操作") public Map<String, Object> update(Customer toaShytCustomer, BindingResult result, HttpServletRequest request) throws Exception{ Map<String, Object> resultMap = validateBean(result); if (resultMap.size() > 0) { return resultMap; } if(toaShytCustomer.getEndIntel()!=null){ toaShytCustomer.setExtStr1("1"); } Integer flag = toaShytCustomerService.update(toaShytCustomer); if (flag == 1) { resultMap.put(GlobalContext.RESULT_SUCCESS, "true"); resultMap.put(GlobalContext.RESULT_SUCCESSMESSAGE, MessageUtils.getMessage("JC_SYS_003")); } String token = getToken(request); resultMap.put(GlobalContext.SESSION_TOKEN, token); return resultMap; } /** * 修改方法(维护专员) * @param TimeSet timeSet 实体类 * @return Integer 更新的数目 * @author */ @RequestMapping(value="updateTrade.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="updateTrade",operateDescribe="对客户信息表进行更新操作") public Map<String, Object> updateTrade(Customer toaShytCustomer, BindingResult result, HttpServletRequest request) throws Exception{ Map<String, Object> resultMap = validateBean(result); if (resultMap.size() > 0) { return resultMap; } if(toaShytCustomer.getEndIntel()!=null){ toaShytCustomer.setExtStr1("1"); } Visit visit = new Visit(); CustomerPeople customerPeople = new CustomerPeople(); User user=new User(); user.setId(Long.valueOf(toaShytCustomer.getCreateUser())); User newUser=userService.get(user); toaShytCustomer.setTradeUser(newUser.getDisplayName()); Integer flag = toaShytCustomerService.update(toaShytCustomer); if (flag == 1) { //修改回访信息 visit.setCreateUser(Long.valueOf(toaShytCustomer.getCreateUser())); visit.setCustomerId(Integer.valueOf(toaShytCustomer.getId().toString())); visitService.updateCustomer(visit); customerPeople.setCreateUser(Long.valueOf(toaShytCustomer.getCreateUser())); customerPeople.setCustomerId(Integer.valueOf(toaShytCustomer.getId().toString())); customerPeopleService.updatePeople(customerPeople); resultMap.put(GlobalContext.RESULT_SUCCESS, "true"); resultMap.put(GlobalContext.RESULT_SUCCESSMESSAGE, MessageUtils.getMessage("JC_SYS_003")); } String token = getToken(request); resultMap.put(GlobalContext.SESSION_TOKEN, token); return resultMap; } /** * 获取单条记录方法 * @param TimeSet timeSet 实体类 * @return TimeSet 查询结果 * @throws Exception * @author */ @RequestMapping(value="get.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="get",operateDescribe="对客户信息表进行单条查询操作") public Customer get(Customer toaShytCustomer,HttpServletRequest request) throws Exception{ return toaShytCustomerService.get(toaShytCustomer); } /** * 分页查询方法 * @param TimeSet timeSet 实体类 * @param PageManager page 分页实体类 * @return PagingBean 查询结果 * @throws Exception * @author * @throws CustomException */ @RequestMapping(value="manageList.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="get",operateDescribe="客户信息表分页查询") public PageManager manageList(Customer toaShytCustomer,PageManager page,HttpServletRequest request) throws UnsupportedEncodingException, CustomException{ //默认排序 if(StringUtil.isEmpty(toaShytCustomer.getOrderBy())) { toaShytCustomer.addOrderByFieldDesc("t.CREATE_DATE"); } // String deptName = SystemSecurityUtils.getUser().getDeptName(); // if(!SystemSecurityUtils.getUser().getIsLeader().equals("1")){ // equipment.setContact(deptName); // } PageManager page_ = toaShytCustomerService.query(toaShytCustomer, page); return page_; } /** * 权限分页查询方法 * @param TimeSet timeSet 实体类 * @param PageManager page 分页实体类 * @return PagingBean 查询结果 * @throws Exception * @author * @throws CustomException */ @RequestMapping(value="managePermissionList.action") @ResponseBody @ActionLog(operateModelNm="客户信息表",operateFuncNm="get",operateDescribe="客户信息表分页查询") public PageManager managePermissionList(Customer toaShytCustomer,PageManager page,HttpServletRequest request) throws UnsupportedEncodingException, CustomException{ //默认排序 if(StringUtil.isEmpty(toaShytCustomer.getOrderBy())) { toaShytCustomer.addOrderByFieldDesc("t.CREATE_DATE"); } // String deptName = SystemSecurityUtils.getUser().getDeptName(); // if(!SystemSecurityUtils.getUser().getIsLeader().equals("1")){ // equipment.setContact(deptName); // } PageManager page_ = toaShytCustomerService.queryForPermission(toaShytCustomer, page); return page_; } /** * 跳转方法 * @return String 跳转的路径 * @throws Exception * @author */ @RequestMapping(value="manage.action") @ActionLog(operateModelNm="客户信息表",operateFuncNm="manage",operateDescribe="对客户信息表进行跳转操作") public String manage(Model model,HttpServletRequest request) throws Exception{ return "shyt/customer/toaShytCustomer"; } /** * 删除方法 * @param TimeSet timeSet 实体类 * @param String ids 删除的多个主键 * @return Integer 成功删除 * @throws Exception * @author */ @RequestMapping(value="deleteByIds.action") @ResponseBody @ActionLog(operateModelNm="客户信息表表",operateFuncNm="deleteByIds",operateDescribe="对客户信息表表进行删除") public Map<String, Object> deleteByIds(Customer toaShytCustomer,String ids, HttpServletRequest request) throws Exception{ Map<String, Object> resultMap = new HashMap<String, Object>(); toaShytCustomer.setPrimaryKeys(ids.split(",")); if(toaShytCustomerService.deleteByIds(toaShytCustomer) != 0){ resultMap.put(GlobalContext.RESULT_SUCCESS, "true"); resultMap.put(GlobalContext.RESULT_SUCCESSMESSAGE, MessageUtils.getMessage("JC_SYS_005")); } else { resultMap.put(GlobalContext.RESULT_SUCCESS, "false"); resultMap.put(GlobalContext.RESULT_ERRORMESSAGE, MessageUtils.getMessage("JC_SYS_006")); } return resultMap; } /** * @description 新增与修改方法跳转页面 * @return String form对话框所在位置 * @throws Exception * @author * @version 2015-08-03 */ @RequestMapping(value="loadForm.action") @ActionLog(operateModelNm="客户信息表表",operateFuncNm="loadForm",operateDescribe="对客户信息表表跳转") public String loadForm(Model model,HttpServletRequest request) throws Exception{ Map<String, Object> map = new HashMap<String, Object>(); String token = getToken(request); map.put(GlobalContext.SESSION_TOKEN, token); model.addAttribute("data", map); String id= request.getParameter("id"); if(!StringUtil.isEmpty(id)){ model.addAttribute("Id", id); } return "shyt/customer/toaShytCustomerForm"; } /** * 跳转方法 * @return String 跳转到查看所有信息 * @throws Exception * @author */ @RequestMapping(value="viewPage.action") @ActionLog(operateModelNm="客户信息表",operateFuncNm="manage",operateDescribe="对客户信息表进行跳转操作") public String viewPage(Model model,HttpServletRequest request) throws Exception{ String id= request.getParameter("id"); model.addAttribute("Id", id); String company = request.getParameter("company"); model.addAttribute("company", company); return "shyt/customer/viewPage"; } /** * 跳转方法 * @return String 跳转综合查询客户信息list表 * @throws Exception * @author */ @RequestMapping(value="viewCustomer.action") @ActionLog(operateModelNm="客户信息表",operateFuncNm="manage",operateDescribe="对客户信息表进行跳转操作") public String viewCustomer(Model model,HttpServletRequest request) throws Exception{ return "shyt/customer/viewCustomer"; } /** * 终止客户跳转方法 * @return String 跳转综合查询客户信息list表 * @throws Exception * @author */ @RequestMapping(value="zhongzhiCustomer.action") @ActionLog(operateModelNm="客户信息表",operateFuncNm="manage",operateDescribe="对终止客户信息表进行跳转操作") public String zhongzhiCustomer(Model model,HttpServletRequest request) throws Exception{ return "shyt/customer/zhongzhiCustomer"; } /** * @return String 跳转客户信息首页显示 * @throws Exception * @author */ @RequestMapping(value="top.action") @ActionLog(operateModelNm="客户信息表",operateFuncNm="manage",operateDescribe="对客户信息表进行跳转操作") public String top(Model model,HttpServletRequest request) throws Exception{ return "sys/customerSystem"; } /** * @description 新增与修改方法跳转页面 * @return String form对话框所在位置 * @throws Exception * @author * @version 2015-08-03 */ @RequestMapping(value="loadForm2.action") @ActionLog(operateModelNm="客户信息表表",operateFuncNm="loadForm",operateDescribe="对客户信息表表跳转") public String loadForm2(Customer toaShytCustomer,Model model,HttpServletRequest request) throws Exception{ String id= request.getParameter("id"); if(!StringUtil.isEmpty(id)){ toaShytCustomer.setId(Long.valueOf(id)); } Customer customer = toaShytCustomerService.get(toaShytCustomer); model.addAttribute("customer", customer); return "shyt/customer/viewCustomerFrom"; } /** * @description 基本信息默认跳转方法 * @param HttpServletRequest request * @return /WebRoot/WEB-INF/web/doc/template/official.jsp * @throws Exception * @author 吕桢卓 * @version 2014-09-05 */ @RequestMapping(value="officialjump.action") @ActionLog(operateModelNm="基本信息",operateFuncNm="officialjump",operateDescribe="基本信息默认跳转") public String personalOfficeSkip(HttpServletRequest request) throws Exception{ return "sys/official"; } }
true
c4e504b8d156efdcf6fd0bd59c4566d5661d8fec
Java
grodtron/coen445-project
/src/coen445/project/common/udp/RegisteredMessage.java
UTF-8
1,943
3.046875
3
[]
no_license
package coen445.project.common.udp; import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; public class RegisteredMessage extends UdpMessage { private int requestNumber; private String name; private SocketAddress registeredAddress; public RegisteredMessage(UdpContext context, byte[] rawdata, InetSocketAddress address) { super(context, rawdata, address); // Get the request number requestNumber = (int)rawdata[1]; // Get the name. Strings are prefixed with their length, as this is // the most convenient method for Java. int nameBegin = 3; int nameLength = rawdata[2]; name = new String(rawdata, nameBegin, nameLength); // Retrieve the IP Address. It is the next 4 bytes after the string // ends int ipAddrBegin = nameBegin + nameLength; int ipAddrEnd = ipAddrBegin + 4; InetAddress ipAddress; try { ipAddress = Inet4Address.getByAddress(Arrays.copyOfRange(rawdata, ipAddrBegin, ipAddrEnd)); } catch (UnknownHostException e) { ipAddress = null; System.err.println("Couldn't get IP Address: " + e); } int portBegin = ipAddrEnd; int portEnd = ipAddrEnd + 1; int port = ((0xff & rawdata[portBegin]) << 8) | (0xff & rawdata[portEnd]); registeredAddress = new InetSocketAddress(ipAddress, port); System.out.println("Created Registered message: " + this); } public RegisteredMessage(RegisterMessage msg){ this(msg.context, Arrays.copyOf(msg.getData(), msg.getData().length), msg.getAddress()); data[0] = (byte)UdpMessage.OpCodes.REGISTERED.ordinal(); } @Override public Collection<? extends UdpMessage> onReceive() { return context.process(this); } @Override public String toString(){ return requestNumber + " " + name + " " + registeredAddress; } }
true
fb310356bcf2c50ee8f09367aa91c5b4ab4499cf
Java
lifang/ZF_Agent_A_Pad
/src/com/comdo/zf_agent_a_pad/fragment/Staffmanagr.java
UTF-8
6,635
1.710938
2
[]
no_license
package com.comdo.zf_agent_a_pad.fragment; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import com.comdo.zf_agent_a_pad.activity.CreatStaff; import com.comdo.zf_agent_a_pad.activity.StallmanagerDetail; import com.comdo.zf_agent_a_pad.adapter.StaffmanagerAdapter; import com.comdo.zf_agent_a_pad.common.CommonUtil; import com.comdo.zf_agent_a_pad.common.HttpCallback; import com.comdo.zf_agent_a_pad.common.Page; import com.comdo.zf_agent_a_pad.entity.StaffmanagerEntity; import com.comdo.zf_agent_a_pad.util.Config; import com.comdo.zf_agent_a_pad.util.MyApplication; import com.comdo.zf_agent_a_pad.util.Tools; import com.comdo.zf_agent_a_pad.util.XListView; import com.comdo.zf_agent_a_pad.util.XListView.IXListViewListener; import com.epalmpay.agentPad.R; import com.google.gson.reflect.TypeToken; public class Staffmanagr extends Fragment implements OnClickListener, IXListViewListener { private View view; public static List<StaffmanagerEntity> datastaff; private BaseAdapter staffmanageradapter; private XListView xxlistview; private Button btn_creatstaff; public static Handler myHandler; private boolean isrefersh = false; private int page = 0; private int rows = 10; private int agentId = MyApplication.NewUser.getAgentId(); private Activity mActivity; private boolean noMoreData = false; private String pullType = "loadData"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // view = inflater.inflate(R.layout.f_main,container,false); if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.staffmanagr, container, false); init(); } catch (InflateException e) { } return view; } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); if (datastaff.size() != 0) { datastaff.clear(); } getData(); myHandler = new Handler() { public void handleMessage(android.os.Message msg) { switch (msg.what) { case 0: break; case 1: Intent intent = new Intent(getActivity(), StallmanagerDetail.class); intent.putExtra("idd", datastaff .get(StaffmanagerAdapter.pp).getId()); startActivity(intent); break; case 2: delectone(); break; default: break; } } }; } protected void delectone() { final com.comdo.zf_agent_a_pad.util.AlertDialog ad = new com.comdo.zf_agent_a_pad.util.AlertDialog( getActivity()); ad.setTitle("提示"); ad.setMessage("确认删除?"); ad.setPositiveButton("取消", new OnClickListener() { @Override public void onClick(View arg0) { ad.dismiss(); } }); ad.setNegativeButton("确定", new OnClickListener() { @Override public void onClick(final View arg0) { Config.delectStaff(getActivity(), datastaff.get(StaffmanagerAdapter.pp).getId(), agentId, new HttpCallback(getActivity()) { @Override public void onSuccess(Object data) { CommonUtil.toastShort(getActivity(), "删除成功"); page = 0; datastaff.clear(); getData(); } @Override public TypeToken getTypeToken() { return null; } }); ad.dismiss(); } }); } private void getData() { Config.getStaffList(mActivity, agentId, page + 1, rows, new HttpCallback<Page<StaffmanagerEntity>>(mActivity) { @Override public void onSuccess(Page<StaffmanagerEntity> data) { if (null == data || data.getList().size() <= 0) noMoreData = true; if (pullType.equals("onRefresh")) { datastaff.clear(); } datastaff.addAll(data.getList()); page++; staffmanageradapter.notifyDataSetChanged(); } @Override public void preLoad() { } @Override public void postLoad() { loadFinished(); } @Override public TypeToken<Page<StaffmanagerEntity>> getTypeToken() { return new TypeToken<Page<StaffmanagerEntity>>() { }; } }); } private void init() { btn_creatstaff = (Button) view.findViewById(R.id.btn_creatstaff); datastaff = new ArrayList<StaffmanagerEntity>(); staffmanageradapter = new StaffmanagerAdapter(datastaff, getActivity() .getBaseContext()); xxlistview = (XListView) view.findViewById(R.id.list); xxlistview.setPullLoadEnable(true); xxlistview.setXListViewListener(this); xxlistview.setDivider(null); xxlistview.setAdapter(staffmanageradapter); btn_creatstaff.setOnClickListener(this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_creatstaff: Intent intent = new Intent(getActivity(), CreatStaff.class); startActivity(intent); break; default: break; } } @Override public void onRefresh() { if (!Tools.isConnect(getActivity())) { CommonUtil.toastShort(getActivity(), "网络异常"); return; } page = 0; datastaff.clear(); pullType = "onRefresh"; noMoreData = false; xxlistview.setPullLoadEnable(true); getData(); } private void loadFinished() { xxlistview.stopRefresh(); xxlistview.stopLoadMore(); xxlistview.setRefreshTime(Tools.getHourAndMin()); } @Override public void onLoadMore() { if (!Tools.isConnect(getActivity())) { CommonUtil.toastShort(getActivity(), "网络异常"); return; } pullType = "onLoadMore"; if (noMoreData) { xxlistview.setPullLoadEnable(false); xxlistview.stopLoadMore(); CommonUtil.toastShort(getActivity(), getResources().getString(R.string.no_more_data)); } else { getData(); } } }
true
d3511ded48df1a535dddbc0fa6d7730d4bbc4ca7
Java
BGCX262/zsey-svn-to-git
/trunk/ducrm/src/cn/com/kington/webapp/security/SecurityFilter.java
GB18030
1,689
2.171875
2
[]
no_license
package cn.com.kington.webapp.security; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import cn.com.kington.common.Constants; import cn.com.kington.utils.FunctionTools; public class SecurityFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { HttpServletRequest request=(HttpServletRequest)arg0; HttpServletResponse response=(HttpServletResponse)arg1; HttpSession session=request.getSession(); String ctxpath = request.getContextPath(); String uri = request.getRequestURI().substring(ctxpath.length()); if( !uri.endsWith(".css") && !uri.endsWith(".gif") && !uri.endsWith(".png") && !uri.endsWith(".jpg") && !uri.endsWith(".jpeg") && !uri.endsWith(".bmp") && !uri.endsWith(".gif") && !uri.endsWith(".js") && !uri.endsWith("/login-index.jsp") && !uri.endsWith("/image.jsp") ){ if(session.getAttribute(Constants.DEFAULT_USER_LOGIN)==null){ FunctionTools.showMsgAndOutFrame(response, "ȵ½ִиò", request.getContextPath()+"/login/index.jhtml"); return; } } chain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { } }
true
d8043b839a9a4ed145f60ab0082bd6cc7a6c1a92
Java
OmkarKirpan/java-course
/src/net/azib/java/lessons/io/PerformanceTimer.java
UTF-8
740
3.21875
3
[]
no_license
package net.azib.java.lessons.io; import java.io.File; import java.io.IOException; /** * PerformanceTimer * * @author anton */ public class PerformanceTimer { public static long measureTime(FileCopier copier, File src, File dest) throws IOException { long t = System.currentTimeMillis(); copier.copy(src, dest); return System.currentTimeMillis() - t; } public static void main(String[] args) throws IOException { measureTime(new DummyFileCopier(), new File("build.xml"), File.createTempFile("dummy", null)); } private static class DummyFileCopier implements FileCopier { @Override public void copy(File src, File dest) throws IOException { System.out.println("Dummy copy of " + src + " to " + dest); } } }
true
6646d61c1de8dd161c9afe46a2f8a12d5e3f2df4
Java
mohamedmohamedtaha/Am_Store
/app/src/main/java/com/imagine/mohamedtaha/store/model/TableCategories.java
UTF-8
1,486
2.328125
2
[]
no_license
package com.imagine.mohamedtaha.store.model; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity public class TableCategories { @PrimaryKey(autoGenerate = true) private int id_category; private String name_category; private String notes; private String createdDate; private String createdTime; public String getCreatedDate() { return createdDate; } public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } public String getCreatedTime() { return createdTime; } public void setCreatedTime(String createdTime) { this.createdTime = createdTime; } public int getId_category() { return id_category; } public void setId_category(int id_category) { this.id_category = id_category; } public String getName_category() { return name_category; } public void setName_category(String name_category) { this.name_category = name_category; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public TableCategories(int id_category, String name_category, String notes, String createdDate, String createdTime) { this.id_category = id_category; this.name_category = name_category; this.notes = notes; this.createdDate = createdDate; this.createdTime = createdTime; } }
true
3143c167052c426549021c4ecd3b1c61f7c7dbac
Java
can-ok/RestaurantApp
/restapi/src/main/java/com/resturant/restapi/builder/MediaDtoBuilder.java
UTF-8
785
2.59375
3
[]
no_license
package com.resturant.restapi.builder; import com.resturant.restapi.dto.MediaDto; public class MediaDtoBuilder extends Builder{ private Integer id; private String name; private byte[] fileContent; @Override public MediaDto build() { MediaDto mediaDto=new MediaDto(); mediaDto.setId(this.id); mediaDto.setName(this.name); mediaDto.setFileContent(this.fileContent); return mediaDto; } @Override public MediaDtoBuilder id(int id) { this.id=id; return this; } public MediaDtoBuilder fileContent(byte[] fileContent){ this.fileContent=fileContent; return this; } public MediaDtoBuilder name(String name){ this.name=name; return this; } }
true
ab28dbf70ab1f2e999e678104483eb3f4ba54fbb
Java
whatafree/JCoffee
/benchmark/bigclonebenchdata_partial/5439181.java
UTF-8
293
2.34375
2
[]
no_license
class c5439181 { private String hash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } }
true
e77f95d7fef5ced3aa835dc49b98dea13460e861
Java
softpo/miaojie
/TestMJ/src/com/test/testmj/MainActivity.java
UTF-8
8,675
1.960938
2
[]
no_license
package com.test.testmj; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.OnScrollListener; import android.util.TypedValue; import com.test.testmj.MyAdapter.ItemViewHolder; public class MainActivity extends Activity implements OnRefreshListener{ private int item_normal_height; private int item_max_height; private float item_normal_alpha; private float item_max_alpha; private float alpha_d; private float item_normal_font_size; private float item_max_font_size; private float font_size_d; private List<Integer> imgs = Arrays.asList(R.drawable.wall01, R.drawable.wall02, R.drawable.wall03, R.drawable.wall04, R.drawable.wall05, R.drawable.wall06, R.drawable.wall07, R.drawable.wall08, R.drawable.wall09, R.drawable.wall10); private List<Integer> cacheList = new ArrayList<Integer>(); private SwipeRefreshLayout mSwipeRefreshWidget; private RecyclerView mRecyclerView; private LinearLayoutManager layoutManager; private MyAdapter adapter; private ItemViewHolder viewHolder; private RecyclerView.ViewHolder firstViewHolder,secondViewHolder,threeViewHolder,lastViewHolder; private int lastVisibleItem; public static final int DATA_REFRESH = 0; public static final int DATA_LOAD_MORE = 1; private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case DATA_REFRESH: mSwipeRefreshWidget.setRefreshing(false); adapter.clear(); adapter.setFirst(true); cacheList.clear(); updateData(); break; case DATA_LOAD_MORE: updateData(); break; default: break; } } }; private void updateData() { cacheList.addAll(imgs); adapter.updateData(cacheList); adapter.notifyDataSetChanged(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); item_max_height = (int) getResources().getDimension(R.dimen.item_max_height); item_normal_height = (int) getResources().getDimension(R.dimen.item_normal_height); item_normal_font_size = getResources().getDimension(R.dimen.item_normal_font_size); item_max_font_size = getResources().getDimension(R.dimen.item_max_font_size); item_normal_alpha = getResources().getFraction(R.fraction.item_normal_mask_alpha, 1, 1); item_max_alpha = getResources().getFraction(R.fraction.item_max_mask_alpha, 1, 1); font_size_d = item_max_font_size - item_normal_font_size; alpha_d = item_max_alpha - item_normal_alpha; mSwipeRefreshWidget = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); mSwipeRefreshWidget.setColorSchemeResources(R.color.color1, R.color.color2, R.color.color3, R.color.color4); mSwipeRefreshWidget.setOnRefreshListener(this); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); layoutManager=new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(false); adapter = new MyAdapter(this, cacheList); mRecyclerView.setAdapter(adapter); // View moreView = getLayoutInflater().inflate(R.layout.footer_more, null); // TextView more = (TextView) moreView.findViewById(R.id.more); // more.getLayoutParams().height = DeviceUtils.getScreenHeight(this) - // item_max_height; // RecyclerViewUtils.setFooterView(mRecyclerView, moreView); mRecyclerView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) { handler.sendEmptyMessageDelayed(DATA_LOAD_MORE, 2000); } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); firstViewHolder = recyclerView .findViewHolderForPosition(layoutManager.findFirstVisibleItemPosition()); secondViewHolder = recyclerView .findViewHolderForPosition(layoutManager.findFirstCompletelyVisibleItemPosition()); threeViewHolder = recyclerView .findViewHolderForPosition(layoutManager.findFirstCompletelyVisibleItemPosition() + 1); lastViewHolder = recyclerView .findViewHolderForPosition(layoutManager.findLastVisibleItemPosition()); lastVisibleItem = layoutManager.findLastVisibleItemPosition(); if (firstViewHolder != null && firstViewHolder instanceof ItemViewHolder) { viewHolder = (ItemViewHolder) firstViewHolder; if (viewHolder.itemView.getLayoutParams().height - dy <= item_max_height && viewHolder.itemView.getLayoutParams().height - dy >= item_normal_height) { viewHolder.itemView.getLayoutParams().height = viewHolder.itemView.getLayoutParams().height - dy; viewHolder.mark.setAlpha(viewHolder.mark.getAlpha() - dy * alpha_d / item_normal_height); viewHolder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewHolder.text.getTextSize() - dy * font_size_d / item_normal_height); viewHolder.itemView.setLayoutParams(viewHolder.itemView.getLayoutParams()); } } if (secondViewHolder != null && secondViewHolder instanceof ItemViewHolder) { viewHolder = (ItemViewHolder) secondViewHolder; if (viewHolder.itemView.getLayoutParams().height + dy <= item_max_height && viewHolder.itemView.getLayoutParams().height + dy >= item_normal_height) { viewHolder.itemView.getLayoutParams().height = viewHolder.itemView.getLayoutParams().height + dy; viewHolder.mark.setAlpha(viewHolder.mark.getAlpha() + dy * alpha_d / item_normal_height); viewHolder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, viewHolder.text.getTextSize() + dy * font_size_d / item_normal_height); viewHolder.itemView.setLayoutParams(viewHolder.itemView.getLayoutParams()); } } if (threeViewHolder != null && threeViewHolder instanceof ItemViewHolder) { viewHolder = (ItemViewHolder) threeViewHolder; viewHolder.mark.setAlpha(item_normal_alpha); viewHolder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, item_normal_font_size); viewHolder.itemView.getLayoutParams().height = item_normal_height; viewHolder.itemView.setLayoutParams(viewHolder.itemView.getLayoutParams()); } if (lastViewHolder != null && lastViewHolder instanceof ItemViewHolder) { viewHolder = (ItemViewHolder) lastViewHolder; viewHolder.mark.setAlpha(item_normal_alpha); viewHolder.text.setTextSize(TypedValue.COMPLEX_UNIT_PX, item_normal_font_size); viewHolder.itemView.getLayoutParams().height = item_normal_height; viewHolder.itemView.setLayoutParams(viewHolder.itemView.getLayoutParams()); } } }); // mSwipeRefreshWidget.setRefreshing(true); handler.sendEmptyMessageDelayed(DATA_REFRESH, 2000); } @Override public void onRefresh() { handler.sendEmptyMessageDelayed(DATA_REFRESH, 2000); } }
true
9acf22e57bbe2c0d0a8ee3e4a1bf1e2bd6fc0d33
Java
cpwk/news-api
/src/main/java/com/maidao/edu/news/springbootdemo/api/article/controller/AdmArticleController.java
UTF-8
2,003
1.992188
2
[]
no_license
package com.maidao.edu.news.springbootdemo.api.article.controller; import com.maidao.edu.news.springbootdemo.api.article.model.Article; import com.maidao.edu.news.springbootdemo.api.article.qo.ArticleQo; import com.maidao.edu.news.springbootdemo.api.article.service.IArticleService; import com.maidao.edu.news.springbootdemo.common.controller.Action; import com.maidao.edu.news.springbootdemo.common.controller.ActionSession; import com.maidao.edu.news.springbootdemo.common.controller.BaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * 创建人:chenpeng * 创建时间:2019-08-05 10:05 * Version 1.8.0_211 * 项目名称:news * 类名称:AdmArticleController * 类描述:Article控制层接口 **/ @Controller @RequestMapping("/adm/article") public class AdmArticleController extends BaseController { @Autowired private IArticleService articleService; @RequestMapping(value = "/save") @Action(session = ActionSession.ADMIN) public ModelAndView save(String article) throws Exception { articleService.save(parseModel(article, new Article())); return feedback(null); } @RequestMapping(value = "/remove") @Action(session = ActionSession.ADMIN) public ModelAndView remove(Integer id) throws Exception { articleService.remove(id); return feedback(null); } @RequestMapping(value = "/article") @Action(session = ActionSession.ADMIN) public ModelAndView article(Integer id) throws Exception { return feedback(articleService.article(id)); } @RequestMapping(value = "/articles") @Action(session = ActionSession.ADMIN) public ModelAndView articles(String articleQo) throws Exception { return feedback(articleService.articles(parseModel(articleQo, new ArticleQo()), true)); } }
true
e725a2226427fd7c3f90bdac414b9ae981e7128f
Java
maryem30/PFA
/stage_back/src/main/java/stage/controller/UserController.java
UTF-8
2,165
2.15625
2
[]
no_license
package stage.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import stage.dao.UserRepository; import stage.dao.UserRepository; import stage.entities.user; import stage.service.UserService; @CrossOrigin("*") @RestController @RequestMapping("/user/") public class UserController { private UserService userService; @Autowired private UserRepository userRepository; @Autowired public UserController(UserService userService) { super(); this.userService = userService; } @GetMapping(value = "/all") public List<user> findUser() { return userService.findAll(); } @GetMapping(value = "/{id}") public Optional<user> findUser(@PathVariable Long id) { return userService.findUser(id); } @GetMapping(value = "/page") public Page<user> showPage(@RequestParam(defaultValue = "1") int page) { return userRepository.findAll(new PageRequest(page, 10)); } @PostMapping public void addUser(@PathVariable(name = "id") Long id, @RequestBody user user) { user.setId(id); userService.addUser(user); } @PutMapping("/{id}") public void updateUser(@PathVariable(name = "id") Long id, @RequestBody user user) { user.setId(id); userService.updateUser(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable(name = "id") Long id) { userService.delete(id); } }
true
0706757ba811edaf05e25a24cfd6b2aae5bea152
Java
kubastepaniak/Java2048
/application/Tile.java
UTF-8
2,121
2.828125
3
[]
no_license
package application; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; public class Tile extends StackPane { public static final int TILE_SIZE = 125; boolean taken; int value; int verticalIndex; int horizontalIndex; Text text; Rectangle background; public Tile(int hor, int ver) { this.value = 0; this.horizontalIndex = hor; this.verticalIndex = ver; this.taken = false; setBG(); } private void setBG() { if(taken) { getChildren().clear(); background = new Rectangle(0, 0, TILE_SIZE, TILE_SIZE); background.setFill(getRectColor()); text = new Text(String.valueOf(value)); if(value < 1000) { text.setFont(new Font(50)); } else { text.setFont(new Font(30)); } text.setStyle("-fx-font-weight: bold"); text.setFill(getTextColor()); getChildren().addAll(background, text); } else { getChildren().clear(); background = new Rectangle(0 , 0, TILE_SIZE, TILE_SIZE); background.setFill(Color.web("#cdc1b4")); getChildren().add(background); } } private Color getTextColor() { if(value == 2 || value == 4) { return Color.rgb(120, 110, 100); } else { return Color.WHITE; } } private Color getRectColor() { switch(value) { case 2: return Color.web("#eee4da"); case 4: return Color.web("#ede0c8"); case 8: return Color.web("#f2b179"); case 16: return Color.web("#f59563"); case 32: return Color.web("#f67c5f"); case 64: return Color.web("#f65e3b"); case 128: return Color.web("#edcf72"); case 256: case 512: case 1024: case 2048: return Color.web("#edc850"); default: return Color.WHITE; } } public void occupy() { taken = true; value = 2; setBG(); } public void occupy(int points) { taken = true; value = points; setBG(); } public void free() { taken = false; value = 0; setBG(); } public void doubleValue() { this.value *= 2; Main.score += value; Interface.updateScore(); setBG(); if(this.value == 2048) { Main.screens.setScreen("win"); } } }
true
b8462b344c8079df38e590697ad1106987752e5e
Java
Thpffcj/DataStructures-and-Algorithms
/Java/src/algorithms/leetcodecn/linkedList/SwapNodesInPairs.java
UTF-8
1,900
3.921875
4
[]
no_license
package algorithms.leetcodecn.linkedList; import algorithms.leetcodecn.ListNode; /** * Created by thpffcj on 2020/1/31. * * 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 * 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 * * 示例: * 给定 1->2->3->4, 你应该返回 2->1->4->3. */ public class SwapNodesInPairs { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode guard = new ListNode(-1); guard.next = head; ListNode pre = guard; ListNode last = head.next; while (last != null) { pre.next = last; last = last.next; pre.next.next = head; head.next = last; pre = head; head = head.next; if (last != null) { last = last.next; } } return guard.next; } public ListNode swapPairs2(ListNode head) { if ((head == null) || (head.next == null)) { return head; } ListNode firstNode = head; ListNode secondNode = head.next; firstNode.next = swapPairs2(secondNode.next); secondNode.next = firstNode; return secondNode; } public ListNode swapPairs3(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode prevNode = dummy; while ((head != null) && (head.next != null)) { ListNode firstNode = head; ListNode secondNode = head.next; prevNode.next = secondNode; firstNode.next = secondNode.next; secondNode.next = firstNode; prevNode = firstNode; head = firstNode.next; } return dummy.next; } }
true
4b2014f84e94d95830cfa8eeda33dad19b95119b
Java
katrova/ProgrammingPatternsFactoryBuilder
/src/com/company/IGeometry.java
UTF-8
381
2.6875
3
[]
no_license
package com.company; /** * @author Vasylkivska Kateryna KNTEU * * @varsion 1.0 17.06.2020 * * Classname IGeometry * * Description: Interface * * Module 2 task 4 * * Develop for your class 1. Factory. 2. Abstract factory. 3. Create a class Student - 25 fields. 4. Create a builder for the class Student */ public interface IGeometry { double getArea(); double getPerimeter(); }
true
8daffec797e016927ffc042bcb42ccf85e97cc9a
Java
sSUNIL96/hibernate
/src/abstractclass/u.java
UTF-8
66
1.6875
2
[]
no_license
package abstractclass; public interface u { void pq(); }
true
2d6c40b983be8db8e877ec286934b6cdd56a82c2
Java
jawadn/Tcheckit-android
/src/com/fortutech/tcheckit/ejb/sessions/Mission.java
UTF-8
7,527
2.015625
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package com.fortutech.tcheckit.ejb.sessions; import java.util.Hashtable; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import com.tcheckit.utils.SoapUtils; public class Mission extends com.fortutech.tcheckit.ejb.sessions.EntityMother implements org.ksoap2.serialization.KvmSerializable { private java.lang.Long id; private com.fortutech.tcheckit.ejb.sessions.PhotoInstruction[] listPhotoInstruction; private com.fortutech.tcheckit.ejb.sessions.Media[] listPhotosProducts; private com.fortutech.tcheckit.ejb.sessions.Question[] listQuestions; private com.fortutech.tcheckit.ejb.sessions.Sign[] listSign; private com.fortutech.tcheckit.ejb.sessions.Brand oneBrand; private java.lang.String oneDescription; private java.lang.String oneMoreText; private com.fortutech.tcheckit.ejb.sessions.PageContent onePageContentMain; private java.lang.Float onePrice; private java.lang.String oneTitle; private int distance = 0; public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public Mission() { super(); } public Mission(Mission mi) { this.distance = mi.distance; this.id = mi.id; this.listPhotoInstruction = mi.listPhotoInstruction; this.listPhotosProducts = mi.listPhotosProducts; this.listQuestions = mi.listQuestions; this.listSign = mi.listSign; this.oneBrand = mi.oneBrand; this.oneDescription = mi.oneDescription; this.oneMoreText = mi.oneMoreText; this.onePageContentMain = mi.onePageContentMain; this.onePrice = mi.onePrice; this.oneTitle = mi.oneTitle; } public Mission(SoapObject so) { super(so); this.setId(SoapUtils.getSoapLong(so,"id")); this.setListPhotoInstruction(PhotoInstruction.parse(so,"listPhotoInstruction")); this.setListPhotosProducts(Media.parse(so,"listPhotosProducts")); this.setListQuestions(Question.parse(so, "listQuestions")); this.setListSign(Sign.parse(so, "listSign")); this.setOneBrand(new Brand(SoapUtils.getSoapObject(so, "oneBrand"))); this.setOneDescription(SoapUtils.getSoapString(so,"oneDescription")); this.setOneFlag(new Flag(SoapUtils.getSoapString(so,"oneFlag"))); this.setOneMoreText(SoapUtils.getSoapString(so,"oneMoreText")); this.setOnePageContentMain(new PageContent(SoapUtils.getSoapObject(so, "onePageContentMain"))); this.setOnePrice(SoapUtils.getSoapFloat(so,"onePrice")); this.setOneTitle(SoapUtils.getSoapString(so,"oneTitle")); } public void setId(java.lang.Long id) { this.id = id; } public java.lang.Long getId() { return this.id; } public void setListPhotoInstruction(com.fortutech.tcheckit.ejb.sessions.PhotoInstruction[] listPhotoInstruction) { this.listPhotoInstruction = listPhotoInstruction; } public com.fortutech.tcheckit.ejb.sessions.PhotoInstruction[] getListPhotoInstruction() { return this.listPhotoInstruction; } public void setListPhotosProducts(com.fortutech.tcheckit.ejb.sessions.Media[] listPhotosProducts) { this.listPhotosProducts = listPhotosProducts; } public com.fortutech.tcheckit.ejb.sessions.Media[] getListPhotosProducts() { return this.listPhotosProducts; } public void setListQuestions(com.fortutech.tcheckit.ejb.sessions.Question[] listQuestions) { this.listQuestions = listQuestions; } public com.fortutech.tcheckit.ejb.sessions.Question[] getListQuestions() { return this.listQuestions; } public void setListSign(com.fortutech.tcheckit.ejb.sessions.Sign[] listSign) { this.listSign = listSign; } public com.fortutech.tcheckit.ejb.sessions.Sign[] getListSign() { return this.listSign; } public void setOneBrand(com.fortutech.tcheckit.ejb.sessions.Brand oneBrand) { this.oneBrand = oneBrand; } public com.fortutech.tcheckit.ejb.sessions.Brand getOneBrand() { return this.oneBrand; } public void setOneDescription(java.lang.String oneDescription) { this.oneDescription = oneDescription; } public java.lang.String getOneDescription() { return this.oneDescription; } public void setOneMoreText(java.lang.String oneMoreText) { this.oneMoreText = oneMoreText; } public java.lang.String getOneMoreText() { return this.oneMoreText; } public void setOnePageContentMain(com.fortutech.tcheckit.ejb.sessions.PageContent onePageContentMain) { this.onePageContentMain = onePageContentMain; } public com.fortutech.tcheckit.ejb.sessions.PageContent getOnePageContentMain() { return this.onePageContentMain; } public void setOnePrice(java.lang.Float onePrice) { this.onePrice = onePrice; } public java.lang.Float getOnePrice() { return this.onePrice; } public void setOneTitle(java.lang.String oneTitle) { this.oneTitle = oneTitle; } public java.lang.String getOneTitle() { return this.oneTitle; } public int getPropertyCount() { return 11; } public Object getProperty(int __index) { switch(__index) { case 0: return id; case 5: return oneBrand; case 6: return oneDescription; case 7: return oneMoreText; case 8: return onePageContentMain; case 9: return onePrice; case 10: return oneTitle; } return null; } public void setProperty(int __index, Object __obj) { switch(__index) { case 0: id = (java.lang.Long) __obj; break; case 5: oneBrand = (com.fortutech.tcheckit.ejb.sessions.Brand) __obj; break; case 6: oneDescription = (java.lang.String) __obj; break; case 7: oneMoreText = (java.lang.String) __obj; break; case 8: onePageContentMain = (com.fortutech.tcheckit.ejb.sessions.PageContent) __obj; break; case 9: onePrice = (java.lang.Float) __obj; break; case 10: oneTitle = (java.lang.String) __obj; break; } } public void getPropertyInfo(int __index, Hashtable __table, PropertyInfo __info) { switch(__index) { case 0: __info.name = "id"; __info.type = java.lang.Long.class; break; case 1: __info.name = "listPhotoInstruction"; case 2: __info.name = "listPhotosProducts"; case 3: __info.name = "listQuestions"; case 4: __info.name = "listSign"; case 5: __info.name = "oneBrand"; __info.type = com.fortutech.tcheckit.ejb.sessions.Brand.class; break; case 6: __info.name = "oneDescription"; __info.type = java.lang.String.class; break; case 7: __info.name = "oneMoreText"; __info.type = java.lang.String.class; break; case 8: __info.name = "onePageContentMain"; __info.type = com.fortutech.tcheckit.ejb.sessions.PageContent.class; break; case 9: __info.name = "onePrice"; __info.type = java.lang.Float.class; break; case 10: __info.name = "oneTitle"; __info.type = java.lang.String.class; break; } } }
true
2fffcc3e3cc309c1ee6bea293f114050bce49d04
Java
sebhero/Database_Connecting
/src/com/dao/PersonDAO.java
UTF-8
7,504
3.125
3
[]
no_license
package com.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.sun.rowset.JdbcRowSetImpl; /*** * Handles the communication with the server and with the table Person * Implements the DAOinterface, but since the hsql file that came with the * assigment was an older version the functions needs to be done manaully. * * @author seb * */ public class PersonDAO implements DAOinterface { private final String updateDB = "Please update your database to the newest version, function is not supported. hsql 2.3.2 "; private JdbcRowSetImpl rowSet; public PersonDAO() { rowSet = DbUtil.getRowSet(); } @Override public Object[] createPerson(String fName, String lName, String address) { int rowNR = -1; Object[] tempRow = null; try { // update the rowSet, get latest version of DB rowSet = DbUtil.getRowSet(); rowSet.last(); final int cur = rowSet.getRow(); System.out.println("current row: " + cur); rowNR = rowSet.getInt(1) + 1; System.out.println("rownR: " + rowNR); rowSet.moveToInsertRow(); rowSet.updateInt("NR", rowNR); rowSet.updateString("fnamn", fName); rowSet.updateString("enamn", lName); rowSet.updateString("adress", address); rowSet.insertRow(); // TODO NEVER FORGET EXECUTE! rowSet.execute(); rowSet.last(); tempRow = new Object[] { rowSet.getInt(1), rowSet.getString(2), rowSet.getString(3), rowSet.getString(4) }; } catch (final SQLException e1) { final int code = e1.getErrorCode(); if (code == -20) { System.err.println(updateDB); if (rowNR < 0) { return null; } tempRow = createPersonManually(rowNR, fName, lName, address); } // e1.printStackTrace(); } return tempRow; } /*** * When the normal creates fails there is a backup with SQL insert query * * @param nr * the nr row in DB * @param fName * firstname in DB * @param lName * lastname in DB * @param address * address in DB * @return object array to be displayed in the table */ private Object[] createPersonManually(int nr, String fName, String lName, String address) { Connection dbConnection = null; Statement statement = null; final String insertSQL = "INSERT INTO PERSON (NR, FNAMN, ENAMN, ADRESS) VALUES(" + nr + ",'" + fName + "','" + lName + "','" + address + "');"; try { dbConnection = DbUtil.getConnection(); statement = dbConnection.createStatement(); statement.executeQuery(insertSQL); System.out.println("Manually creaet success"); // update the this.rowSet.execute(); return new Object[] { nr, fName, lName, address }; } catch (final SQLException e) { // TODO Auto-generated catch block System.out.println("MANUALLY FAILD"); e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } if (dbConnection != null) { try { dbConnection.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } } return null; } @Override public ResultSet readAllPersons() { final String selectStuff = "SELECT nr, fnamn, enamn, adress FROM Person"; try { rowSet.setCommand(selectStuff); rowSet.execute(); System.out.println("succefully read all"); } catch (final SQLException e) { if (e.getErrorCode() == 80) { System.err.println("Please check database is up and running, connection error"); } e.printStackTrace(); } return rowSet; } @Override public void deletePerson(int rowNr) { int nr = -1; try { rowSet.absolute(rowNr); nr = rowSet.getInt(1); System.out.println(nr); rowSet.deleteRow(); rowSet.execute(); } catch (final SQLException e) { final int code = e.getErrorCode(); if (code == -20) { System.err.println(updateDB); if (nr < 0) { return; } // dont know why deleteselected in table need to be +1 deletePersonManually(nr); } } } /*** * When normal delete fails. Take the Person Nr. which is the key of the * Persons. * * @param nr * person Nr and not the row number in table */ private void deletePersonManually(int nr) { Connection dbConnection = null; Statement statement = null; final String deleteSQL = " DELETE FROM Person WHERE NR=" + nr + ";"; System.out.println(deleteSQL); try { dbConnection = DbUtil.getConnection(); statement = dbConnection.createStatement(); statement.executeQuery(deleteSQL); System.out.println("manuall delet success"); } catch (final SQLException e) { // TODO Auto-generated catch block System.out.println("MANUALLY FAILD"); e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } if (dbConnection != null) { try { dbConnection.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } } } @Override public void updatePerson(int rowNr, int columnNr, String newValue) { int nr = -1; try { rowSet.absolute(rowNr); nr = rowSet.getInt(1); rowSet.updateString(columnNr, newValue); rowSet.updateRow(); rowSet.execute(); } catch (final SQLException e) { final int code = e.getErrorCode(); if (code == -20 || code == 0) { System.err.println(updateDB); updatePersonManually(nr, columnNr, newValue); } } } /*** * Manually updates the person when update fails. Take the Person NR and which * column and the new value. * * @param nr * Person NR * @param columnNr * column where the data should be updated * @param newValue * the new value */ private void updatePersonManually(int nr, int columnNr, String newValue) { System.out.println("updating manully"); // better solution would to query db. but then i would needed the old value // ALT. a enum.. String columnName = ""; switch (columnNr) { case 2: // firstname columnName = "FNAMN"; break; case 3: // LASTNAME columnName = "ENAMN"; break; case 4: // ADDRESS columnName = "ADRESS"; break; default: // do nothing return; } Connection dbConnection = null; Statement statement = null; final String updateSQL = "UPDATE Person SET " + columnName + "='" + newValue + "'" + "WHERE Nr=" + nr; System.out.println(updateSQL); try { dbConnection = DbUtil.getConnection(); statement = dbConnection.createStatement(); statement.executeQuery(updateSQL); System.out.println("manuall update success"); } catch (final SQLException e) { // TODO Auto-generated catch block System.out.println("MANUALLY FAILD"); e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } if (dbConnection != null) { try { dbConnection.close(); } catch (final SQLException e1) { e1.printStackTrace(); } } } } /*** * Gets the current Resultset (but is actully the rowset), Cached data. * * @return a resultset of the database. */ public ResultSet getRowSet() { return this.rowSet; } }
true
fdd09037ce8c1a126c6c008fa0762d6983aefe34
Java
Bibekay/IMS
/app/src/main/java/com/example/meropasal/activities/User/LoginActivity.java
UTF-8
4,861
2.046875
2
[]
no_license
package com.example.meropasal.activities.User; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Vibrator; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.meropasal.MainActivity; import com.example.meropasal.R; import com.example.meropasal.activities.admin.AdminaddproductActivity; import com.example.meropasal.activities.admin.AdminhomeActivity; import com.example.meropasal.bll.LoginBLL; import com.example.meropasal.strictmode.StrictModeClass; import com.example.meropasal.url.url; public class LoginActivity extends AppCompatActivity { private Button btnsignup, btnlogin; private EditText etusername, etpassword; Vibrator vibrate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btnsignup = findViewById(R.id.btnsignup); etusername = findViewById(R.id.etusername); vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE); etpassword = findViewById(R.id.etpassword); btnlogin = findViewById(R.id.btnSignin); btnsignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openSignup(); } private void openSignup() { Intent openSignup = new Intent(LoginActivity.this, SignupActivity.class); startActivity(openSignup); } }); SharedPreferences sharedPreferences = getSharedPreferences("IMS", MODE_PRIVATE); String token = sharedPreferences.getString("token", "empty"); String status = sharedPreferences.getString("status", "isadmin"); if (!token.equals("empty") && status.equals("isadmin")) { url.token = token; url.status = status; Intent intent = new Intent(LoginActivity.this, AdminhomeActivity.class); startActivity(intent); } else if (!token.equals("empty") && !status.equals("isadmin")) { url.token = token; url.status = status; Intent intent = new Intent(LoginActivity.this, UserdashActivity.class); startActivity(intent); } btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ///validation for login String username = etusername.getText().toString(); if (TextUtils.isEmpty(username)) { etusername.setError("Enter username"); return; } String password = etpassword.getText().toString(); if (TextUtils.isEmpty(password)) { etpassword.setError("Enter password"); return; } login(); } }); } private void login() { String username = etusername.getText().toString().trim(); String password = etpassword.getText().toString().trim(); LoginBLL loginBLL = new LoginBLL(); StrictModeClass.StrictMode(); if (loginBLL.checkUser(username, password)) { SharedPreferences sharedPreferences = getSharedPreferences("IMS", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("token", url.token); editor.putString("status", url.status); editor.putString("username", username); editor.putString("password", password); editor.commit(); Intent intent = new Intent(LoginActivity.this, UserdashActivity.class); startActivity(intent); finish(); } else { if (loginBLL.checkadmin(username, password)) { SharedPreferences sharedPreferences = getSharedPreferences("IMS", MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("token", url.token); editor.putString("isadmin", url.status); editor.putString("username", username); editor.putString("password", password); editor.commit(); Intent intent = new Intent(LoginActivity.this, AdminhomeActivity.class); startActivity(intent); finish(); } else { Toast.makeText(this, "Username or Password doesnot match", Toast.LENGTH_SHORT).show(); vibrate.vibrate(1000); etusername.requestFocus(); } } } }
true
b26a8dd2a53502d21cea47c7efe04d3997e6973a
Java
dXu23/Exam
/ExamBuilderGUI.java
UTF-8
494
2.15625
2
[]
no_license
/** * @author Rodhit */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ExamBuilderGUI { JFrame frame = new JFrame("ExamBuilder"); JPanel examPanel; JPanel options; JButton addButton = new JButton("Add Question"); JButton removeButton = new JButton("Remove Question"); JButton loadExamButton = new JButton("Load Exam"); JButton reorderQuestionsButton = new JButton("Reorder Questions"); JButton reorderAnswersButton = new JButton("Reorder answers"); }
true
0a0d8110aec656c1167d08916040a66a0b5b4ca8
Java
jpsember/spredit
/workspace/scredit/src/com/js/scredit/GroupObject.java
UTF-8
9,458
2.21875
2
[]
no_license
package com.js.scredit; import java.awt.Color; import java.io.*; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import com.js.basic.Freezable; import com.js.editor.Command; import com.js.geometry.*; import com.js.myopengl.GLPanel; import static com.js.basic.Tools.*; public class GroupObject extends EdObject { private GroupObject(EdObject source) { super(source); } private static final boolean db = false; private static class GroupReversible extends Command.Adapter { public GroupReversible() { this(false); } private GroupReversible(boolean undoFlag) { this.undoFlag = undoFlag; if (!undoFlag) { slots = ScriptEditor.items().getSelectedSlots(); } if (db) pr("Constructed " + this); } @Override public Command getReverse() { if (rev != null) return rev; ASSERT(!undoFlag); if (origObj == null) { origObj = frozen(ScriptEditor.items()); // observe we are actually mutating the frozen object here; later // perhaps we'll move selected flags out of the EdObjectArray origObj.clearAllSelected(); } GroupReversible gr = new GroupReversible(true); gr.rev = this; gr.origObj = this.origObj; gr.slots = this.slots; rev = gr; return rev; } @Override public void perform() { if (db) pr("perform " + this); if (undoFlag) { ScriptEditor.setItems(origObj); origObj.setSelected(slots); } else { int groupSlot = -1; getReverse(); // make sure we've constructed origObj EdObjectArray a = new EdObjectArray(); GroupObject group = new GroupObject(null); group.setSelected(true); int slot = 0; for (int i = 0; i < origObj.size(); i++) { EdObject obj = origObj.get(i); if (slot < slots.size() && slots.get(slot) == i) { group.addParsedObject(obj); if (slot == 0) groupSlot = a.add(group); slot++; } else a.add(obj); } origObj.setSelected(new SlotList(groupSlot)); ScriptEditor.setItems(a); } } @Override public boolean valid() { return undoFlag || slots.size() >= 2; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Group "); if (slots != null) sb.append(EdTools.itemsStr(slots.size())); if (db) { // sb.append("\n id=" + id); sb.append("\n undoFlag=" + d(undoFlag)); } return sb.toString(); } private SlotList slots; private EdObjectArray origObj; // true if this object is actually the reversal of the original Group // operation private boolean undoFlag; private GroupReversible rev; // private static int uniqueId = 500; // private int id; }; private static class UnGroupReversible extends Command.Adapter { private UnGroupReversible(boolean undoFlag) { this.undoFlag = undoFlag; } public UnGroupReversible() { this(false); EdObjectArray a = ScriptEditor.items(); SlotList slots = a.getSelectedSlots(); if (slots.size() == 1) { EdObject obj = a.get(slots.get(0)); if (obj instanceof GroupObject) { group = (GroupObject) obj; slot = slots.get(0); } } } public String toString() { return "Ungroup"; } private GroupObject group; private int slot; private UnGroupReversible rev; private boolean undoFlag; private EdObjectArray origObj; @Override public Command getReverse() { if (db) pr("UnGroupReversible.getReverse()"); if (rev == null) { ASSERT(!undoFlag); if (origObj == null) { if (db) pr(" storing ScriptEditor items in origObj"); die("unsupported"); // origObj = new EdObjectArray(ScriptEditor.items()); } UnGroupReversible gr = new UnGroupReversible(true); // not sure we need a redo here... gr.origObj = origObj; gr.slot = slot; if (false) gr.rev = this; rev = gr; } return rev; } @Override public void perform() { if (undoFlag) { if (db) pr("performing undo, restoring items " + origObj); origObj.clearAllSelected(); origObj.get(slot).setSelected(true); if (db) pr(" set slot " + slot + " selected"); ScriptEditor.setItems(origObj); } else { getReverse(); // make sure we've saved original items EdObjectArray a = ScriptEditor.items(); EdObjectArray b = new EdObjectArray(); for (int i = 0; i < a.size(); i++) { EdObject obj = a.get(i); if (i == slot) { for (int k = 0; k < group.size(); k++) { EdObject o2 = copyOf(group.obj(k)); o2.setSelected(true); b.add(o2); } } else b.add(obj); } ScriptEditor.setItems(b); } } @Override public boolean valid() { return group != null; } }; public static Command getGroupReversible() { return new GroupReversible(); } public static Command getUnGroupReversible() { return new UnGroupReversible(); } public static final int CODE = 3; // code for group object private ArrayList<EdObject> objects = new ArrayList(); private int size() { return objects.size(); } private void setObj(int index, EdObject obj) { objects.set(index, obj); } private EdObject obj(int i) { return objects.get(i); } @Override public Freezable getMutableCopy() { GroupObject g = new GroupObject(this); g.objects = new ArrayList(); // If we make objects immutable, we don't need to get copies of them...? for (int i = 0; i < size(); i++) g.objects.add(frozen(obj(i))); return g; } @Override public Rect boundingRect() { if (bounds == null) { for (int i = 0; i < size(); i++) { EdObject obj = obj(i); Rect b = obj.boundingRect(); if (bounds == null) bounds = new Rect(b); else bounds.include(b); } } return bounds; } public boolean contains(Point pt) { return boundingRect().contains(pt); } // @Override // public Point getPoint(int index) { // return location(); // } // @Override // public int nPoints() { // return 1; // } @Override public Point location() { return boundingRect().midPoint(); } @Override public void setLocation(Point pt) { mutate(); Point prev = location(); Point diff = Point.difference(pt, prev); bounds = null; for (int i = 0; i < size(); i++) { EdObject obj = obj(i); Point ploc = obj.location(); obj.setLocation(Point.sum(ploc, diff)); } } private Rect bounds; private int expectedSize; @Override public EdObject applyColor(Color color) { EdObject ret = this; GroupObject g = mutableCopyOf(this); for (int i = 0; i < g.size(); i++) { EdObject obj = obj(i); EdObject obj2 = obj.applyColor(color); if (obj2 != obj) { ret = g; g.setObj(i, obj2); } } return ret; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Group of "); sb.append(size()); sb.append(" objects"); return sb.toString(); } @Override public EdObjectFactory getFactory() { return FACTORY; } @Override public void render(GLPanel panel, boolean isSelected, boolean isEditable) { if (isSelected) { panel.setRenderColor(Color.YELLOW); panel.drawFrame(boundingRect()); } for (int i = 0; i < size(); i++) { EdObject ob = obj(i); ob.render(panel, false, false); } } public static EdObjectFactory FACTORY = new OurFactory(); private static class OurFactory extends EdObjectFactory { @Override public String getTag() { return "G"; } @Override public EdObject parse(Script script, JSONObject map) throws JSONException { GroupObject so = new GroupObject(null); so.expectedSize = map.getInt("size"); // the caller will handle reading additional objects and adding them to // the group // until it is complete. return so; } @Override public void write(Script script, JSONObject map, EdObject obj) throws JSONException { GroupObject g = (GroupObject) obj; map.put("size", g.size()); unimp("parse objects from group"); // for (int i = 0; i < g.size(); i++) { // EdObject o2 = g.obj(i); // EdObjectFactory f = o2.getFactory(); // sb.append(f.getTag()); // f.write(script, sb, o2); // sb.addCr(); // } } public void write(ScriptsFile sf, EdObject obj) throws IOException { GroupObject so = (GroupObject) obj; for (int i = 0; i < so.size(); i++) { EdObject o2 = so.obj(i); o2.getFactory().write(sf, o2); } } @Override public int getCode() { return CODE; } } public void addParsedObject(EdObject obj) { objects.add(obj); } public boolean parseComplete() { return size() == expectedSize; } }
true
ec3dc1f71c57c0c80b63798465c5843b80bbcd65
Java
Software-Engineering-A-Team/DemTrains
/TrackModel/src/prototype/TrackModelGUI.java
UTF-8
4,981
2.5
2
[]
no_license
package prototype; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import net.miginfocom.swing.MigLayout; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JScrollPane; import javax.swing.JList; import javax.swing.JTable; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.IOException; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import javax.swing.ListSelectionModel; import java.util.*; public class TrackModelGUI extends JFrame { private JPanel contentPane; private JTextField input_filename; private JButton btnImportTrack; private JPanel panel_1; private JPanel panel_2; private JScrollPane scrollPane; private JList list_line; private JScrollPane scrollPane_1; private JList list_blockNumber; private JLabel lblLines; private JLabel lblBlockNumber; private JScrollPane scrollPane_2; private JLabel lblBlockData; private JTable table_blockData; private TrackModel trackModel; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TrackModelGUI frame = new TrackModelGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public TrackModelGUI() { trackModel = new TrackModel(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 700, 500); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new MigLayout("", "[grow][grow]", "[][grow]")); JPanel panel = new JPanel(); contentPane.add(panel, "cell 0 0 2 1,grow"); JLabel lblFilename = new JLabel("Filename"); panel.add(lblFilename); input_filename = new JTextField(); input_filename.setText("green.csv"); panel.add(input_filename); input_filename.setColumns(10); btnImportTrack = new JButton("Import Track"); btnImportTrack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { trackModel.importLineFromFile( input_filename.getText() ); input_filename.setText( "" ); list_line.setListData( trackModel.getLineNames() ); } }); panel.add(btnImportTrack); panel_1 = new JPanel(); contentPane.add(panel_1, "cell 0 1,grow"); panel_1.setLayout(new MigLayout("", "[grow][grow]", "[][grow]")); lblLines = new JLabel("Lines"); panel_1.add(lblLines, "cell 0 0"); lblBlockNumber = new JLabel("Block Number"); panel_1.add(lblBlockNumber, "cell 1 0"); scrollPane = new JScrollPane(); panel_1.add(scrollPane, "cell 0 1,grow"); list_line = new JList(); list_line.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_line.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { JList source = (JList)e.getSource(); if ( source.getSelectedValue() != null ) { String selected = source.getSelectedValue().toString(); TrackLayout lay = trackModel.getLine( selected ); List<TrackBlock> blocks = lay.getBlocks(); String[] numbers = new String[blocks.size()]; int i = 0; for ( TrackBlock block : blocks ) { numbers[i++] = String.valueOf( block.getNumber() ); } list_blockNumber.setListData( numbers ); scrollPane_2.setViewportView( null ); } } }); scrollPane.setViewportView(list_line); scrollPane_1 = new JScrollPane(); panel_1.add(scrollPane_1, "cell 1 1,grow"); list_blockNumber = new JList(); list_blockNumber.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { String listLineSelection = list_line.getSelectedValue().toString(); if ( !listLineSelection.isEmpty() ) { JList source = (JList)e.getSource(); if ( source.getSelectedValue() != null ) { String selected = source.getSelectedValue().toString(); TrackLayout lay = trackModel.getLine( listLineSelection ); List<TrackBlock> blocks = lay.getBlocks(); String[][] model = blocks.get( Integer.parseInt( selected ) - 1 ).getModel(); table_blockData = new JTable( model, new String[] { "Attribute", "Value" } ); scrollPane_2.setViewportView( table_blockData ); } } } }); scrollPane_1.setViewportView(list_blockNumber); panel_2 = new JPanel(); contentPane.add(panel_2, "cell 1 1,grow"); panel_2.setLayout(new MigLayout("", "[grow]", "[][grow]")); lblBlockData = new JLabel("Block Data"); panel_2.add(lblBlockData, "cell 0 0"); scrollPane_2 = new JScrollPane(); panel_2.add(scrollPane_2, "cell 0 1,grow"); table_blockData = new JTable(); scrollPane_2.setViewportView(table_blockData); } }
true
d4fd2d88c830a1824c57f146925538b092a72acb
Java
JuliaBichler/5AHWII_JB
/Observer/src/main/Observable.java
UTF-8
686
3.453125
3
[]
no_license
package main; import java.util.ArrayList; public class Observable { private static ArrayList<Observer> observer; private static int value; public Observable(int value) { observer = new ArrayList<Observer>(); this.value = value; } private static void notifyAllObservers(int value){ for(Observer o : observer) { if(o.getValue()<=value) o.update(value); } } public int getValue() { return value; } public static void setValue(int value1) { value = value1; notifyAllObservers(value1); } public static void subscribe(Observer name) { observer.add(name); } public static void unsubscribe(Observer name){ observer.remove(name); } }
true
9b6d3f6f18638ccd27d53bf61eb7210677e116c7
Java
YEONSUKIM1/2021-JavaStudy
/project2/src/com/kh/exam8/Sample2.java
UTF-8
5,675
3.984375
4
[]
no_license
package com.kh.exam8; import javax.security.auth.Subject; class Student { private String name; private int age; private char gender; private int rank; public Student() {} public Student(String name) { this.name = name; } public String info() { String text = ""; text += "이름 : " + this.name + "(" + this.age + " 세)\n"; text += "성별 : " + this.gender + "\n"; text += "성적 순위 : " + this.rank + " 등"; return text; } public void rankUp(int rank) { this.rank -= rank; } public void rankDown(int rank) { this.rank += rank; } public boolean isHigh(Student student) { if(this.rank < student.rank) { return true; } return false; } public boolean isLow(Student student) { if(this.rank > student.rank) { return true; } return false; } public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setAge(int age) { this.age = age; } public void setGender(char gender) { this.gender = gender; } public void setRank(int rank) { this.rank = rank; } } public class Sample2 { public static void main(String[] args) { /* * 클래스를 사용하여 인스턴스를 만들고 만들어진 인스턴스를 사용하는 코드를 * 보고 해당 코드에 적합한 클래스를 작성해보도록 한다. * (단, 이 클래스는 캡슐화를 적용한다.) */ Student s1 = new Student(); s1.setName("홍길동"); s1.setAge(21); s1.setGender('남'); s1.setRank(100); /* * 이름 : 홍길동(21 세) * 성별 : 남 * 성적 순위 : 100 등 */ System.out.println(s1.info()); s1.rankUp(5); /* * 이름 : 홍길동(21 세) * 성별 : 남 * 성적 순위 : 95 등 */ System.out.println(s1.info()); s1.rankDown(3); /* * 이름 : 홍길동(21 세) * 성별 : 남 * 성적 순위 : 98 등 */ System.out.println(s1.info()); Student s2 = new Student("박지은"); s2.setAge(20); s2.setGender('여'); s2.setRank(90); /* * 이름 : 박지은(20 세) * 성별 : 여 * 성적 순위 : 90 등 */ System.out.println(s2.info()); if(s2.isHigh(s1)) { System.out.println(s2.getName() + "님의 등수가 " + s1.getName() + " 님의" + " 등수보다 높습니다."); } else { System.out.println(s2.getName() + "님의 등수가 " + s1.getName() + " 님의" + " 등수보다 높진 않습니다."); } if(s2.isLow(s1)) { System.out.println(s2.getName() + "님의 등수가 " + s1.getName() + " 님의" + " 등수보다 낮습니다."); } else { System.out.println(s2.getName() + "님의 등수가 " + s1.getName() + " 님의" + " 등수보다 낮진 않습니다."); } // 과목 클래스 // 아래와 같은 다양한 방식으로 과목 클래스의 인스턴스 생성 가능 Subject sub1 = new Subject(); Subject sub2 = new Subject("국어"); // 과목명을 전달하여 인스턴스 생성 Subject sub3 = new Subject("수학", 80); // 과목명과 점수를 전달하여 인스턴스 생성 sub1.setName("영어"); // 과목명을 별도의 Setter 이용하여 저장 가능 /* * 점수는 0 ~ 100 사이의 정수만 입력받아 저장할 수 있다. * 범위를 벗어난 값의 입력이 있는 경우 -1 이 저장되도록 한다. */ sub1.setJumsu(70); // 점수를 별도의 Setter 이용하여 저장 가능 /* * 저장된 점수가 올바른 범위의 점수인지 확인하는 메서드이다. * 올바른 점수인 경우 true, 올바르지 않은 경우 false 를 반환한다. */ if(sub1.isValid()) { System.out.println("점수가 유효합니다."); } else { System.out.println("점수가 유효하지 않습니다."); } /* * 저장된 점수를 기반으로 등급 반환, 등급은 A ~ D 그리고 F * A 등급은 100 ~ 90 이상 * B 등급은 90 미만 ~ 80 이상 * C 등급은 80 미만 ~ 70 이상 * D 등급은 70 미만 ~ 60 이상 * F 등급은 60 미만 */ System.out.println(sub1.getGrade()); /* * 점수의 입력 범위를 한정하기 위한 메서드이다. 기본값으로 0 ~ 100 의 범위가 설정되어 있지만 * 아래의 메서드를 통해 입력 범위를 제한 할 수 있다. * 이미 점수가 입력되어 있는 상태에서 범위가 변경되면 기존 점수도 범위에 맞추어 재설정 되어야 한다. */ sub1.setRangeJumsu(0, 10); // 점수의 입력 범위를 0 ~ 10 으로 한정한다. // 점수의 입력 범위를 확인 할 수 있게 만들어 주는 메서드이다. int[] rg = sub1.getRangeJumsu(); // 점수의 범위가 변경이 되면 등급 또한 변경된 범위에 맞추어 계산이 이루어져야 한다. System.out.println(sub1.getGrade()); // 동일한 과목인지 비교하는 메서드이다. if(sub1.equalSubject(sub2)) { System.out.println("동일한 과목 입니다."); } else { System.out.println("동일한 과목이 아닙니다."); } /* * 점수를 비교하는 메서드이다. * 이 메서드는 gt, lt, ge, le, eq, nq 의 추가 메서드도 만들어서 동작하게 한다. * gt : 큰값인지 비교하기 위해 사용 * ge : 크거나 같은 값인지 비교하기 위해 사용 * lt : 작은값인지 비교하기 위해 사용 * le : 작거나 같은값인지 비교하기 위해 사용 * eq : 같은 값인지 비교하기 위해 사용 * nq : 다른 값인지 비교하기 위해 사용 */ if(sub1.gt(sub2)) { System.out.println(sub1.getName() + "의 점수가 더 높습니다."); } } }
true
8d3f1e76ba00a2352dec22fdcf11dee81cb42351
Java
bellmit/workflow-g
/src/main/java/com/gionee/gniflow/web/listener/AccessoriesPricing/AccessoriesPricingSendMailListener.java
UTF-8
5,059
1.984375
2
[]
no_license
package com.gionee.gniflow.web.listener.AccessoriesPricing; import java.util.Arrays; import org.activiti.engine.RuntimeService; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.gionee.gniflow.biz.service.ProcessHelpService; import com.gionee.gniflow.web.util.SendMailTool; import com.gionee.gniflow.web.util.SpringTools; //配件定价流程通过审批时给所有参与审批的人员发送邮件通知 public class AccessoriesPricingSendMailListener implements ExecutionListener { private static final long serialVersionUID = -5004958930882885109L; private Logger logger = LoggerFactory.getLogger(AccessoriesPricingSendMailListener.class); private ProcessHelpService processHelpService; @Override public void notify(DelegateExecution execution) throws Exception { logger.debug("Running in AccessoriesPricingSendMailListener begin!"); RuntimeService runtimeService= execution.getEngineServices().getRuntimeService(); processHelpService = (ProcessHelpService) SpringTools.getBean(ProcessHelpService.class); String AccessoriesManagerAccount = ""; if(runtimeService.getVariable(execution.getId(),"AccessoriesManagerAccount") != null) { AccessoriesManagerAccount = (String) runtimeService.getVariable(execution.getId(),"AccessoriesManagerAccount"); } String FinanceManagerAccount = "00000074"; String ECManagerAccount = ""; if(runtimeService.getVariable(execution.getId(),"ECManagerAccount") != null) { ECManagerAccount = (String) runtimeService.getVariable(execution.getId(),"ECManagerAccount"); } String BrandsManagerAccount = ""; if(runtimeService.getVariable(execution.getId(),"BrandsManagerAccount") != null) { BrandsManagerAccount = (String) runtimeService.getVariable(execution.getId(),"BrandsManagerAccount"); } String CSManagerAccount = ""; if(runtimeService.getVariable(execution.getId(),"CSManagerAccount") != null) { CSManagerAccount = (String) runtimeService.getVariable(execution.getId(),"CSManagerAccount"); } String CommercialManagementAccount = "02500075"; String processId = execution.getProcessInstanceId(); String title = "配件定价流程已通过审批通知"; String content = "尊敬的同事,您好:</br>" + "流程实例编号为" + processId + "的配件定价流程已通过审批,请登录工作流平台查看。</br>" + "此邮件由 Gionee工作流平台(网址:<a href='http://flow.gionee.com'>http://flow.gionee.com</a>) 自动生成,请勿回复此邮件!感谢您的配合!</br>" + "祝您工作顺利,生活愉快!"; if(AccessoriesManagerAccount != null && !AccessoriesManagerAccount.equals("")) { String email = processHelpService.getUserEmailAddress(AccessoriesManagerAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } if(FinanceManagerAccount != null && !FinanceManagerAccount.equals("")) { String email = processHelpService.getUserEmailAddress(FinanceManagerAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } if(ECManagerAccount != null && !ECManagerAccount.equals("")) { String email = processHelpService.getUserEmailAddress(ECManagerAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } if(BrandsManagerAccount != null && !BrandsManagerAccount.equals("")) { String email = processHelpService.getUserEmailAddress(BrandsManagerAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } if(CSManagerAccount != null && !CSManagerAccount.equals("")) { String email = processHelpService.getUserEmailAddress(CSManagerAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } if(CommercialManagementAccount != null && !CommercialManagementAccount.equals("")) { String email = processHelpService.getUserEmailAddress(CommercialManagementAccount); if(email != null && !email.trim().equals("")) { //processHelpService.sendEmail4UserAccount(Arrays.asList(new String[]{email.trim()}), title, content); SendMailTool.sendMailByAddress(title, content, email); } } logger.debug("Running in AccessoriesPricingSendMailListener end!"); } }
true
f0983b4a8cbd2cb73bc90636eb48452b85a482ae
Java
gahlawat4u/repoName
/rda0105-agl-aus-java-a43926f304e3/xms-weblib/src/main/java/com/gms/xms/weblib/controller/invoicing/SendEmailInvoicesController.java
UTF-8
10,177
1.929688
2
[]
no_license
package com.gms.xms.weblib.controller.invoicing; import com.gms.xms.common.constants.AppConstants; import com.gms.xms.common.constants.Attributes; import com.gms.xms.common.constants.ErrorCode; import com.gms.xms.common.context.ContextBase2; import com.gms.xms.common.exception.CustomException; import com.gms.xms.common.utils.DateUtils; import com.gms.xms.model.FranchiseInfoModel; import com.gms.xms.model.InvoiceModel; import com.gms.xms.model.utils.ModelUtils; import com.gms.xms.persistence.service.invoice.IInvoiceService; import com.gms.xms.persistence.service.invoice.InvoiceServiceImp; import com.gms.xms.txndb.vo.InvoiceFilter; import com.gms.xms.txndb.vo.InvoiceVo; import com.gms.xms.weblib.controller.AdminJsonBaseController; import com.gms.xms.workflow.core2.WorkFlowManager2; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class SendEmailInvoicesController extends AdminJsonBaseController { private static final long serialVersionUID = -8336988049322842141L; private List<String> listInvoiceDates; private String franchiseCode; private String invoiceCode; private String invoiceDate; public String show() { try { this.prepareDatas(); } catch (Exception e) { this.handleError(e, AppConstants.SYSTEM_ERROR_MESSAGE); } return "success"; } public String getInvDates() { try { this.prepareInvoiceDates(); } catch (Exception e) { this.setErrorCode(ErrorCode.ACTION_ERROR); this.setErrorMessage(this.getLocalizationText(e.getMessage())); log.error(e.getMessage(), e); } return "success"; } public String sendEmailByInvDate() { try { if (!StringUtils.isBlank(this.getInvoiceDate())) { IInvoiceService invoiceService = new InvoiceServiceImp(); this.prepareFranchises(); List<String> franchiseCodes = new LinkedList<>(); if (StringUtils.isBlank(this.getFranchiseCode())) { for (FranchiseInfoModel franchiseInfo : this.getFranchises()) { franchiseCodes.add(franchiseInfo.getCode()); } } else { franchiseCodes.add(this.getFranchiseCode()); } InvoiceFilter filter = new InvoiceFilter(); filter.setInvoiceDate(DateUtils.convertStringToDate(this.getInvoiceDate(), AppConstants.APP_SETTINGS.getDefaultDateFormat(), null)); filter.setStatus(1); filter.setFranchiseCodes(franchiseCodes); List<InvoiceVo> invoiceVos = invoiceService.getInvoicesByInvDatesAndStatus(filter); List<Long> invoiceIds = new LinkedList<>(); for (InvoiceVo invoiceVo : invoiceVos) { invoiceIds.add(invoiceVo.getInvoiceId()); } // Load invoice information and send email in background. final ContextBase2 context = new ContextBase2(this.getAddInfoMap()); context.put(Attributes.LIST_INVOICE_IDS, invoiceIds); context.put(Attributes.FRANCHISE_CODE_LIST, franchiseCodes); context.put(Attributes.WFP_NAME, "Wfl-SendCustomerInvoicesEmail"); Thread thread = new Thread(new Runnable() { @Override public void run() { ContextBase2 runableContext = context; try { runableContext = WorkFlowManager2.getInstance().process(runableContext); if (runableContext.getString(Attributes.ERROR_CODE).equalsIgnoreCase(ErrorCode.SUCCESS)) { } else { throw new CustomException(context.getString(Attributes.ERROR_MESSAGE)); } } catch (Exception e) { log.error(e); } } }); thread.start(); this.prepareInvoiceDates(); } else { throw new CustomException("Invoice date cannot be empty."); } } catch (Exception e) { this.handleError(e, AppConstants.SYSTEM_ERROR_MESSAGE); return "error"; } return "success"; } public String sendEmailByInvCode() { try { if (!StringUtils.isBlank(this.getInvoiceCode())) { IInvoiceService invoiceService = new InvoiceServiceImp(); InvoiceVo invoiceVo = invoiceService.selectByCode(this.getInvoiceCode()); if (invoiceVo == null) { throw new CustomException("Cannot find the invoice with this invoice code."); } if (invoiceVo.getStatus() < 1) { throw new CustomException("This invoice has not been frozen or already sent."); } this.prepareFranchises(); String customerCode = String.valueOf(invoiceVo.getCustomerCode()); String franchiseCode = customerCode.substring(0, 3); Boolean hasPermission = false; List<String> franchiseCodes = new LinkedList<>(); if (StringUtils.isBlank(this.getFranchiseCode())) { for (FranchiseInfoModel franchiseInfo : this.getFranchises()) { if (franchiseCode.equalsIgnoreCase(franchiseInfo.getCode())) { hasPermission = true; franchiseCodes.add(franchiseInfo.getCode()); } } } else { franchiseCodes.add(this.getFranchiseCode()); } if (hasPermission) { List<Long> invoiceIds = new LinkedList<>(); if (invoiceVo.getInvoiceId() != null) { invoiceIds.add(invoiceVo.getInvoiceId()); } final ContextBase2 context = new ContextBase2(this.getAddInfoMap()); context.put(Attributes.LIST_INVOICE_IDS, invoiceIds); context.put(Attributes.FRANCHISE_CODE_LIST, franchiseCodes); context.put(Attributes.WFP_NAME, "Wfl-SendCustomerInvoicesEmail"); Thread thread = new Thread(new Runnable() { @Override public void run() { ContextBase2 runableContext = context; try { runableContext = WorkFlowManager2.getInstance().process(runableContext); if (runableContext.getString(Attributes.ERROR_CODE).equalsIgnoreCase(ErrorCode.SUCCESS)) { } else { throw new CustomException(context.getString(Attributes.ERROR_MESSAGE)); } } catch (Exception e) { log.error(e); } } }); thread.start(); this.prepareInvoiceDates(); } else { throw new CustomException("You do not have permission to send this invoice."); } } else { throw new CustomException("Invoice code cannot be empty."); } } catch (Exception e) { this.handleError(e, AppConstants.SYSTEM_ERROR_MESSAGE); return "error"; } return "success"; } private void prepareDatas() throws Exception { this.prepareFranchises(); this.prepareInvoiceDates(); } private void prepareInvoiceDates() throws Exception { List<String> franchiseCodes = new ArrayList<>(); List<String> invoiceDates = new LinkedList<>(); if (StringUtils.isBlank(this.getFranchiseCode())) { for (FranchiseInfoModel franchise : this.getFranchises()) { franchiseCodes.add(franchise.getCode()); } } else { franchiseCodes.add(this.getFranchiseCode()); } IInvoiceService invoiceService = new InvoiceServiceImp(); InvoiceFilter filter = new InvoiceFilter(); filter.setFranchiseCodes(franchiseCodes); filter.setStatus(1); filter.setEmailInvoice(1); List<InvoiceVo> invoiceDatesVo = invoiceService.getInvoiceDates(filter); List<InvoiceModel> invoiceDatesModel = ModelUtils.createListModelFromVo(invoiceDatesVo, InvoiceModel.class); for (InvoiceModel invoiceModel : invoiceDatesModel) { if (invoiceModel != null && StringUtils.isNotBlank(invoiceModel.getInvoiceDate())) { invoiceDates.add(invoiceModel.getInvoiceDate()); } } this.setListInvoiceDates(invoiceDates); } public List<String> getListInvoiceDates() { return listInvoiceDates; } public void setListInvoiceDates(List<String> listInvoiceDates) { this.listInvoiceDates = listInvoiceDates; } public String getFranchiseCode() { return franchiseCode; } public void setFranchiseCode(String franchiseCode) { this.franchiseCode = franchiseCode; } public String getInvoiceCode() { return invoiceCode; } public void setInvoiceCode(String invoiceCode) { this.invoiceCode = invoiceCode; } public String getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(String invoiceDate) { this.invoiceDate = invoiceDate; } }
true
bdbebf4da53dd1d636e1f73d8b66a9e597b1e411
Java
RyanTech/ctbri
/WeSee/src/com/ctri/util/UmengUtils.java
UTF-8
2,491
1.84375
2
[]
no_license
package com.ctri.util; import android.content.Context; import android.graphics.Bitmap; import android.text.TextUtils; import ct.navict.tvmate.app.R; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.controller.RequestType; import com.umeng.socialize.controller.UMServiceFactory; import com.umeng.socialize.controller.UMSocialService; import com.umeng.socialize.media.UMImage; import com.umeng.socialize.sso.SinaSsoHandler; import com.umeng.socialize.sso.TencentWBSsoHandler; /** * * @author poet * */ public class UmengUtils { public static UMSocialService getUMSocialService(){ return UMServiceFactory.getUMSocialService("com.umeng.share", RequestType.SOCIAL); } public static UMSocialService getUMLoginService(){ UMSocialService umSocialService = UMServiceFactory.getUMSocialService("com.umeng.login", RequestType.SOCIAL); umSocialService.getConfig().setSsoHandler(new SinaSsoHandler()); umSocialService.getConfig().setSsoHandler(new TencentWBSsoHandler()); return umSocialService; } public static void deleteOauth(Context context){ UMSocialService umSocialService = UMServiceFactory.getUMSocialService("com.umeng.login", RequestType.SOCIAL); umSocialService.deleteOauth(context, SHARE_MEDIA.SINA, null); umSocialService.deleteOauth(context, SHARE_MEDIA.TENCENT, null); } public static void initUmeng(Context context,UMSocialService mController, String content,String picUrl,Bitmap bitmap){ if(!TextUtils.isEmpty(picUrl)) try{ mController.setShareMedia(new UMImage(context, picUrl)); }catch(Throwable e){ mController.setShareMedia(null); } else if(bitmap != null){ try{ mController.setShareImage(new UMImage(context, bitmap)); }catch(Throwable e){ mController.setShareMedia(null); } } else mController.setShareMedia(null); // 设置分享内容 mController.setShareContent(content); // 设置分享图片, 参数2为图片的地址 // wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID String appID = context.getResources().getString(R.string.share_platform_wechat_appid); // 微信图文分享必须设置一个url // 添加微信平台,参数1为当前Activity, 参数2为用户申请的AppID, 参数3为点击分享内容跳转到的目标url mController.getConfig().supportWXPlatform(context,appID, picUrl); mController.getConfig().supportWXCirclePlatform(context, appID, picUrl); } }
true
de897146cb6bb2e74f939e2d2180be11fe2098cb
Java
VinodG/AirArabia
/airArabia/src/main/java/com/winit/airarabia/adapters/BookingMealAdapter.java
UTF-8
7,455
2.078125
2
[]
no_license
package com.winit.airarabia.adapters; import java.util.Vector; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.winit.airarabia.BaseActivity; import com.winit.airarabia.R; import com.winit.airarabia.common.AppConstants; import com.winit.airarabia.objects.FlightSegmentDO; import com.winit.airarabia.objects.MealDO; import com.winit.airarabia.objects.RequestDO; import com.winit.airarabia.utils.StringUtils; public class BookingMealAdapter extends BaseAdapter{ private Vector<MealDO> vecbookMeal; private Context context; private Vector<RequestDO> vecRequestDOs; private FlightSegmentDO flightSegmentDO; private String travelerRefNumberRPHList; public BookingMealAdapter(Context context,String travelerRefNumberRPHList, FlightSegmentDO flightSegmentDO, final Vector<RequestDO> vecRequestDOsData,Vector<MealDO> vecbookMeal) { this.context = context; this.vecbookMeal = vecbookMeal; this.flightSegmentDO = flightSegmentDO; this.travelerRefNumberRPHList = travelerRefNumberRPHList; this.vecRequestDOs = vecRequestDOsData; } @Override public int getCount() { if(vecbookMeal != null && vecbookMeal.size() > 0) return vecbookMeal.size(); else return 0; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertview, ViewGroup paramViewGroup) { MealDO mealDO = vecbookMeal.get(position); final ViewHolder viewHolder; if(convertview== null) { viewHolder = new ViewHolder(); convertview = LayoutInflater.from(context).inflate(R.layout.popup_meal_sub_item_listcell, null); viewHolder.ivPlus = (ImageView)convertview.findViewById(R.id.ivPlus); viewHolder.ivMinus = (ImageView)convertview.findViewById(R.id.ivMinus); viewHolder.imgSlectediteminmeal = (ImageView)convertview.findViewById(R.id.imgSlectediteminmeal); viewHolder.tvTitleslectediteminmeal = (TextView)convertview.findViewById(R.id.tvTitleslectediteminmeal); viewHolder.tvQuantity = (TextView)convertview.findViewById(R.id.tvQuantity); viewHolder.tvPrice = (TextView)convertview.findViewById(R.id.tvPrice); viewHolder.tvDescMeal = (TextView)convertview.findViewById(R.id.tvDescMeal); convertview.setTag(viewHolder); } else viewHolder = (ViewHolder)convertview.getTag(); viewHolder.tvTitleslectediteminmeal.setTypeface(AppConstants.typefaceOpenSansSemiBold); viewHolder.tvQuantity.setTag(position+""); viewHolder.ivPlus.setTag(position+""); viewHolder.ivMinus.setTag(position+""); viewHolder.tvQuantity.setText(StringUtils.getString(mealDO.mealCount)); viewHolder.ivPlus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MealDO mealDO = vecbookMeal.get(StringUtils.getInt(v.getTag().toString())); boolean isAdded = false; if(vecRequestDOs.size() == 0) { mealDO.mealCount = 0; mealDO.mealCount += 1; RequestDO requestDONew = new RequestDO(); requestDONew.departureDate = flightSegmentDO.departureDateTime; requestDONew.flightNumber = flightSegmentDO.flightNumber; requestDONew.flightRefNumberRPHList = flightSegmentDO.RPH; requestDONew.travelerRefNumberRPHList = travelerRefNumberRPHList; requestDONew.mealCode = mealDO.mealCode; requestDONew.mealQuantity = mealDO.mealCount+""; requestDONew.mealName = mealDO.mealName; requestDONew.mealCharge = StringUtils.getFloat(mealDO.mealCharge); vecRequestDOs.add(requestDONew); } else if(vecRequestDOs.size() > 0) { for (RequestDO requestDONew : vecRequestDOs) { if(requestDONew.mealCode.equalsIgnoreCase(mealDO.mealCode)) { isAdded = true; mealDO.mealCount = StringUtils.getInt(requestDONew.mealQuantity); mealDO.mealCount += 1; requestDONew.mealCode = mealDO.mealCode; requestDONew.mealQuantity = mealDO.mealCount+""; requestDONew.mealName = mealDO.mealName; requestDONew.mealCharge = StringUtils.getFloat(mealDO.mealCharge); } } if(!isAdded) { mealDO.mealCount += 1; RequestDO requestDONew = new RequestDO(); requestDONew.departureDate = flightSegmentDO.departureDateTime; requestDONew.flightNumber = flightSegmentDO.flightNumber; requestDONew.flightRefNumberRPHList = flightSegmentDO.RPH; requestDONew.travelerRefNumberRPHList = travelerRefNumberRPHList; requestDONew.mealCode = mealDO.mealCode; requestDONew.mealQuantity = mealDO.mealCount+""; requestDONew.mealName = mealDO.mealName; requestDONew.mealCharge = StringUtils.getFloat(mealDO.mealCharge); vecRequestDOs.add(requestDONew); } } if(v.getTag().toString().equalsIgnoreCase(viewHolder.tvQuantity.getTag().toString())) viewHolder.tvQuantity.setText(StringUtils.getString(mealDO.mealCount)); } }); viewHolder.ivMinus.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MealDO mealDO = vecbookMeal.get(StringUtils.getInt(v.getTag().toString())); if(vecRequestDOs.size() > 0) { for (RequestDO requestDONew : vecRequestDOs) { if(requestDONew.mealCode.equalsIgnoreCase(mealDO.mealCode) && travelerRefNumberRPHList.equalsIgnoreCase(requestDONew.travelerRefNumberRPHList) && flightSegmentDO.flightNumber.equalsIgnoreCase(requestDONew.flightNumber)) { mealDO.mealCount = StringUtils.getInt(requestDONew.mealQuantity); if(mealDO.mealCount > 0) { mealDO.mealCount -= 1; requestDONew.mealQuantity = mealDO.mealCount+""; if(requestDONew.mealQuantity.equalsIgnoreCase("0")) vecRequestDOs.remove(requestDONew); } } } } if(v.getTag().toString().equalsIgnoreCase(viewHolder.tvQuantity.getTag().toString())) viewHolder.tvQuantity.setText(StringUtils.getString(mealDO.mealCount)); } }); viewHolder.tvTitleslectediteminmeal.setText(mealDO.mealName); viewHolder.tvDescMeal.setText(mealDO.mealDescription); viewHolder.tvPrice.setText(context.getString(R.string.Price)+": "+ AppConstants.CurrencyCodeAfterExchange+" "+ ((BaseActivity) context).updateCurrencyByFactor(mealDO.mealCharge+"", 0)+""); Picasso.with(context).load(mealDO.mealImageLink).error(R.drawable.btn_languagebg).into(viewHolder.imgSlectediteminmeal); viewHolder.imgSlectediteminmeal.setBackgroundResource(0); /*UrlImageViewHelper.setUrlDrawable(viewHolder.imgSlectediteminmeal, mealDO.mealImageLink, R.drawable.btn_languagebg, new UrlImageViewCallback() { @Override public void onLoaded(ImageView imageView, Bitmap loadedBitmap, String url, boolean loadedFromCache) { if (!loadedFromCache) { ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1, ScaleAnimation.RELATIVE_TO_SELF, .5f, ScaleAnimation.RELATIVE_TO_SELF, .5f); scale.setDuration(300); scale.setInterpolator(new OvershootInterpolator()); imageView.startAnimation(scale); } } });*/ return convertview; } class ViewHolder{ ImageView ivPlus,ivMinus,imgSlectediteminmeal; TextView tvTitleslectediteminmeal,tvQuantity,tvPrice,tvDescMeal; } }
true
56d15257bf01267ea1301d9d98d11cb627ddb752
Java
MerlinHu0112/Algorithms
/algorithms/sort/quick/Partition.java
UTF-8
2,735
3.921875
4
[]
no_license
package algorithms.sort.quick; import algorithms.sort.SortUtil; /* * 2019-10-04 * Partition类:实现快速排序算法中划分数组的功能 * 包括:算法2.5及2.3.1.1-2.3.1.5部分对partition()方法的改进 */ public class Partition { // 通过切分,保证切分位置左侧的所有元素均不大于array[lo],右侧则是不小于array[lo]。 public static int partition(Integer[] array, int lo, int hi) { int i = lo; // 左指针 int j = hi+1; // 右指针 Integer partitionElement = array[lo]; while(true) { // 首先,从数组的左端开始向右扫描,直至找到一个不小于partitionElement的元素 while(SortUtil.less(array[++i], partitionElement)) {} // 随后,从数组的右端开始向左扫描,直至找到一个不大于partitionElement的元素 while(SortUtil.less(partitionElement, array[--j])) {} if(i>=j) { break; } // 若上述循环中分别找出对应的i、j,则交换二者,以保证i指针左侧元素均不大于partitionElement, // 而j指针右侧元素均不小于partitionElement SortUtil.exch(array, i, j); } // i、j指针相遇,交换lo和j位置元素 SortUtil.exch(array, lo, j); return j; } /* // 在切分过程中,可指定切分元素为array[lo]; // 通过切分,保证切分位置左侧的所有元素均不大于array[lo],右侧则是不小于array[lo]。 public static int partition(Integer[] array, int lo, int hi) { int i = lo; // 左指针 int j = hi+1; // 右指针 Integer partitionElement = array[lo]; while(true) { // 首先,从数组的左端开始向右扫描,直至找到一个不小于partitionElement的元素 while(SortUtil.less(array[++i], partitionElement)) { /* 2.3.1.2:在sort()方法中,将数组最大元素置于最右端,保证i指针不会 * 越过右端边界! if(i==hi) { break; // 若至最右端,终止循环 } */ /* } // 随后,从数组的右端开始向左扫描,直至找到一个不大于partitionElement的元素 while(SortUtil.less(partitionElement, array[--j])) { /* 2.3.1.2:切分元素partitionElement充当哨兵,由于array[lo]=partitionElement, * 故j指针不会越过左端边界! if(j==lo) { break; } */ /* } if(i>=j) { break; } // 若上述循环中分别找出对应的i、j,则交换二者,以保证i指针左侧元素均不大于partitionElement, // 而j指针右侧元素均不小于partitionElement SortUtil.exch(array, i, j); } // i、j指针相遇,交换lo和j位置元素 SortUtil.exch(array, lo, j); return j; } */ }
true
aec9d43c059993d723c0b045f499738ab72ca0bb
Java
wwbg1988/finance
/finance-common/src/main/java/com/blackbeard/common/pojo/order/NextOrder.java
UTF-8
13,084
1.875
2
[]
no_license
package com.blackbeard.common.pojo.order; import java.util.Date; public class NextOrder { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.login_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer loginId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.currency_type * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private String currencyType; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.direction * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer direction; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.price * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private String price; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.tick * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer tick; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.user_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer userId; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.open_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private String openTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.close_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private String closeTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.total * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer total; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.comment * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private String comment; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.stat * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Integer stat; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.create_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Date createTime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_next_order.update_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ private Date updateTime; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.id * * @return the value of t_next_order.id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.id * * @param id the value for t_next_order.id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.login_id * * @return the value of t_next_order.login_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getLoginId() { return loginId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.login_id * * @param loginId the value for t_next_order.login_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setLoginId(Integer loginId) { this.loginId = loginId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.currency_type * * @return the value of t_next_order.currency_type * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public String getCurrencyType() { return currencyType; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.currency_type * * @param currencyType the value for t_next_order.currency_type * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setCurrencyType(String currencyType) { this.currencyType = currencyType == null ? null : currencyType.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.direction * * @return the value of t_next_order.direction * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getDirection() { return direction; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.direction * * @param direction the value for t_next_order.direction * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setDirection(Integer direction) { this.direction = direction; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.price * * @return the value of t_next_order.price * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public String getPrice() { return price; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.price * * @param price the value for t_next_order.price * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setPrice(String price) { this.price = price == null ? null : price.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.tick * * @return the value of t_next_order.tick * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getTick() { return tick; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.tick * * @param tick the value for t_next_order.tick * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setTick(Integer tick) { this.tick = tick; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.user_id * * @return the value of t_next_order.user_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getUserId() { return userId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.user_id * * @param userId the value for t_next_order.user_id * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setUserId(Integer userId) { this.userId = userId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.open_time * * @return the value of t_next_order.open_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public String getOpenTime() { return openTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.open_time * * @param openTime the value for t_next_order.open_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setOpenTime(String openTime) { this.openTime = openTime == null ? null : openTime.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.close_time * * @return the value of t_next_order.close_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public String getCloseTime() { return closeTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.close_time * * @param closeTime the value for t_next_order.close_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setCloseTime(String closeTime) { this.closeTime = closeTime == null ? null : closeTime.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.total * * @return the value of t_next_order.total * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getTotal() { return total; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.total * * @param total the value for t_next_order.total * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setTotal(Integer total) { this.total = total; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.comment * * @return the value of t_next_order.comment * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public String getComment() { return comment; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.comment * * @param comment the value for t_next_order.comment * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setComment(String comment) { this.comment = comment == null ? null : comment.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.stat * * @return the value of t_next_order.stat * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Integer getStat() { return stat; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.stat * * @param stat the value for t_next_order.stat * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setStat(Integer stat) { this.stat = stat; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.create_time * * @return the value of t_next_order.create_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Date getCreateTime() { return createTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.create_time * * @param createTime the value for t_next_order.create_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_next_order.update_time * * @return the value of t_next_order.update_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public Date getUpdateTime() { return updateTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_next_order.update_time * * @param updateTime the value for t_next_order.update_time * * @mbggenerated Thu Jul 21 10:32:31 CST 2016 */ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
true
295338ef93c411efb67647568bc8c4775aa7a5e3
Java
narding30/AlifightApp
/app/src/main/java/com/example/alihfight/alifightapp/User/Fragments/ProfileFragmentUser.java
UTF-8
4,571
1.9375
2
[]
no_license
package com.example.alihfight.alifightapp.User.Fragments; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.example.alihfight.alifightapp.AvailMemberShipActivity; import com.example.alihfight.alifightapp.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import de.hdodenhof.circleimageview.CircleImageView; /** * A simple {@link Fragment} subclass. */ public class ProfileFragmentUser extends Fragment { View view; CircleImageView IVProfImage; TextView nametext,agetext,sextext,addresstext,contactnumbertext,occupationtext,sessiontext,sessionslefttext; DatabaseReference databaseReference; private FirebaseAuth firebaseAuth; public String userID; private Button btnNewMem; public ProfileFragmentUser() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment view = inflater.inflate(R.layout.fragment_profile_user, container, false); IVProfImage = view.findViewById(R.id.IVProfileImage); nametext = view.findViewById(R.id.TVNameProfile); agetext =view.findViewById(R.id.TVAgeProfile); sextext = view.findViewById(R.id.TVSexProfile); addresstext = view.findViewById(R.id.TVAddressProfile); contactnumbertext = view.findViewById(R.id.TVContactNumProfile); occupationtext = view.findViewById(R.id.TVOccupationProfile); sessiontext = view.findViewById(R.id.TVSessionProfile); sessionslefttext = view.findViewById(R.id.TVSessionsLeftProfile); btnNewMem = view.findViewById(R.id.btnAvailNewMem); firebaseAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = firebaseAuth.getCurrentUser(); userID = currentUser.getUid(); databaseReference = FirebaseDatabase.getInstance().getReference("users"); btnNewMem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), AvailMemberShipActivity.class) .putExtra("Id", userID) .putExtra("Identifier", "Renew")); } }); return view; } @Override public void onStart() { super.onStart(); databaseReference.child(userID).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { nametext.setText(dataSnapshot.child("FirstName").getValue().toString() + " " +dataSnapshot.child("LastName").getValue().toString()); agetext.setText(dataSnapshot.child("Age").getValue().toString()); sextext.setText(dataSnapshot.child("Gender").getValue().toString()); addresstext.setText(dataSnapshot.child("Address").getValue().toString()); occupationtext.setText(dataSnapshot.child("Occupation").getValue().toString()); contactnumbertext.setText(dataSnapshot.child("Contact").getValue().toString()); DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PaymentDetails").child(userID); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { sessiontext.setText(dataSnapshot.child("SessionName").getValue().toString()); sessionslefttext.setText(dataSnapshot.child("SessionCount").getValue().toString()+" Sessions"); } @Override public void onCancelled(DatabaseError databaseError) { } }); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
true
4038e4f4818d5f06a332d5c0fbb0dbc70ad49539
Java
uywojh/cloud-project
/simons-cloud-zuul/src/main/java/com/simons/cloud/user/api/cache/NameContext.java
UTF-8
987
2.0625
2
[]
no_license
package com.simons.cloud.user.api.cache; public class NameContext { /** * 用户登录后保存于redis中的信息头 */ public static final String USER_LOGIN_HEADER = "user_login_"; /** * 不同角色的权限菜单保存于redis中的信息头 */ public static final String PERMISSION_INFO = "permission_info_"; /** * 用户信息cookie中存放的名字 */ public static final String USER_INFO_COOKIE = "UserInfo"; /** * 返回用户信息的cookie中存放的token的名字 */ public static final String TOKEN = "token"; /** * 树形结构的根节点 */ public static final Long TOP_TREE_NODE = 1L; /** * 不同角色的菜单列表保存于redis中的信息头 */ public static final String MEUN_ROLE_HEADER = "meun_role_"; /** * 验证码的名字 */ public static final String CHECK_CODE_NAME = "check_code_"; /** * 总菜单树在redis中的名称 */ public static final String NODE_MENU_TREE_NAME = "node_menu_tree"; }
true
2bbfd8991dc7771fa004b90097dbfaaf851f06a8
Java
liuguicheng/CisoftOnline
/src/com/cisoft/model/PurchaseReturn.java
UTF-8
1,306
1.828125
2
[]
no_license
package com.cisoft.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="n_purchasereturn") public class PurchaseReturn extends PageRequest{ //采购退货 @Id @GeneratedValue(strategy=GenerationType.AUTO) private int pr_id; private String pr_no;//采购订单(退货) private String pr_username;//退货人 private Date pr_shdate;//退货时间 private int pr_scbs; private String pr_bz;//备注 public int getPr_id() { return pr_id; } public void setPr_id(int pr_id) { this.pr_id = pr_id; } public String getPr_no() { return pr_no; } public void setPr_no(String pr_no) { this.pr_no = pr_no; } public String getPr_username() { return pr_username; } public void setPr_username(String pr_username) { this.pr_username = pr_username; } public Date getPr_shdate() { return pr_shdate; } public void setPr_shdate(Date pr_shdate) { this.pr_shdate = pr_shdate; } public int getPr_scbs() { return pr_scbs; } public void setPr_scbs(int pr_scbs) { this.pr_scbs = pr_scbs; } public String getPr_bz() { return pr_bz; } public void setPr_bz(String pr_bz) { this.pr_bz = pr_bz; } }
true
532d6b9a3435de42d34518d3d113e913cc186e02
Java
joaopu/spring-stuff
/src/main/java/br/joaopu/pattern/decorator/domain/Costable.java
UTF-8
136
2.125
2
[]
no_license
package br.joaopu.pattern.decorator.domain; public interface Costable { String getCode(); String getName(); Double cost(); }
true
d9f251f9306b171023dfed33ea97b73a3c607153
Java
omrkhld/CS3218proj
/app/src/main/java/sg/edu/nus/accelerometer/AccelerometerActivity.java
UTF-8
9,727
2.171875
2
[]
no_license
package sg.edu.nus.accelerometer; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import sg.edu.nus.data.SensorDBHelper; import sg.edu.nus.data.SensorsContract; import sg.edu.nus.oztrafficcamera.R; public class AccelerometerActivity extends AppCompatActivity implements SensorEventListener { /* 1. Create an instance of the sensor service. Provide methods to access and list sensors, register and unregister sensor event listeners, and acquire orientation info. Also has some constants to report sensor accuracy, set data acquisition rates and calibrate sensor. */ private SensorManager sensorManager; private double ax, ay, az; long mLastTime = 0; long curTime = 0; long diff = 0; private double minX, maxX, minY, maxY, minZ, maxZ; //for calibration int countRounds; private TextView textview_ax, textview_ay, textview_az, textview_accelerometer_timestamp; private TextView textview_accelerometer_fps; private TextView textview_lag; private Boolean calibratePressed; private Boolean isStabilised; private Boolean isLargeChanges; private Boolean foundShake; private Sensor mAcc; AccelerometerReading reading; long startTime = 0L; long lag = 0L; public static final int THRESHOLD_NUM_AXES_WITH_LARGE_CHANGES = 2; Button startRecording, stopRecording; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_accelerometer); calibratePressed = false; foundShake = false; textview_ax = (TextView) findViewById(R.id.textview_ax); textview_ay = (TextView) findViewById(R.id.textview_ay); textview_az = (TextView) findViewById(R.id.textview_az); textview_accelerometer_timestamp = (TextView) findViewById(R.id.textview_accelerometer_timestamp); textview_accelerometer_fps = (TextView) findViewById(R.id.textview_accelerometer_fps); textview_lag = (TextView) findViewById(R.id.textview_lag); startRecording = (Button) findViewById(R.id.btn_start_record_acc); stopRecording = (Button) findViewById(R.id.btn_stop_record_acc); stopRecording.setEnabled(false); // Use with getSystemService to retrieve an android.hardware.SensorManager for accessing sensors. sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mAcc = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // Use method getDefaultSensor to get the default sensor for a given type. // Note that the returned sensor could be a composite sensor, and its data // could be averaged or filtered. if (mAcc != null) { sensorManager.registerListener(this, mAcc, //Create instance of specific sensor SensorManager.SENSOR_DELAY_UI); } else { } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } /* * Starts the calibration after stabilisation * */ public void start_calibrate_acc(View view) { startRecording.setEnabled(false); startRecording.setText(R.string.RECORDING); stopRecording.setEnabled(true); calibratePressed = true; foundShake = false; countRounds = 3; lag = 0; maxX = minX = ax; maxY = minY = ay; maxZ = minZ = az; startTime = System.currentTimeMillis(); long[] vibratePattern = {0, 250, 0}; Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); boolean isVibrator = vibrator.hasVibrator(); if (isVibrator) { vibrator.vibrate(vibratePattern, -1); // -1 for not repeating } else { Toast.makeText(this, "This calibration requires a vibrator to work", Toast.LENGTH_SHORT).show(); } } public void stop_calibrate_acc(View view) { startRecording.setEnabled(true); startRecording.setText(R.string.START_RECORDING); stopRecording.setEnabled(false); calibratePressed = false; foundShake = false; } @Override protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this, mAcc, SensorManager.SENSOR_DELAY_UI); } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { curTime = System.currentTimeMillis(); diff = curTime - mLastTime; textview_accelerometer_fps.setText(String.format("%.2f", 1.0 / diff * 1000)); mLastTime = curTime; ax = event.values[0]; ay = event.values[1]; az = event.values[2]; textview_ax.setText(String.valueOf(ax)); textview_ay.setText(String.valueOf(ay)); textview_az.setText(String.valueOf(az)); textview_accelerometer_timestamp.setText(String.valueOf(curTime)); //Loop a few rounds to find stable values if (countRounds > 0) { if (ax < minX) { minX = ax; } else { maxX = ax; } if (ay < minY) { minY = ay; } else { maxY = ay; } if (az < maxZ) { minZ = az; } else { maxZ = az; } countRounds--; } else { isStabilised = true; } Log.v("AX min and max:", minX + " " + maxX); Log.v("AY min and max:", minY + " " + maxY); Log.v("AZ min and max:", minZ + " " + maxZ); reading = new AccelerometerReading(curTime, ax, ay, az, lag); if (calibratePressed && isStabilised) { isLargeChanges = detectLargeChange(ax, ay, az); Log.v("Large change", String.valueOf(isLargeChanges)); if (isLargeChanges) { //Modify the lag lag = curTime - startTime; textview_lag.setText(String.format("%d", lag)); reading.lag_in_ms = lag; foundShake = true; isStabilised = false; calibratePressed = false; } } if (foundShake){ //Starts asyncTask to write to database WriteToDatabaseTask task = new WriteToDatabaseTask(this); task.execute(reading); } } } // Returns true if at least n out of 3 of ax, ay or az deviates from their normal range private Boolean detectLargeChange(double curr_ax, double curr_ay, double curr_az) { int countLargeChanges = 0; if (curr_ax < minX || curr_ax > maxX){ countLargeChanges++; } if (curr_ay < minY || curr_ay > maxY){ countLargeChanges++; } if (curr_az < minZ || curr_az > maxZ){ countLargeChanges++; } return countLargeChanges >= THRESHOLD_NUM_AXES_WITH_LARGE_CHANGES; // } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } public void view_acc_log(View view) { Intent intent = new Intent(this, AccelerometerDBLog.class); startActivity(intent); } class WriteToDatabaseTask extends AsyncTask<AccelerometerReading, Void, Long> { private Context ctx; public WriteToDatabaseTask(Context ctx) { this.ctx = ctx; } @Override protected Long doInBackground(AccelerometerReading... params) { //Get DBHelper to write to database SensorDBHelper helper = new SensorDBHelper(ctx); SQLiteDatabase db = helper.getWritableDatabase(); if (params.length == 0) { return null; } AccelerometerReading reading = params[0]; //Put in the values within a ContentValues. ContentValues values = new ContentValues(); values.clear(); values.put(SensorsContract.AccelerometerEntry.COLUMN_TIMESTAMP, reading.getTimestampOfSample() - reading.lag_in_ms); values.put(SensorsContract.AccelerometerEntry.COLUMN_AX, reading.getAx()); values.put(SensorsContract.AccelerometerEntry.COLUMN_AY, reading.getAy()); values.put(SensorsContract.AccelerometerEntry.COLUMN_AZ, reading.getAz()); //Insert the values into the Table for Accelerometer db.insertWithOnConflict( SensorsContract.AccelerometerEntry.TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_IGNORE); return reading.getTimestampOfSample(); } } }
true
3de5e7dea9485d578f8e911a909ac77cd22b0ea7
Java
Evegen55/ForStudySpb
/src/_java/_7_0/_05_Exceptions_Errors/_task01/DirAndFileFilter.java
UTF-8
466
2.90625
3
[]
no_license
package _java._7_0._05_Exceptions_Errors._task01; import java.io.File; import java.io.FilenameFilter; import java.util.regex.Pattern; public class DirAndFileFilter implements FilenameFilter { private Pattern pattern; /** * @param pattern */ public DirAndFileFilter(String regex) { pattern = Pattern.compile(regex); } @Override public boolean accept(File dir, String name) { return pattern.matcher(name).matches(); } }
true
aa5aa7fdaeffcbed4513d8eb332ebacb046aab02
Java
deanalvero/upload-picture-browser
/upb-android/app/src/main/java/com/deanalvero/upb/network/LoginServiceRetrofitImpl.java
UTF-8
3,293
2.4375
2
[]
no_license
package com.deanalvero.upb.network; import android.util.Log; import com.deanalvero.upb.Constant; import com.deanalvero.upb.model.RLoginResponse; import com.deanalvero.upb.model.RRegisterResponse; import java.util.HashMap; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by dean on 09/08/16. */ public class LoginServiceRetrofitImpl implements ILoginService { private static final String TAG = LoginServiceRetrofitImpl.class.getSimpleName(); private UPBRetrofitService.UPBApi mUpbApi; public LoginServiceRetrofitImpl(UPBRetrofitService.UPBApi upbApi){ this.mUpbApi = upbApi; } @Override public void register(String username, String password, final RegisterCallback callback) { HashMap<String, Object> params = new HashMap<>(); params.put("username", username); params.put("password", password); Call<RRegisterResponse> call = mUpbApi.register(params); call.enqueue(new Callback<RRegisterResponse>() { @Override public void onResponse(Call<RRegisterResponse> call, Response<RRegisterResponse> response) { if (response.isSuccessful()){ RRegisterResponse rResponse = response.body(); String resultCode = rResponse.getResultCode(); if (resultCode.equals(Constant.SERVER_CODE_USER_ADDED)){ callback.onSuccess(); } else if (resultCode.equals(Constant.SERVER_CODE_USER_EXISTS)){ callback.onError(Constant.CODE_ERROR_USER_TAKEN); } else { callback.onFailure(); } } else { callback.onFailure(); } } @Override public void onFailure(Call<RRegisterResponse> call, Throwable t) { callback.onFailure(); } }); } @Override public void login(String username, String password, final LoginCallback callback) { HashMap<String, Object> params = new HashMap<>(); params.put("username", username); params.put("password", password); Call<RLoginResponse> call = mUpbApi.login(params); call.enqueue(new Callback<RLoginResponse>() { @Override public void onResponse(Call<RLoginResponse> call, Response<RLoginResponse> response) { if (response.isSuccessful()){ RLoginResponse rResponse = response.body(); String resultCode = rResponse.getResultCode(); if (resultCode.equals(Constant.SERVER_CODE_SUCCESS)){ callback.onSuccess(); } else if (resultCode.equals(Constant.SERVER_CODE_ERROR_LOGIN)){ callback.onError(Constant.CODE_ERROR_USER_AUTH); } else { callback.onFailure(); } } else { callback.onFailure(); } } @Override public void onFailure(Call<RLoginResponse> call, Throwable t) { callback.onFailure(); } }); } }
true
33f0ac62a48b63c0bb599111d782720e32d4b99d
Java
sammcilroy/javatut
/JavaTut/src/RelOps.java
UTF-8
1,376
4
4
[]
no_license
import java.util.*; import java.util.stream.IntStream; public class RelOps { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // Relational Operators : == != > < >= <= // Logical Operators ! && || int age = 12; if((age > 5) && (age<=6)) { System.out.println("Go to Kindergarten"); } else if ((age > 7) && (age <=13)) { System.out.println("Go to Middle School"); } else if ((age > 14) && (age <=18)) { System.out.println("Go to High School"); } else { System.out.println("Stay Home"); } System.out.println("true || false = " + (true || false)); System.out.println("!true = " + (!true)); // ternary operator boolean canVote = (age >= 18) ? true : false; System.out.println("Can vote : " + canVote); // switch statement String lang = "England"; switch(lang) { case "Chile" : case "Cuba" : System.out.println("Hola"); break; case "France" : System.out.println("Bonjour"); break; case "Japan" : System.out.println("Konnichiwa"); break; default : System.out.println("Hello"); } } }
true
1a88841962b96a60fba2535e33e47ace5f76a039
Java
folaulau/javascript
/javascript-api/src/main/java/com/lovemesomecoding/config/RestMVCConfig.java
UTF-8
2,601
2.28125
2
[ "MIT" ]
permissive
package com.lovemesomecoding.config; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration public class RestMVCConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedHeaders("*").allowedMethods("*").allowedOrigins("*"); } }; } @Bean public ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new Jdk8Module()); // Serialization // Serialization objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false); objectMapper.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, true); objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true); objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true); objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true); // Deserialization objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false); objectMapper.setSerializationInclusion(Include.NON_NULL); // Date and Time Format objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)); objectMapper.setTimeZone(TimeZone.getTimeZone("UTC")); objectMapper.setSerializationInclusion(Include.NON_NULL); objectMapper.registerModule(new JavaTimeModule()); return objectMapper; } }
true
eba3f6753555efc790fa92edad7975d822914aa4
Java
Blychro/miradi-client
/tests/org/miradi/project/TestSimpleThreatFormula.java
UTF-8
8,899
2.03125
2
[]
no_license
/* Copyright 2005-2018, Foundations of Success, Bethesda, Maryland on behalf of the Conservation Measures Partnership ("CMP"). Material developed between 2005-2013 is jointly copyright by Beneficent Technology, Inc. ("The Benetech Initiative"), Palo Alto, California. This file is part of Miradi Miradi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. Miradi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Miradi. If not, see <http://www.gnu.org/licenses/>. */ package org.miradi.project; import org.miradi.ids.BaseId; import org.miradi.ids.FactorId; import org.miradi.main.MiradiTestCase; import org.miradi.project.threatrating.SimpleThreatFormula; import org.miradi.project.threatrating.SimpleThreatRatingFramework; import org.miradi.project.threatrating.ThreatRatingBundle; public class TestSimpleThreatFormula extends MiradiTestCase { public TestSimpleThreatFormula(String name) { super(name); } @Override public void setUp() throws Exception { super.setUp(); project = ProjectForTesting.createProjectWithDefaultObjects(getName()); framework = project.getSimpleThreatRatingFramework(); formula = new SimpleThreatFormula(framework); } @Override public void tearDown() throws Exception { project.close(); project = null; super.tearDown(); } public void testWithOldModel() { String BAD_LABEL = "Non-Existant Label"; assertNull("found non-existant criterion?", framework.findCriterionByLabel(BAD_LABEL)); } public void testComputeMagnitude() { verifyMagnitudeCalculation(4, 4, 4); verifyMagnitudeCalculation(4, 3, 3); verifyMagnitudeCalculation(4, 2, 2); verifyMagnitudeCalculation(4, 1, 1); verifyMagnitudeCalculation(3, 4, 3); verifyMagnitudeCalculation(3, 3, 3); verifyMagnitudeCalculation(3, 2, 2); verifyMagnitudeCalculation(3, 1, 1); verifyMagnitudeCalculation(2, 4, 2); verifyMagnitudeCalculation(2, 3, 2); verifyMagnitudeCalculation(2, 2, 2); verifyMagnitudeCalculation(2, 1, 1); verifyMagnitudeCalculation(1, 4, 1); verifyMagnitudeCalculation(1, 3, 1); verifyMagnitudeCalculation(1, 2, 1); verifyMagnitudeCalculation(1, 1, 1); verifyMagnitudeCalculation(0, 4, 0); verifyMagnitudeCalculation(0, 3, 0); verifyMagnitudeCalculation(0, 2, 0); verifyMagnitudeCalculation(0, 1, 0); verifyMagnitudeCalculation(1, 0, 0); verifyMagnitudeCalculation(2, 0, 0); verifyMagnitudeCalculation(3, 0, 0); verifyMagnitudeCalculation(4, 0, 0); } public void testInvalidScopeAndSeverity() { try { formula.computeMagnitude(0, 1); } catch (RuntimeException IgnoreExpected) { } try { formula.computeMagnitude(1, 0); } catch (RuntimeException IgnoreExpected) { } } public void verifyMagnitudeCalculation(int scope, int severity, int magnitude) { String label = "wrong magnitude for " + scope + " " + severity; assertEquals(label, magnitude, formula.computeMagnitude(scope, severity)); } public void testComputeSeriousness() { verifySeriousnessCalculation(4, 4, 4); verifySeriousnessCalculation(4, 3, 4); verifySeriousnessCalculation(4, 2, 4); verifySeriousnessCalculation(4, 1, 3); verifySeriousnessCalculation(3, 4, 4); verifySeriousnessCalculation(3, 3, 3); verifySeriousnessCalculation(3, 2, 3); verifySeriousnessCalculation(3, 1, 2); verifySeriousnessCalculation(2, 4, 3); verifySeriousnessCalculation(2, 3, 2); verifySeriousnessCalculation(2, 2, 2); verifySeriousnessCalculation(2, 1, 1); verifySeriousnessCalculation(1, 4, 2); verifySeriousnessCalculation(1, 3, 1); verifySeriousnessCalculation(1, 2, 1); verifySeriousnessCalculation(1, 1, 1); verifySeriousnessCalculation(0, 4, 0); verifySeriousnessCalculation(0, 3, 0); verifySeriousnessCalculation(0, 2, 0); verifySeriousnessCalculation(0, 1, 0); verifySeriousnessCalculation(1, 0, 0); verifySeriousnessCalculation(2, 0, 0); verifySeriousnessCalculation(3, 0, 0); verifySeriousnessCalculation(4, 0, 0); } public void verifySeriousnessCalculation(int magnitude, int irreversibility, int seriousness) { String label = "wrong seriousness for " + magnitude + " " + irreversibility; assertEquals(label, seriousness, formula.computeSeriousness(magnitude, irreversibility)); } public void testInvalidMagnitudeAndSeriousness() { try { formula.computeSeriousness(0, 1); } catch (RuntimeException IgnoreExpected) { } try { formula.computeSeriousness(1, 0); } catch (RuntimeException IgnoreExpected) { } } public void testComputeBundleValue() { verifyComputeBundleValue(0, 0, 0, 0); verifyComputeBundleValue(1, 1, 1, 1); verifyComputeBundleValue(2, 2, 2, 2); verifyComputeBundleValue(3, 3, 3, 3); verifyComputeBundleValue(4, 4, 4, 4); } public void verifyComputeBundleValue(int scope, int severity, int irreversibility, int bundleValue) { String label = "wrong bundle value for " + scope + " " + severity + " " + irreversibility + " " + bundleValue; assertEquals(label, formula.computeBundleValue(scope, severity, irreversibility), bundleValue); } public void testGetBundleValues() throws Exception { BaseId scopeId = framework.findCriterionByLabel("Scope").getId(); BaseId severityId = framework.findCriterionByLabel("Severity").getId(); BaseId urgencyId = framework.findCriterionByLabel("Irreversibility").getId(); BaseId veryHighId = framework.findValueOptionByNumericValue(4).getId(); BaseId highId = framework.findValueOptionByNumericValue(3).getId(); BaseId none = framework.findValueOptionByNumericValue(0).getId(); ThreatRatingBundle bundle = new ThreatRatingBundle(new FactorId(1), new FactorId(2), none); assertEquals("empty bundle value not zero? ", 0, formula.computeBundleValue(bundle)); bundle.setValueId(scopeId, veryHighId); bundle.setValueId(severityId, veryHighId); assertEquals("bundle missing value not zero?", 0, formula.computeBundleValue(bundle)); bundle.setValueId(urgencyId, highId); assertEquals("right bundle value? ", 4, formula.computeBundleValue(bundle)); } public void testGetSummaryOfBundles() { int[] bundles; bundles = new int[] {}; assertEquals(0, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {0, 0, 0,}; assertEquals(0, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {1, 1, 1, 1, 1, 1, 1,}; assertEquals(1, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,}; assertEquals(2, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {2, 2, 2, 2, 2, 2, 2, 2, 2, 2,}; assertEquals(3, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {3, 3, 3, 3, 3, 3,}; assertEquals(4, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {2, 3, 1, 4, 2,}; assertEquals(3, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3,}; assertEquals(3, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); bundles = new int[] {4, 4,}; assertEquals(4, formula.getSummaryOfBundlesWithTwoPrimeRule(bundles)); } public void testGetHighestValue() { int targetRatings[]; targetRatings = new int[] {0, 0, 0, 0}; assertEquals(0, formula.getHighestValue(targetRatings)); targetRatings = new int[] {0, 1, 1, 1}; assertEquals(1, formula.getHighestValue(targetRatings)); targetRatings = new int[] {0, 4, 2, 3, 3}; assertEquals(4, formula.getHighestValue(targetRatings)); } public void testGetMajority() { int allTargets[]; allTargets = new int[] {3, 3, 1}; assertEquals(3, formula.getMajority(allTargets)); allTargets = new int[] {3, 3, 3, 1}; assertEquals(3, formula.getMajority(allTargets)); allTargets = new int[] {2, 2, 2, 3, 3, 4, 4}; assertEquals(3, formula.getMajority(allTargets)); allTargets = new int[] {2, 2, 4, 4, 4, 4}; assertEquals(4, formula.getMajority(allTargets)); allTargets = new int[] {1, 1, 2, 2}; assertEquals(1, formula.getMajority(allTargets)); allTargets = new int[] {1}; assertEquals(1, formula.getMajority(allTargets)); try { allTargets = new int[] {33}; assertEquals(1, formula.getMajority(allTargets)); } catch (RuntimeException IgnoreExpected) { } } private ProjectForTesting project; private SimpleThreatRatingFramework framework; private SimpleThreatFormula formula; }
true
bd4ffe246082183ea2ff1d06a3293b30ab9614e3
Java
Hankers3/redstar
/redstar/redstar-p2pbiz/src/main/java/cn/com/fero/domain/loan/entity/Debt.java
UTF-8
15,644
2.171875
2
[]
no_license
/* --------------------------------------------------------------------------------------------------- * Copyright (C) 2014-2015 fero.com.cn * * Title: Debt.java * Description: 实体Debt类定义 * * Dependencies: * * History: * Date Modifier Log * 2016-05-24 fero auto Created * * --------------------------------------------------------------------------------------------------- */ package cn.com.fero.domain.loan.entity; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class Debt implements Serializable { /** * SVU */ private static final long serialVersionUID = 1L; /**ID*/ private String id; /**债权转让编号*/ private String debtCode; /**转让项目名*/ private String debtTitle; /**产品编号*/ private String productCode; /**转让价格*/ private BigDecimal debtAmount; /**转让后实收*/ private BigDecimal debtActAmount; /**最高转让价格*/ private BigDecimal maxDebtAmount; /**最低转让价格*/ private BigDecimal minDebtAmount; /**转让实际时间*/ private Date actualTime; /**转让申请时间*/ private Date applyTime; /**转让起始时间*/ private Date startTime; /**转让截止时间*/ private Date endTime; /**项目到期日期*/ private Date loanEndTime; /**转让预期收益*/ private BigDecimal interestRates; /**转让年化收益率*/ private BigDecimal rate; /**已收益金额*/ private BigDecimal incomeAmount; /**已收益期限*/ private Integer earningsAmount; /**剩余本金(或原本金)*/ private BigDecimal remainingPrincipal; /**剩余期限(或原期限)*/ private Integer remainingLimit; /**期限单位*/ private String limitUnit; /**期限天数*/ private Integer limitDays; /**计息方式*/ private String drawType; /**已计息待收收益*/ private BigDecimal currentInterest; /**未计息待收收益*/ private BigDecimal withoutReceivableInterest; /**下次还款日期*/ private Date nextPaymentDate; /**项目价值*/ private BigDecimal loanAmount; /**服务费*/ private BigDecimal serviceFee; /**服务费率*/ private BigDecimal serviceRate; /**项目盈亏率*/ private BigDecimal profitLossRate; /**最终收款*/ private BigDecimal finalPayment; /**转让状态*/ private String status; /**是否显示到前台*/ private String showFlag; /**融资编号*/ private String loanCode; /**原投资编号*/ private String oldInvestCode; /**转让人USERID*/ private String debtUserId; /**转让形式*/ private String transForm; /**可否分割*/ private String canPartition; /**转让次数*/ private Integer transferNumber; /**原始收益率*/ private BigDecimal originalInvestRate; /**创建时间*/ private Date createTime; /**更新时间*/ private Date updateTime; /**创建者*/ private String createUserId; /**更新者*/ private String updateUserId; /**版本*/ private Integer version; public Debt() { } /**获取ID*/ public String getId() { return id; } /**设置ID*/ public void setId(String id) { this.id = id; } /**获取债权转让编号*/ public String getDebtCode() { return debtCode; } /**设置债权转让编号*/ public void setDebtCode(String debtCode) { this.debtCode = debtCode; } /**获取转让项目名*/ public String getDebtTitle() { return debtTitle; } /**设置转让项目名*/ public void setDebtTitle(String debtTitle) { this.debtTitle = debtTitle; } /**获取产品编号*/ public String getProductCode() { return productCode; } /**设置产品编号*/ public void setProductCode(String productCode) { this.productCode = productCode; } /**获取转让价格*/ public BigDecimal getDebtAmount() { return debtAmount; } /**设置转让价格*/ public void setDebtAmount(BigDecimal debtAmount) { this.debtAmount = debtAmount; } /**获取转让后实收*/ public BigDecimal getDebtActAmount() { return debtActAmount; } /**设置转让后实收*/ public void setDebtActAmount(BigDecimal debtActAmount) { this.debtActAmount = debtActAmount; } /**获取最高转让价格*/ public BigDecimal getMaxDebtAmount() { return maxDebtAmount; } /**设置最高转让价格*/ public void setMaxDebtAmount(BigDecimal maxDebtAmount) { this.maxDebtAmount = maxDebtAmount; } /**获取最低转让价格*/ public BigDecimal getMinDebtAmount() { return minDebtAmount; } /**设置最低转让价格*/ public void setMinDebtAmount(BigDecimal minDebtAmount) { this.minDebtAmount = minDebtAmount; } /**获取转让实际时间*/ public Date getActualTime() { return actualTime; } /**设置转让实际时间*/ public void setActualTime(Date actualTime) { this.actualTime = actualTime; } /**获取转让申请时间*/ public Date getApplyTime() { return applyTime; } /**设置转让申请时间*/ public void setApplyTime(Date applyTime) { this.applyTime = applyTime; } /**获取转让起始时间*/ public Date getStartTime() { return startTime; } /**设置转让起始时间*/ public void setStartTime(Date startTime) { this.startTime = startTime; } /**获取转让截止时间*/ public Date getEndTime() { return endTime; } /**设置转让截止时间*/ public void setEndTime(Date endTime) { this.endTime = endTime; } /**获取项目到期日期*/ public Date getLoanEndTime() { return loanEndTime; } /**设置项目到期日期*/ public void setLoanEndTime(Date loanEndTime) { this.loanEndTime = loanEndTime; } /**获取转让预期收益*/ public BigDecimal getInterestRates() { return interestRates; } /**设置转让预期收益*/ public void setInterestRates(BigDecimal interestRates) { this.interestRates = interestRates; } /**获取转让年化收益率*/ public BigDecimal getRate() { return rate; } /**设置转让年化收益率*/ public void setRate(BigDecimal rate) { this.rate = rate; } /**获取已收益金额*/ public BigDecimal getIncomeAmount() { return incomeAmount; } /**设置已收益金额*/ public void setIncomeAmount(BigDecimal incomeAmount) { this.incomeAmount = incomeAmount; } /**获取已收益期限*/ public Integer getEarningsAmount() { return earningsAmount; } /**设置已收益期限*/ public void setEarningsAmount(Integer earningsAmount) { this.earningsAmount = earningsAmount; } /**获取剩余本金(或原本金)*/ public BigDecimal getRemainingPrincipal() { return remainingPrincipal; } /**设置剩余本金(或原本金)*/ public void setRemainingPrincipal(BigDecimal remainingPrincipal) { this.remainingPrincipal = remainingPrincipal; } /**获取剩余期限(或原期限)*/ public Integer getRemainingLimit() { return remainingLimit; } /**设置剩余期限(或原期限)*/ public void setRemainingLimit(Integer remainingLimit) { this.remainingLimit = remainingLimit; } /**获取期限单位*/ public String getLimitUnit() { return limitUnit; } /**设置期限单位*/ public void setLimitUnit(String limitUnit) { this.limitUnit = limitUnit; } /**获取期限天数*/ public Integer getLimitDays() { return limitDays; } /**设置期限天数*/ public void setLimitDays(Integer limitDays) { this.limitDays = limitDays; } /**获取计息方式*/ public String getDrawType() { return drawType; } /**设置计息方式*/ public void setDrawType(String drawType) { this.drawType = drawType; } /**获取已计息待收收益*/ public BigDecimal getCurrentInterest() { return currentInterest; } /**设置已计息待收收益*/ public void setCurrentInterest(BigDecimal currentInterest) { this.currentInterest = currentInterest; } /**获取未计息待收收益*/ public BigDecimal getWithoutReceivableInterest() { return withoutReceivableInterest; } /**设置未计息待收收益*/ public void setWithoutReceivableInterest(BigDecimal withoutReceivableInterest) { this.withoutReceivableInterest = withoutReceivableInterest; } /**获取下次还款日期*/ public Date getNextPaymentDate() { return nextPaymentDate; } /**设置下次还款日期*/ public void setNextPaymentDate(Date nextPaymentDate) { this.nextPaymentDate = nextPaymentDate; } /**获取项目价值*/ public BigDecimal getLoanAmount() { return loanAmount; } /**设置项目价值*/ public void setLoanAmount(BigDecimal loanAmount) { this.loanAmount = loanAmount; } /**获取服务费*/ public BigDecimal getServiceFee() { return serviceFee; } /**设置服务费*/ public void setServiceFee(BigDecimal serviceFee) { this.serviceFee = serviceFee; } /**获取服务费率*/ public BigDecimal getServiceRate() { return serviceRate; } /**设置服务费率*/ public void setServiceRate(BigDecimal serviceRate) { this.serviceRate = serviceRate; } /**获取项目盈亏率*/ public BigDecimal getProfitLossRate() { return profitLossRate; } /**设置项目盈亏率*/ public void setProfitLossRate(BigDecimal profitLossRate) { this.profitLossRate = profitLossRate; } /**获取最终收款*/ public BigDecimal getFinalPayment() { return finalPayment; } /**设置最终收款*/ public void setFinalPayment(BigDecimal finalPayment) { this.finalPayment = finalPayment; } /**获取转让状态*/ public String getStatus() { return status; } /**设置转让状态*/ public void setStatus(String status) { this.status = status; } /**获取是否显示到前台*/ public String getShowFlag() { return showFlag; } /**设置是否显示到前台*/ public void setShowFlag(String showFlag) { this.showFlag = showFlag; } /**获取融资编号*/ public String getLoanCode() { return loanCode; } /**设置融资编号*/ public void setLoanCode(String loanCode) { this.loanCode = loanCode; } /**获取原投资编号*/ public String getOldInvestCode() { return oldInvestCode; } /**设置原投资编号*/ public void setOldInvestCode(String oldInvestCode) { this.oldInvestCode = oldInvestCode; } /**获取转让人USERID*/ public String getDebtUserId() { return debtUserId; } /**设置转让人USERID*/ public void setDebtUserId(String debtUserId) { this.debtUserId = debtUserId; } /**获取转让形式*/ public String getTransForm() { return transForm; } /**设置转让形式*/ public void setTransForm(String transForm) { this.transForm = transForm; } /**获取可否分割*/ public String getCanPartition() { return canPartition; } /**设置可否分割*/ public void setCanPartition(String canPartition) { this.canPartition = canPartition; } /**获取转让次数*/ public Integer getTransferNumber() { return transferNumber; } /**设置转让次数*/ public void setTransferNumber(Integer transferNumber) { this.transferNumber = transferNumber; } /**获取原始收益率*/ public BigDecimal getOriginalInvestRate() { return originalInvestRate; } /**设置原始收益率*/ public void setOriginalInvestRate(BigDecimal originalInvestRate) { this.originalInvestRate = originalInvestRate; } /**获取创建时间*/ public Date getCreateTime() { return createTime; } /**设置创建时间*/ public void setCreateTime(Date createTime) { this.createTime = createTime; } /**获取更新时间*/ public Date getUpdateTime() { return updateTime; } /**设置更新时间*/ public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } /**获取创建者*/ public String getCreateUserId() { return createUserId; } /**设置创建者*/ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /**获取更新者*/ public String getUpdateUserId() { return updateUserId; } /**设置更新者*/ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /**获取版本*/ public Integer getVersion() { return version; } /**设置版本*/ public void setVersion(Integer version) { this.version = version; } public String toString() { return "Debt [" + ", id=" + id + ", debtCode=" + debtCode + ", debtTitle=" + debtTitle + ", productCode=" + productCode + ", debtAmount=" + debtAmount + ", debtActAmount=" + debtActAmount + ", maxDebtAmount=" + maxDebtAmount + ", minDebtAmount=" + minDebtAmount + ", actualTime=" + actualTime + ", applyTime=" + applyTime + ", startTime=" + startTime + ", endTime=" + endTime + ", loanEndTime=" + loanEndTime + ", interestRates=" + interestRates + ", rate=" + rate + ", incomeAmount=" + incomeAmount + ", earningsAmount=" + earningsAmount + ", remainingPrincipal=" + remainingPrincipal + ", remainingLimit=" + remainingLimit + ", limitUnit=" + limitUnit + ", limitDays=" + limitDays + ", drawType=" + drawType + ", currentInterest=" + currentInterest + ", withoutReceivableInterest=" + withoutReceivableInterest + ", nextPaymentDate=" + nextPaymentDate + ", loanAmount=" + loanAmount + ", serviceFee=" + serviceFee + ", serviceRate=" + serviceRate + ", profitLossRate=" + profitLossRate + ", finalPayment=" + finalPayment + ", status=" + status + ", showFlag=" + showFlag + ", loanCode=" + loanCode + ", oldInvestCode=" + oldInvestCode + ", debtUserId=" + debtUserId + ", transForm=" + transForm + ", canPartition=" + canPartition + ", transferNumber=" + transferNumber + ", originalInvestRate=" + originalInvestRate + ", createTime=" + createTime + ", updateTime=" + updateTime + ", createUserId=" + createUserId + ", updateUserId=" + updateUserId + ", version=" + version + "]"; } }
true
ca9f2bb5fbde622111e4de967d60c0eca1f87162
Java
codesquad-member-2020/todo-4
/server/src/main/java/com/codesquad/server/domain/value/ResponseDTO.java
UTF-8
258
1.625
2
[]
no_license
package com.codesquad.server.domain.value; import lombok.AllArgsConstructor; import lombok.Getter; import java.time.LocalDateTime; @Getter @AllArgsConstructor public class ResponseDTO { private Long id; private LocalDateTime historyCreatedTime; }
true
d63acc2f4be0f7924875daef57deacce4f3a5b51
Java
nahumar/java
/src/punto3/AlumnoEjercicio7.java
UTF-8
237
2.734375
3
[]
no_license
package punto3; public class AlumnoEjercicio7 { public String nombre; public AlumnoEjercicio7(String nombre ) { this.nombre = nombre; } @Override public String toString() { return "Alumno [nombre=" + this.nombre+"]"; } }
true
eef4309302441d6e5f367e8dd4a7d5a851fdd31a
Java
selfOfDiscipline/salary
/src/main/java/com/tyzq/salary/model/vo/user/UserBaseResultVO.java
UTF-8
5,794
2.296875
2
[]
no_license
package com.tyzq.salary.model.vo.user; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * @ProJectName: salary * @Author: zwc zwc_503@163.com * @CreateTime: 2020-09-18 17:14 * @Description: //TODO 用户基本信息返回结果VO **/ public class UserBaseResultVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键id */ private Long id; /** * 姓名 */ private String userName; /** * 用户证件号 */ private String userCard; /** * 用户手机号 */ private String userTel; /** * 用户账号 */ private String userAccount; /** * 用户邮箱 */ private String userEmail; /** * 用户性别:0--男,1--女 */ private Integer userSex; /** * 入职日期 */ private Date userEntryDate; /** * 预计转正日期 */ private Date planChangeFormalDate; /** * 户口类型:0--城镇,1--农村 */ private Integer householdType; /** * 工作城市 */ private String workCity; /** * 员工岗位类型:0--管理岗,1--成本岗,2--技术岗 */ private Integer userPostType; /** * 员工在职类型:0--试用期,1--正式,2--离职 */ private Integer userRankType; /** * 员工标准薪资 */ private BigDecimal standardSalary; /** * 薪资发放比例 */ private BigDecimal salaryGrantRatio; /** * 计算后的员工计薪工资=员工标准薪资*薪资发放比例 */ private BigDecimal computeStandardSalary; /** * 绩效占工资比例 */ private BigDecimal performanceRatio; /** * 业务归属部门名称 */ private String userDeptName; /** * 薪资归属部门名称 */ private String salaryDeptName; /** * 职位 */ private String roleName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserCard() { return userCard; } public void setUserCard(String userCard) { this.userCard = userCard; } public String getUserTel() { return userTel; } public void setUserTel(String userTel) { this.userTel = userTel; } public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public Integer getUserSex() { return userSex; } public void setUserSex(Integer userSex) { this.userSex = userSex; } public Date getUserEntryDate() { return userEntryDate; } public void setUserEntryDate(Date userEntryDate) { this.userEntryDate = userEntryDate; } public Date getPlanChangeFormalDate() { return planChangeFormalDate; } public void setPlanChangeFormalDate(Date planChangeFormalDate) { this.planChangeFormalDate = planChangeFormalDate; } public Integer getHouseholdType() { return householdType; } public void setHouseholdType(Integer householdType) { this.householdType = householdType; } public String getWorkCity() { return workCity; } public void setWorkCity(String workCity) { this.workCity = workCity; } public Integer getUserPostType() { return userPostType; } public void setUserPostType(Integer userPostType) { this.userPostType = userPostType; } public Integer getUserRankType() { return userRankType; } public void setUserRankType(Integer userRankType) { this.userRankType = userRankType; } public BigDecimal getStandardSalary() { return standardSalary; } public void setStandardSalary(BigDecimal standardSalary) { this.standardSalary = standardSalary; } public BigDecimal getSalaryGrantRatio() { return salaryGrantRatio; } public void setSalaryGrantRatio(BigDecimal salaryGrantRatio) { this.salaryGrantRatio = salaryGrantRatio; } public BigDecimal getComputeStandardSalary() { return computeStandardSalary; } public void setComputeStandardSalary(BigDecimal computeStandardSalary) { this.computeStandardSalary = computeStandardSalary; } public BigDecimal getPerformanceRatio() { return performanceRatio; } public void setPerformanceRatio(BigDecimal performanceRatio) { this.performanceRatio = performanceRatio; } public String getUserDeptName() { return userDeptName; } public void setUserDeptName(String userDeptName) { this.userDeptName = userDeptName; } public String getSalaryDeptName() { return salaryDeptName; } public void setSalaryDeptName(String salaryDeptName) { this.salaryDeptName = salaryDeptName; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } }
true