text stringlengths 10 2.72M |
|---|
package edu.palindrome.sweezy.kenneth;
import edu.jenks.dist.palindrome.*;
public class PalindromeChecker extends AbstractPalindromeChecker {
public static void main(String[] args) {
PalindromeChecker instance = new PalindromeChecker();
System.out.println(instance.isPalindrome("%%"));
}
public boolean isPalindrome(String input) {
String symbolsRemoved = correctSymbols(input);
System.out.println(symbolsRemoved);
int stringLength = symbolsRemoved.length();
double midPointRound = stringLength / 2;
int midPoint = (int)midPointRound;
if(symbolsRemoved.equals("")) {
return false;
}
for(int i = 0; i < midPoint; i++) {
if(symbolsRemoved.charAt((midPoint + 1) - i) == symbolsRemoved.charAt((midPoint - 1) + i)){
continue;
} else {
return false;
}
}
return true;
}
public String correctSymbols(String input) {
System.out.println(input.replaceAll("\\W", "").toUpperCase());
return input.replaceAll("\\W", "").toUpperCase();
}
} |
package com.hlx.view.play;
import com.hlx.model.Score;
import com.hlx.view.common.BackgroundLabel;
import com.hlx.view.common.TipLabel;
import com.hlx.view.common.TranslucentPanel;
/**
* The component that serve the RankPanel
* @author hlx
* @version 1.0 2018-3-21
*/
public class ScorePanel extends TranslucentPanel{
private TipLabel scoreLabel;
private TipLabel userLabel;
private BackgroundLabel changeLabel;
public ScorePanel(int level) {
super();
this.setLayout(null);
this.setSize(180, 30);
this.setTransparency((float) 0);
initLevelLabel(level);
initUserLabel();
initScoreLabel();
initChangeLabel();
}
private void initChangeLabel() {
String imgUrl = "view/image/change/0.png";
changeLabel = new BackgroundLabel(imgUrl);
changeLabel.setLocation(165,5);
this.add(changeLabel);
}
private void initScoreLabel() {
scoreLabel = new TipLabel("", 13);
scoreLabel.setBounds(120, 5, 35, 15);
this.add(scoreLabel);
}
private void initUserLabel() {
userLabel = new TipLabel("", 13);
userLabel.setBounds(70, 5, 40, 15);
this.add(userLabel);
}
private void initLevelLabel(int level) {
String imgUrl = "view/image/level/" + level + ".png";
BackgroundLabel levelLabel = new BackgroundLabel(imgUrl);
levelLabel.setLocation(0,0);
this.add(levelLabel);
}
public void setScore(Score score) {
scoreLabel.setText("" + score.getNumber());
userLabel.setText(score.getId() + "号");
changeLabel.setImage("view/image/change/" + score.getChange() + ".png");
}
public void clear() {
changeLabel.setImage("view/image/change/0.png");
userLabel.setText("");
scoreLabel.setText("");
}
}
|
package com.lovers.base.service;
import com.lovers.base.mapper.BaseMapper;
/**
* @Auther: wangzefeng
* @Date: 2019-09-27 22:14
* @Description:
*/
public interface BaseService<E,PK> {
int insert(E e);
int deleteByPrimaryKey(PK pk);
E selectByPrimaryKey(PK pk);
int updateByPrimaryKey(E e);
}
|
package shop.itis.kpfu.ru.server;
import shop.itis.kpfu.ru.client.GreetingService;
import org.springframework.stereotype.Service;
@Service("greetingService")
public class GreetingServiceImpl implements GreetingService {
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}
|
package com.example.studentmanagment;
import java.io.File;
import java.io.FileNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class InsertPersonalDetailsActivity extends Activity implements
OnClickListener {
String branch, year, course,name,fname,mname,address,paddress,collegeId,dob,contact,fcontact,email;
EditText t1, t2, t3, t4, t5, t6, t7, t8, t9, t10;
ImageView iv1;
Button b1;
String realPath="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_personal_details);
Intent i = getIntent();
branch = i.getStringExtra("branch");
year = i.getStringExtra("year");
course = i.getStringExtra("course");
t1 = (EditText) findViewById(R.id.editText1);
t2 = (EditText) findViewById(R.id.editText2);
t3 = (EditText) findViewById(R.id.editText3);
t4 = (EditText) findViewById(R.id.editText4);
t5 = (EditText) findViewById(R.id.editText5);
t6 = (EditText) findViewById(R.id.editText6);
t7 = (EditText) findViewById(R.id.editText7);
t8 = (EditText) findViewById(R.id.editText8);
t9 = (EditText) findViewById(R.id.editText9);
t10 = (EditText) findViewById(R.id.editText10);
b1 = (Button) findViewById(R.id.editText11);
iv1 = (ImageView) findViewById(R.id.imageView1);
b1.setOnClickListener(this);
iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int reqcode = 1;
Intent action = new Intent(Intent.ACTION_GET_CONTENT);
action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(action, reqcode);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.insert_personal_details, menu);
return true;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.editText11:
collegeId=t1.getText().toString();
name=t2.getText().toString();
fname=t3.getText().toString();
mname=t4.getText().toString();
address=t5.getText().toString();
paddress=t6.getText().toString();
dob=t7.getText().toString();
contact=t9.getText().toString();
email=t8.getText().toString();
fcontact=t10.getText().toString();
Intent i=new Intent(InsertPersonalDetailsActivity.this,InsertAcadmicDetailsActivity.class);
i.putExtra("imagePath", realPath);
i.putExtra("collegeId", collegeId);
i.putExtra("name", name);
i.putExtra("fname", fname);
i.putExtra("mname", mname);
i.putExtra("address", address);
i.putExtra("paddress", paddress);
i.putExtra("dob", dob);
i.putExtra("contact", contact);
i.putExtra("fcontact", fcontact);
i.putExtra("email", email);
i.putExtra("branch", branch);
i.putExtra("year",year);
i.putExtra("course",course);
startActivity(i);
break;
default:
break;
}
}
@Override
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if(resCode == Activity.RESULT_OK && data != null){
// SDK < API11
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Uri uriFromPath = Uri.fromFile(new File(realPath));
//display selected image
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uriFromPath));
if(bitmap!=null)
iv1.setImageBitmap(bitmap);
else
iv1.setBackgroundResource(R.drawable.file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
|
package com.zzwc.cms.common.utils.qiniu;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.zzwc.cms.common.exception.ZhiZhiException;
import com.zzwc.cms.common.utils.TimeUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
/**
* 七牛存储相关操作工具类
*
*/
public class QiniuUtils {
private static Logger logger = LoggerFactory.getLogger(QiniuUtils.class);
/**
* 上传文件(图片、音频等各种文件)到七牛
*
* @param file
* 待上传的文件
* @param bucketName
* 七牛上的空间名称
* @param key
* 指定的文件key
* @return 文件在七牛上的url,若上传失败则返回null
* @throws QiniuException
* @throws FileNotFoundException
*
*/
public static String uploadFileToQiuNiu(File file, String bucketName, String key)
throws QiniuException, FileNotFoundException {
if (file == null || !file.exists()) {
throw new ZhiZhiException( "上传的文件不存在");
}
UploadManager uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
String token = getToken(bucketName, null);
Response res = uploadManager.put(file, key, token);
if (res.statusCode == 200 && res.isOK()) {
logger.debug("上传成功");
return domainMap.get(bucketName)+key;
}
logger.debug("upload error!!!");
return null;
}
/**
* 获取七牛token,七牛不会检测指定空间名是否存在;猜测token是根据空间名计算出来的
*
* @param bucketName
* 空间名
* @return
*/
public static String getToken(String bucketName, String key) {
return getToken(bucketName, null, null, key);
}
private final static String ACCESS_KEY = "5WX4HInoIwWiR8dFy0Zakq2CehgXcKzS06hOsoGW";
private final static String SECRET_KEY = "BgbtKnG5JLpx88iEnGtNLeGUFrf9Jxh3J2VyPkio";
/**
* 获取七牛上传凭证
*
* @param bucketName
* 上传到的空间名称
* @param fileType
* 文件类型,file,video,image,music
* @param params
* 文件类型对应的配置参数
* @return
*/
public static String getToken(String bucketName, String fileType, Map<String, String> params, String key) {
if (StringUtils.isEmpty(bucketName)) {
throw new ZhiZhiException( "未指定七牛空间名称");
}
if (params == null) {
params = new HashMap<>();
}
Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
StringMap policy = new StringMap();
policy.put("returnBody",
"{\"key\": $(key), \"hash\": $(etag), \"mimeType\": $(mimeType),\"persistentId\":$(persistentId)}");
List<String> persistentOps = new ArrayList<>();
if ("video".equals(fileType)) {
// 是否需要截帧,默认true
boolean isNeedFrame = MapUtils.getBooleanValue(params, "isNeedFrame", true);
if (isNeedFrame) {
StringBuffer vframeFop = new StringBuffer("vframe/");
// 如果需要截帧,截成什么格式,默认jpg
String frameFormat = MapUtils.getString(params, "frameFormat", "jpg");
vframeFop.append(frameFormat);
// 如果需要截帧,从哪截,默认0.2秒处
String frameStartTime = MapUtils.getString(params, "frameStartTime", "0.2");
vframeFop.append("/offset/").append(frameStartTime);
// 保存到哪,bucket默认为方法参数中bucketName,key默认为video_poster_yyyyMMddHHmmss.截图格式
String frameSaveBucket = MapUtils.getString(params, "frameSaveBucket", bucketName);
String frameSaveKey = MapUtils.getString(params, "frameSaveKey",
"video_poster_" + TimeUtils.getDateStr(new Date(), "yyyyMMddHHmmss") + "." + frameFormat);
String bucketAndKeyUrlSafeBase64 = UrlSafeBase64.encodeToString(frameSaveBucket + ":" + frameSaveKey);
vframeFop.append("|saveas/").append(bucketAndKeyUrlSafeBase64);
persistentOps.add(vframeFop.toString());
}
// 是否需要转码,默认true
boolean isNeedTranscode = MapUtils.getBooleanValue(params, "isNeedTranscode", true);
if (isNeedTranscode) {
StringBuffer avthumbFop = new StringBuffer("avthumb/");
// 如果需要转码,转成什么格式
String transcodeFormat = MapUtils.getString(params, "transcodeFormat");
if (StringUtils.isEmpty(transcodeFormat)) {
throw new ZhiZhiException( "未指定视频转码格式");
}
avthumbFop.append(transcodeFormat);
// 视频帧率多少,默认每秒23帧
String frameRate = MapUtils.getString(params, "frameRate", "23");
avthumbFop.append("/r/").append(frameRate);
// 视频码率多少,默认2048kbps
String videoBitRate = MapUtils.getString(params, "videoBitRate", "2048k");
avthumbFop.append("/vb/").append(videoBitRate);
// 保存到哪
String vidoeSaveBucket = MapUtils.getString(params, "vidoeSaveBucket", bucketName);
String videoSaveKey = MapUtils.getString(params, "videoSaveKey",
"video_thumb_" + TimeUtils.getDateStr(new Date(), "yyyyMMddHHmmss") + "." + transcodeFormat);
String bucketAndKeyUrlSafeBase64 = UrlSafeBase64.encodeToString(vidoeSaveBucket + ":" + videoSaveKey);
avthumbFop.append("|saveas/").append(bucketAndKeyUrlSafeBase64);
persistentOps.add(avthumbFop.toString());
}
} else if ("image".equals(fileType)) {
// 图片处理
StringBuffer imageFop = new StringBuffer("imageMogr2/auto-orient");
// 旋转
String rotate = MapUtils.getString(params, "rotate");
if (params.containsKey("rotate") && StringUtils.isEmpty(rotate)) {
throw new ZhiZhiException( "未指定旋转值");
} else {
imageFop.append("/rotate/").append(rotate);
}
// TODO 其他操作需要时再处理
// 缩放
// 裁剪
// 保存到哪,默认空间为方法参数中bucketName,key为"mogr_image_yyyyMMddHHmmss.jpg"
String imageSaveBucket = MapUtils.getString(params, "imageSaveBucket", bucketName);
String imageSaveKey = MapUtils.getString(params, "imageSaveKey",
"mogr_image_" + TimeUtils.getDateStr(new Date(), "yyyyMMddHHmmss") + ".jpg");
String bucketAndKeyUrlSafeBase64 = UrlSafeBase64.encodeToString(imageSaveBucket + ":" + imageSaveKey);
imageFop.append("|saveas/").append(bucketAndKeyUrlSafeBase64);
persistentOps.add(imageFop.toString());
}
if (!persistentOps.isEmpty()) {
if (persistentOps.size() == 1) {
policy.put("persistentOps", persistentOps.get(0));
} else {
policy.put("persistentOps", String.join(";", persistentOps));
}
// 私有转码队列
String persistentPipeline = MapUtils.getString(params, "persistentPipeline");
if (!StringUtils.isEmpty(persistentPipeline)) {
policy.put("persistentPipeline", persistentPipeline);
}
}
if (StringUtils.isBlank(key)) {
key = null;
}
return auth.uploadToken(bucketName, key, 3600, policy);
}
private static Map<String, String> domainMap = new HashMap<>();
static {
domainMap.put("live", "http://pb0xhvjbh.bkt.clouddn.com/");
domainMap.put("awaken", "http://pc1mihua7.bkt.clouddn.com/");
}
/**
* 七牛处理结果另存
* <a href="http://developer.qiniu.com/code/v6/api/dora-api/saveas.html">参考 </a>
*
* @param bucketName
* 处理后的结果存储 空间名
* @param key
* 处理后的结果资源key
* @param urlWithoutSchema
* 无协议的原始资源url
* @return 处理后的子资源的url
* @throws IOException
* @throws MalformedURLException
* @throws Exception
*/
public static String saveas(String bucketName, String key, String urlWithoutSchema) throws Exception {
Assert.notNull(bucketName, "未指定空间名");
if (StringUtils.isEmpty(key)) {
key = "saveas_random_key_" + TimeUtils.getDateStr(new Date(), "yyyyMMddHHmmss");
logger.info("未指定key,生成默认key:" + key);
}
if (urlWithoutSchema.startsWith("http://")) {
urlWithoutSchema = urlWithoutSchema.substring(7);
}
String encodedEntryURI = UrlSafeBase64.encodeToString(bucketName + ":" + key);
String signingStr = urlWithoutSchema + "|saveas/" + encodedEntryURI;
byte[] enbytes = Signature.hmacSHA1Encrypt(signingStr, SECRET_KEY);
String sign = UrlSafeBase64.encodeToString(enbytes);
String fullUrl = "http://" + signingStr + "/sign/" + ACCESS_KEY + ":" + sign;
HttpURLConnection connection = (HttpURLConnection) new URL(fullUrl).openConnection();
try {
int respCode = connection.getResponseCode();
if (respCode == 200) {
String domain = domainMap.get(bucketName);
String newUrl = domain + key;
// int i = urlWithoutSchema.indexOf("/");
// String newUrl;
// if (i != -1) {
// newUrl = "http://" + urlWithoutSchema.substring(0, i) + "/" +
// key;
// } else {
// newUrl = "http://" + urlWithoutSchema + "/" + key;
// }
return newUrl;
}
} catch (UnknownHostException e) {
throw new ZhiZhiException( urlWithoutSchema,e);
}
return null;
}
public static void main(String[] args) throws Exception {
String url = saveas("test-user", "qqqqqqq3.jpg",
"http://7xlwpk.com1.z0.glb.clouddn.com/201611291322393504_1480419304179_generateImage_20161129193457_1480419297822_background.jpg_20161129193457_1480419297871_head.jpg?imageMogr2/auto-orient/rotate/300");
System.out.println(url);
}
}
|
package com.tongchuang.huangshan.admin.controller;
import com.tongchuang.huangshan.admin.annotation.Log;
import com.tongchuang.huangshan.admin.service.ISysRoleService;
import com.tongchuang.huangshan.admin.utils.SecurityUtils;
import com.tongchuang.huangshan.common.base.ResultVO;
import com.tongchuang.huangshan.common.constatnts.UserConstants;
import com.tongchuang.huangshan.common.enums.BusinessType;
import com.tongchuang.huangshan.common.enums.ResultEnum;
import com.tongchuang.huangshan.common.utils.ResultVOUtil;
import com.tongchuang.huangshan.model.domain.admin.SysRole;
import com.tongchuang.huangshan.model.dtos.admin.base.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 角色信息
*
* @author fangwenzao
*/
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
@Autowired
private ISysRoleService roleService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role)
{
startPage();
List<SysRole> list = roleService.selectRoleList(role);
return getDataTable(list);
}
/**
* 根据角色编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public ResultVO getInfo(@PathVariable Long roleId)
{
return ResultVOUtil.success(roleService.selectRoleById(roleId));
}
/**
* 新增角色
*/
@PreAuthorize("@ss.hasPermi('system:role:add')")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public ResultVO add(@Validated @RequestBody SysRole role)
{
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return ResultVOUtil.fail(ResultEnum.PARAM_ERROR,"新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return ResultVOUtil.fail(ResultEnum.PARAM_ERROR,"新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(SecurityUtils.getUsername());
return ResultVOUtil.success(roleService.insertRole(role));
}
/**
* 修改保存角色
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public ResultVO edit(@Validated @RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
{
return ResultVOUtil.fail(ResultEnum.PARAM_ERROR,"修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
}
else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
{
return ResultVOUtil.fail(ResultEnum.PARAM_ERROR,"修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(SecurityUtils.getUsername());
return ResultVOUtil.success(roleService.updateRole(role));
}
/**
* 修改保存数据权限
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public ResultVO dataScope(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
return ResultVOUtil.success(roleService.authDataScope(role));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public ResultVO changeStatus(@RequestBody SysRole role)
{
roleService.checkRoleAllowed(role);
role.setUpdateBy(SecurityUtils.getUsername());
return ResultVOUtil.success(roleService.updateRoleStatus(role));
}
/**
* 删除角色
*/
@PreAuthorize("@ss.hasPermi('system:role:remove')")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public ResultVO remove(@PathVariable Long[] roleIds)
{
return ResultVOUtil.success(roleService.deleteRoleByIds(roleIds));
}
/**
* 获取角色选择框列表
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public ResultVO optionselect()
{
return ResultVOUtil.success(roleService.selectRoleAll());
}
} |
package com.bytest.autotest.model.juzifenqi;
import lombok.Data;
/**
* <h3>tool</h3>
* <p>照片信息</p>
*
* @author : hh
* @date : 2020-03-19 23:24
**/
@Data
public class ImgNameList {
private String imageUrl;
private String imageType;
private String transportProtocol;
}
|
public class SmallTest {
public static void main(String[] args) {
String str1 = "abc" , str2;
System.out.println(str1.hashCode());
str2 = str1;
System.out.println(str1 + " " + str1.hashCode() + " " + str2 + str2.hashCode() );
str1 = str1 + "a";
System.out.println(str1 + " " + str1.hashCode() + " " + str2 + str2.hashCode() );
}
static class tester{
}
}
|
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
class Plansza extends JPanel implements MouseMotionListener, MouseListener
{
int maxAmountOfBalls = 10;
int ballCount = 1;
Belka b;
Kulka[] a = new Kulka[maxAmountOfBalls];
Color barColor;
Floor floor;
int lastMousePositionX = 325;
String brickTextureSource0 ="textures/Fabric026_1K_Color.jpg";
BufferedImage brickTextureImage0;
TexturePaint brickTexture0;
String brickTextureSource1 ="textures/Fabric023_1K_Color.jpg";
BufferedImage brickTextureImage1;
TexturePaint brickTexture1;
SilnikKulki s;
BonusEngine bonusEngine;
int rows = 3;
int columns = 12;
int liczba_kafelek = columns * rows;
int livingBricks = liczba_kafelek;
Kafelka[] k = new Kafelka[liczba_kafelek];
Bonus [] fallingBonus = new Bonus[liczba_kafelek];
//TODO: CREATE ONE THREAD TO HANDLE ALL BONUSES
int score = 0;
boolean game_over = false;
boolean engineStartFlag = false;
Plansza()
{
super();
addMouseMotionListener(this);
addMouseListener(this);
setBackground(new Color(67, 65, 75));
b=new Belka(325-40, 430);
floor=new Floor(this, 0, 455, 650);
bonusEngine = new BonusEngine(this);
for(int w=0; w<maxAmountOfBalls; w++)
a[w]=new Kulka(this,325-5,420,0,-2, false);
a[0].isAlive=true;
a[1].addDeltaX(10);
for (int i=0; i<liczba_kafelek; i++){
k[i]=new Kafelka(this, i%columns, i/columns, 650/columns);
fallingBonus[i] = new Bonus(this,i%columns, i/columns, 650/columns);
}
loadTextures();
}
void loadTextures(){
barColor = new Color(0,60,60);
try
{
File f=new File(brickTextureSource0);
brickTextureImage0 =ImageIO.read(f);
brickTexture0 = new TexturePaint(brickTextureImage0, k[0]);
File f1=new File(brickTextureSource1);
brickTextureImage1 =ImageIO.read(f1);
brickTexture1 = new TexturePaint(brickTextureImage1, k[0]);
}
catch(IOException e)
{
System.err.println("Problem z plikiem");
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon img = new ImageIcon("textures/woodenBackground.jpg");
if (img != null)
{
g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
}
Graphics2D g2d=(Graphics2D)g;
if (livingBricks==0){
s.running = false;
bonusEngine.running=false;
g2d.setPaint(new Color(63, 75, 68));
g.setFont(new Font("Dialog", Font.BOLD, 20));
g2d.drawString("YOU WON!", getSize().width/2 - 65, getSize().height/2+30);
g2d.drawString("SCORE: " + score, getSize().width/2 - 65, getSize().height/2+60);
}else{
if (!game_over){
if (engineStartFlag){
g2d.setPaint(new Color(63, 75, 68));
g.setFont(new Font("Dialog", Font.BOLD, 15));
g2d.drawString("SCORE: "+score, 20, 360);
}
g2d.setPaint(barColor);
g2d.fill(b);
g2d.setPaint(new GradientPaint(b.x,b.y, new Color(32,178,170), b.x+(int)(b.width*b.roundPercentage), b.y+b.height, barColor));
g2d.fill(new Rectangle2D.Float(b.x, b.y,(int) (b.width * b.roundPercentage), b.height));
g2d.setPaint(new GradientPaint((b.x + (int) (b.width*(1- b.roundPercentage))) ,b.y, barColor, b.x+ b.width, b.y+b.height, new Color(32,178,170)));
g2d.fill(new Rectangle2D.Float((b.x + (int) (b.width*(1- b.roundPercentage))) ,b.y, (int) (b.width * b.roundPercentage), b.height));
if(floor.isAlive){
g2d.setPaint(floor.getTexture());
g2d.fill(floor);
}
for(int i=0; i<liczba_kafelek; i++){
if (fallingBonus[i].isAlive){
//g2d.setPaint(fallingBonus[i].getTexture());
g2d.setPaint(new TexturePaint(fallingBonus[i].getTexture(), (Rectangle2D) fallingBonus[i]));
g2d.fill(fallingBonus[i]);
}
if (k[i].flaga_ZYCIA > 0){
if (k[i].flaga_ZYCIA==1)
g2d.setPaint(brickTexture0);
else if (k[i].flaga_ZYCIA==2){
g2d.setPaint(brickTexture1);
}
g2d.fill(k[i]);
}
}
g2d.setPaint(a[0].getTexture());
for(int i=0; i<maxAmountOfBalls; i++){
if(a[i].isAlive)
g2d.fill(a[i]);
}
if (!engineStartFlag){
g2d.setPaint(new Color(63, 75, 68));
g.setFont(new Font("Dialog", Font.BOLD, 20));
g2d.drawString("LEFT CLICK", 150, 320);
g2d.setPaint(new Color(76, 57, 74));
g.setFont(new Font("Dialog", Font.BOLD, 17));
g2d.drawString("TO SHOOT THE BALL!", 300, 320);
}
}else{
s.running = false;
bonusEngine.running=false;
g2d.setPaint(new Color(76, 57, 74));
g.setFont(new Font("Dialog", Font.BOLD, 20));
g2d.drawString("GAME OVER", getSize().width/2 - 65, getSize().height/2+30);
}
}
}
public void mouseMoved(MouseEvent e)
{
int mousePositionX=e.getX();
for(int i=0; i<maxAmountOfBalls; i++){
if(a[i].isAlive){
if(!a[i].isFlying){
a[i].addDeltaX(-(lastMousePositionX-mousePositionX));
a[i].setY(getSize().height - 30 -13);
}
}
}
b.setY(getSize().height - 20-13);
b.setX(e.getX()-(int) b.width/2);
if (!engineStartFlag)
repaint();
lastMousePositionX=mousePositionX;
}
public void mouseClicked(MouseEvent e){
System.out.println("CLICKED!");
if(!engineStartFlag){
engineStartFlag =true;
s=new SilnikKulki(this, a);
}
for(int w=0; w<maxAmountOfBalls; w++){
if(a[w].isAlive){
if(!a[w].isFlying){
a[w].isFlying = true;
w=maxAmountOfBalls+10;
}
}
}
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
}
|
package com.example.mohammedmansour.newsapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.mohammedmansour.newsapp.API.Responses.Everything.ArticlesItem;
import com.example.mohammedmansour.newsapp.API.Responses.Everything.Source;
public class NewsWholeContentActivity extends AppCompatActivity {
TextView title, date, desc, content, see_more;
ImageView imageView;
ArticlesItem articlesItem = null;
Source source = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_details);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra("activityLabel"));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// finish();
onBackPressed();
}
});
title = findViewById(R.id.content_title);
date = findViewById(R.id.content_date);
desc = findViewById(R.id.content_desc);
content = findViewById(R.id.content_content);
imageView = findViewById(R.id.content_image);
see_more = findViewById(R.id.see_more);
articlesItem = getIntent().getParcelableExtra("newsItem");
source = getIntent().getParcelableExtra("newsItemSource");
title.setText(articlesItem.getTitle());
date.setText(articlesItem.getPublishedAt());
desc.setText(articlesItem.getDescription());
content.setText(articlesItem.getContent());
getSupportActionBar().setTitle(articlesItem.getSource_name());
Glide.with(this).load(articlesItem.getUrlToImage())
.into(imageView);
see_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(articlesItem.getUrl()));
startActivity(i);
}
});
}
// @Override
// public void onConfigurationChanged(Configuration newConfig) {
// super.onConfigurationChanged(newConfig);
// setContentView(R.layout.activity_news_details_content);
// }
}
|
package pl.bykowski.springbootdata;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CorpseRepo extends CrudRepository<Corpse, Long> {
List<Corpse> findByName(String name);
List<Corpse> findByCorpseSize(CorpseSize corpseSize);
// nativeQuery
@Query(value = "SELECT AVG(AGE_OF_DEATH), CORPSE_SIZE FROM Corpse GROUP BY CORPSE_SIZE", nativeQuery = true)
List<Object> getAvgByAgeOfDeath();
// HQL
@Query(value = "FROM Corpse", nativeQuery = false)
List<Corpse> getAllElements();
}
|
package com.migu.spider.util;
public class ReflectUtil {
/**
* getObject: 利用反射生成对象. <br/>
*
* @author breeze
* @param path
* @return
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static Object getObject(String path) {
Object obj = null;
try {
obj = Class.forName(path).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
}
|
package com.example.test;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TransactionFragment extends Fragment {
public enum TransactionKey {
CONTENT, IMAGE
}
private String content;
private String image;
public TransactionFragment(Bundle bundle) {
if (bundle != null) {
this.content = bundle.getString(TransactionKey.CONTENT.name());
this.image = bundle.getString(TransactionKey.IMAGE.name());
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.transaction_fragment, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView textView = view.findViewById(R.id.content_field);
textView.setText("Content: " + content);
ImageView imageView = view.findViewById(R.id.bitmap);
imageView.setImageBitmap(processImageString());
}
private Bitmap processImageString() {
String[] imageSplit = image.split(",");
byte[] decodedString = Base64.decode(imageSplit[imageSplit.length - 1], Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return Bitmap.createScaledBitmap(bitmap, 800, 800, false);
}
}
|
/*
* Copyright 2013 Basho Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.basho.riak.client.api.cap;
import java.util.List;
/**
* Interface used to resolve siblings.
* <p>
* When you have multiple writers there may be multiple versions of the same
* object stored in Riak. When fetching all of these will be returned and you
* will need to resolve the conflict.
* </p>
* <p>
* To facilitate this, you can store an instance of the ConflictResolver
* in the {@link com.basho.riak.client.api.cap.ConflictResolverFactory} for a class.
* It will then be used by the {@link com.basho.riak.client.api.commands.kv.FetchValue.Response}
* to resolve a set a of siblings to a single object.
* </p>
* @author Brian Roach <roach at basho dot com>
* @since 2.0
* @param <T> The type of the objects to be resolved.
*/
public interface ConflictResolver<T>
{
T resolve(List<T> objectList) throws UnresolvedConflictException;
}
|
package structural.bridge;
public class Test {
public static void main(String[] args){
IImplementation implementation = new ImplementationB();
AAbstraction abstraction = new Abstraction();
abstraction.setImplementation(implementation);
abstraction.operation();
}
}
|
package com.jgw.supercodeplatform.project.zaoyangpeach.controller;
import com.jgw.supercodeplatform.project.zaoyangpeach.service.BatchInfoService;
import com.jgw.supercodeplatform.trace.common.model.RestResult;
import com.jgw.supercodeplatform.trace.common.model.page.AbstractPageService;
import com.jgw.supercodeplatform.trace.dto.dynamictable.DynamicTableRequestParam;
import com.jgw.supercodeplatform.trace.service.zaoyangpeach.StoragePlaceService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/trace/zaoyangpeach/batchinfo")
public class BatchInfoController {
@Autowired
private BatchInfoService batchInfoService;
@Autowired
private StoragePlaceService storagePlaceService;
@GetMapping("/selectByName")
public RestResult selectByName(String batchName,Integer functionType) throws Exception {
return new RestResult(200, "success", batchInfoService.getBatchInfo(batchName,functionType));
}
@GetMapping("/selectByStoragePlace")
public RestResult selectByStoragePlace(String storagePlaceId){
return new RestResult(200, "success", storagePlaceService.selectBatchStoragePlaceRelation(storagePlaceId));
}
}
|
package Command;
import Exceptions.CommandExecuteException;
import Exceptions.CommandParseException;
import Logic.Game;
import Managers.PrinterManager;
import Printer.BoardPrinter;
public class PrintCommand extends Command {
private String modo;
public final static String commandLetter = "p";
public final static String commandText = "Printmode";
public final static String commandInfo = "[P]rintMode <mode>";
public final static String helpInfo = "change print mode [Release|Debug].";
public PrintCommand() {
super(commandText, commandInfo, helpInfo);
}
public boolean execute(Game game) throws CommandExecuteException{
BoardPrinter tablero = PrinterManager.parsePrinter(modo);
if (tablero == null) {
throw new CommandExecuteException("Unknown print mode: " + modo +"\n");
}
else {
game.modificarInterfaz(tablero);
game.printGame();
}
return false;
}
public Command parse(String[] texto) throws CommandParseException {
Command comando = null;
if (texto[0].toLowerCase().equals(commandLetter) || texto[0].toLowerCase().equals(commandText.toLowerCase())) {
if (texto.length != 2) {
throw new CommandParseException("Incorrect number of arguments for printmode command: [P]rintMode release|debug\n");
}
else {
comando = this;
modo = texto[1];
}
}
return comando;
}
} |
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
/**
* This class holds all methods concerning the player.
*
* @author Ahmed Mansour
* @version 8/3/17
*/
public class Player
{
private String name; //name of the player
private int health; //current health of the player
private int energy; //current energy of the player
private int strength; //strength of the player
private int EXP; //EXP the player owns
private int magic; //magic of the player
private int level; //level of the player
private int damage; //damage the player deals
private int gold; //gold the player owns
private int EXPold; //EXP before EXP from a battle is earned, used to determine if a new level is reached
private int healthLoss; //amount of health lost from an attack
private int maxHealth; //max health the player has
private int maxEnergy; //max energy the player has
private int numHealthPot; //number of health potions the player owns
private int numEnergyPot; //number of energy potions the player owns
private int numRevive; //number of revive items the player own
private String physicalWeapon; //name of the physical weapon the player owns
private int physicalWeaponID = 0;
private String magicWeapon; //name of the magic weapon the player owns
private int magicWeaponID = 0;
private int physicalWeaponStrength; //strength of the physical weapon
private int magicWeaponStrength; //magic strength of the magic weapon
private double healthMulti; //health stat level up multiplier, based on class
private double energyMulti; //energy stat level up multiplier, based on class
private double strengthMulti; //strength stat level up multiplier, based on class
private double magicMulti; //magic stat level up multiplier, based on class
private int areaComplete = 1; //index of the area you've been to, starting from 1, the first area
private int currentArea;
private int battleComplete = 1; //index of the battle you're in
private boolean running;
private String Password;
private String attackType;
private String playerClass; //class of the player
private int classID;
private String gender; //gender of the player (used when describing the attack of the player)
private ArrayList<String> items = new ArrayList<String>(); //ArrayList that holds the items the player has
private Effects effect = new Effects(); //creates an Effects class object
public Player(String name, int health, int energy, int strength, int EXP, int magic, int level, int gold, int maxHealth, int maxEnergy, ArrayList<String> items, int numHealthPot, int numEnergyPot, String physicalWeapon, String magicWeapon, int physicalWeaponStrength, int magicWeaponStrength, String gender, String playerClass)
{ //constructor that initalizes all the attributes of the player
this.name = name;
this.health = health;
this.energy = energy;
this.strength = strength;
this.EXP = EXP;
this.magic = magic;
this.level = level;
this.gold = gold;
this.maxHealth = maxHealth;
this.maxEnergy = maxEnergy;
this.items = items;
this.numHealthPot = numHealthPot;
this.numEnergyPot = numEnergyPot;
this.physicalWeapon = physicalWeapon;
this.magicWeapon = magicWeapon;
this.physicalWeaponStrength = physicalWeaponStrength;
this.magicWeaponStrength = magicWeaponStrength;
this.gender = gender;
this.playerClass = playerClass;
}
public int getPlayerHealth()//returns the current health of the player
{
return health;
}
public void setPlayerHealth(int health)//sets the player health
{
this.health = health;
}
public int getPlayerLevel()//return the current level of the player
{
return level;
}
public void setPlayerLevel(int level)//sets the player level
{
this.level = level;
}
public int getPlayerEnergy()//return the current energy of the player
{
return energy;
}
public void setPlayerEnergy(int Energy)//sets the player energy
{
this.energy = energy;
}
public int getPlayerGold()//return the current gold of the player
{
return gold;
}
public void setPlayerGold(int gold)//sets the player gold
{
this.gold = gold;
}
public void setPlayerStrength(int strength)//sets the player strength
{
this.strength = strength;
}
public void setPlayerMagic(int magic)//sets the player magic
{
this.magic = magic;
}
public void setPlayerEXP(int EXP)//sets the player EXP
{
this.EXP = EXP;
}
public void setPlayerMaxHealth(int maxHealth)//sets the player EXP
{
this.maxHealth = maxHealth;
}
public void setPlayerMaxEnergy(int maxEnergy)//sets the player EXP
{
this.maxEnergy = maxEnergy;
}
public void setPlayerNumHealthPot(int numHealthPot)//sets the player EXP
{
this.numHealthPot = numHealthPot;
}
public void setPlayerNumEnergyPot(int numEnergyPot)//sets the player EXP
{
this.numEnergyPot = numEnergyPot;
}
public void setPlayerNumRevive(int numRevive)//sets the player EXP
{
this.numRevive = numRevive;
}
public void setPlayerPhysicalWeapon(int physicalWeaponID)//sets the player EXP
{
if(physicalWeaponID == 0)
{
physicalWeapon = "Fists";
physicalWeaponStrength = 0;
}
else if(physicalWeaponID == 1)
{
physicalWeapon = "Wooden Sword";
physicalWeaponStrength = 10;
}
else if(physicalWeaponID == 2)
{
physicalWeapon = "Copper Longsword";
physicalWeaponStrength = 20;
}
else if(physicalWeaponID == 3)
{
physicalWeapon = "Iron Broadsword";
physicalWeaponStrength = 35;
}
else if(physicalWeaponID == 4)
{
physicalWeapon = "Razor Sabre";
physicalWeaponStrength = 50;
}
else if(physicalWeaponID == 5)
{
physicalWeapon = "Katana";
physicalWeaponStrength = 75;
}
else if(physicalWeaponID == 6)
{
physicalWeapon = "Excalibur";
physicalWeaponStrength = 250;
}
}
public void setPlayerMagicWeapon(int magicWeaponID)//sets the player EXP
{
if(magicWeaponID == 0)
{
physicalWeapon = "Tree Branch";
physicalWeaponStrength = 0;
}
else if(magicWeaponID == 1)
{
magicWeapon = "Plastic Stick";
magicWeaponStrength = 10;
}
else if(magicWeaponID == 2)
{
magicWeapon = "Magician's Wand";
magicWeaponStrength = 25;
}
else if(magicWeaponID == 3)
{
magicWeapon = "Golden Scepeter";
magicWeaponStrength = 40;
}
else if(magicWeaponID == 4)
{
magicWeapon = "Titanium Staff";
magicWeaponStrength = 65;
}
else if(magicWeaponID == 5)
{
magicWeapon = "Holographic Rod";
magicWeaponStrength = 85;
}
else if(magicWeaponID == 6)
{
magicWeapon = "Strange Twig";
magicWeaponStrength = 200;
}
}
public void setPlayerAreaComplete(int areaComplete)//sets the player EXP
{
this.areaComplete = areaComplete;
}
public void setPlayerClassPass(int playerClassID)//sets the player EXP
{
if(playerClassID == 1)
{
playerClass = "Swordsmen";
healthMulti = 1.5;
energyMulti = 0.8;
strengthMulti = 1.6;
magicMulti = 0.5;
maxHealth = 550;
health = maxHealth;
name += " The Swordsmen";
}
else if(playerClassID == 2)
{
playerClass = "Wizard";
healthMulti = 0.9;
energyMulti = 1.2;
strengthMulti = 0.5;
magicMulti = 1.7;
maxHealth = 450;
health = maxHealth;
name += " The Wizard";
}
else if(playerClassID == 3)
{
playerClass = "Tank";
healthMulti = 1.8;
energyMulti = 1.1;
strengthMulti = 1.3;
magicMulti = 0.9;
maxHealth = 650;
health = maxHealth;
name += " The Tank";
}
}
public void setPlayerGenderPass(String gender)//sets the player EXP
{
this.gender = gender;
}
public void setPlayerName(String name)//sets the player name
{
this.name = name;
}
public int getBattleComplete()
{
return battleComplete;
}
public void setPlayerGender(String choice)//sets the player gender
{
Scanner ix = new Scanner(System.in);
if(choice.equals("M"))
{
gender = "his";
}
else if(choice.equals("F"))
{
gender = "her";
}
else
{
effect.Scroll("Invalid choice. Please try again!");
effect.pauseQuick();
effect.Scroll("Please choose your player gender ([M]ale or [F]emale)");
choice = ix.next();
setPlayerGender(choice); //calls itself to reset the method
}
}
public void setPlayerClass(String choice)
{
Scanner ix = new Scanner(System.in);
if(choice.equals("S"))
{
playerClass = "Swordsmen";
healthMulti = 1.5;
energyMulti = 0.8;
strengthMulti = 1.6;
magicMulti = 0.5;
maxHealth = 550;
health = maxHealth;
name += " The Swordsmen";
classID = 1;
}
else if(choice.equals("W"))
{
playerClass = "Wizard";
healthMulti = 0.9;
energyMulti = 1.2;
strengthMulti = 0.5;
magicMulti = 1.7;
maxHealth = 450;
health = maxHealth;
name += " The Wizard";
classID = 2;
}
else if(choice.equals("T"))
{
playerClass = "Tank";
healthMulti = 1.8;
energyMulti = 1.1;
strengthMulti = 1.3;
magicMulti = 0.9;
maxHealth = 650;
health = maxHealth;
name += " The Tank";
classID = 3;
}
else
{
effect.Scroll("Invalid choice. Please try again!");
effect.pauseQuick();
effect.Scroll("Please choose your class!");
effect.Scroll(" [S]wordsmen [W]izard [T]ank");
choice = ix.next();
setPlayerClass(choice); //calls itself to reset the method
}
}
public void levelHealth()//increases player health
{
maxHealth += 10 * healthMulti;
}
public void levelEnergy()//increases player energy
{
maxEnergy += 5 * energyMulti;
}
public void levelStrength()//increases player strength
{
strength += 2 * strengthMulti;
}
public void levelMagic()//increases player magic
{
magic += 3 * magicMulti;
}
public void randLevel()//randomly increases two stats
{
int rand = (int)(Math.random() * 100);
if(rand < 25)
{
effect.Scroll("Maximum health increased by " + (int)(10 * healthMulti) + "!");
maxHealth += 20 * healthMulti;
}
else if(rand < 50)
{
effect.Scroll("Maximum energy increased by " + (int)(5 * energyMulti) + "!");
maxEnergy += 10 * energyMulti;
}
else if(rand < 75)
{
effect.Scroll("Maximum strength increased by " + (int)(2 *strengthMulti) + "!");
strength += 2 * strengthMulti;
}
else if(rand < 100)
{
effect.Scroll("Maximum magic increased by " + (int)(3 * magicMulti) + "!");
magic += 2 * magicMulti;
}
}
public void EXPGain(int enemyLevel)//increaes the EXP of the player after winning a battle, uses the enemy level to determine the EXP
{
EXP += enemyLevel * 10;
effect.Scroll("EXP gain: " + EXP);
levelUpCheck(level); //calls the levelUpCheck to check if the EXP gained is enough for a level up
}
public void levelUpCheck(int level)//checks if the EXP gained is enough for a level up
{
if(EXP - EXPold >= 50 * level) //checks if the difference between the EXP you had before the battle and your EXP now is enough for a level up
{
levelUpFirst(); //calls the level up prompt
EXPold += 50 * level; //brings the oldEXP variable closer to the current EXP variable
levelUpCheck(level + 1); //calls itself and checks if the player made it to the next level
}
}
public void levelUpFirst()//first level up prompt
{
int oldHealth;
int oldEnergy;
int oldStrength;
int oldMagic;
String choice;
level++;
health = maxHealth;
energy = maxEnergy;
Scanner ix = new Scanner(System.in);
effect.Scroll("------------------LEVEL UP------------------");
randLevel();
effect.pauseNorm();
randLevel();
effect.pauseNorm();
effect.Scroll("Choose two stats to level up!");
effect.Scroll("First Pick: [H]ealth, [E]nergy, [S]trength, [M]agic");
choice = ix.next();
if(choice.equals("H"))
{
oldHealth = maxHealth;
levelHealth();
health = maxHealth;
effect.pauseNorm();
effect.Scroll("\n" + name + "'s health increased from " + oldHealth + " to " + maxHealth);
effect.pauseNorm();
}
else if(choice.equals("E"))
{
oldEnergy = maxEnergy;
levelEnergy();
energy = maxEnergy;
effect.pauseNorm();
effect.Scroll("\n" + name + "'s energy increased from " + oldEnergy + " to " + maxEnergy);
effect.pauseNorm();
}
else if(choice.equals("S"))
{
oldStrength = strength + physicalWeaponStrength;
levelStrength();
effect.pauseNorm();
effect.Scroll("\n" + name + "'s strength increased from " + oldStrength + " to " + (strength + physicalWeaponStrength));
effect.pauseNorm();
}
else if(choice.equals("M"))
{
oldMagic = magic + magicWeaponStrength;
levelMagic();
effect.pauseNorm();
effect.Scroll("\n" + name + "'s magic increased from " + oldMagic + " to " + (magic + magicWeaponStrength));
effect.pauseNorm();
}
else
{
effect.Scroll("Invalid option. Try again!");
levelUpFirst();
return;
}
levelUpSecond();
}
public void levelUpSecond()//Second level up prompt. The two level up prompts are split so a player can't intentionally type in a wrong letter and repeat the prompt from the beginning.
{
int oldHealth;
int oldEnergy;
int oldStrength;
int oldMagic;
String choice;
Scanner ix = new Scanner(System.in);
effect.Scroll("Second Pick: [H]ealth, [E]nergy, [S]trength, [M]agic");
choice = ix.next();
if(choice.equals("H"))
{
oldHealth = health;
levelHealth();
health = maxHealth;
effect.pauseNorm();
effect.Scroll("\n" + name + "'s health increased from " + oldHealth + " to " + maxHealth);
effect.pauseNorm();
}
else if(choice.equals("E"))
{
oldEnergy = energy;
levelEnergy();
energy = maxEnergy;
effect.pauseNorm();
effect.Scroll("\n" + name + "'s energy increased from " + oldEnergy + " to " + maxEnergy);
effect.pauseNorm();
}
else if(choice.equals("S"))
{
oldStrength = strength + physicalWeaponStrength;
levelStrength();
effect.pauseNorm();
effect.Scroll("\n" + name + "'s strength increased from " + oldStrength + " to " + (strength + physicalWeaponStrength));
effect.pauseNorm();
}
else if(choice.equals("M"))
{
oldMagic = magic + magicWeaponStrength;
levelMagic();
effect.pauseNorm();
effect.Scroll("\n" + name + "'s magic increased from " + oldMagic + " to " + (magic + magicWeaponStrength));
effect.pauseNorm();
}
else
{
effect.Scroll("Invalid option. Try again!");
levelUpSecond();
}
}
public void dropCheck(String enemyName)
{
int rand = (int)(Math.random() * 100);
if(rand < 10)
{
effect.Scroll("The " + enemyName + " dropped a Un-Weakness Brew!");
items.add("Un-Weakness Brew");
}
else if(rand < 20)
{
effect.Scroll("The " + enemyName + " dropped a Vigor Tonic!");
items.add("Vigor Tonic");
}
else if(rand < 22)
{
effect.Scroll("The " + enemyName + " dropped a Energy Sword!");
effect.pauseQuick();
effect.Scroll("Strength: 75 Current weapon strength: " + physicalWeaponStrength);
effect.pauseSuperQuick();
physicalWeaponChange("Energy Sword", 75);
}
else if(rand < 24)
{
effect.Scroll("The " + enemyName + " dropped a Ivory Staff!");
effect.pauseQuick();
effect.Scroll("Strength: 90 Current weapon strength: " + magicWeaponStrength);
effect.pauseSuperQuick();
physicalWeaponChange("Ivory Staff", 90);
}
}
public void physicalWeaponChange(String physicalWeapon, int physicalWeaponStrength)
{
Scanner ix = new Scanner(System.in);
String choice;
int oldStrength = strength + this.physicalWeaponStrength;
effect.Scroll("Would you like to change weapons? (Y or N)");
choice = ix.next();
if(choice.equals("Y"))
{
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
this.physicalWeapon = physicalWeapon;
this.physicalWeaponStrength = physicalWeaponStrength;
}
else if(choice.equals("N"))
{
return;
}
else
{
effect.Scroll("Invalid option. Please Try again!");
physicalWeaponChange(physicalWeapon, physicalWeaponStrength);
}
}
public void magicWeaponChange(String magicWeapon, int magicWeaponStrength)
{
Scanner ix = new Scanner(System.in);
String choice;
int oldMagic = magic + this.magicWeaponStrength;
effect.Scroll("Would you like to change weapons? (Y or N)");
choice = ix.next();
if(choice.equals("Y"))
{
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
this.magicWeapon = magicWeapon;
this.magicWeaponStrength = magicWeaponStrength;
}
else if(choice.equals("N"))
{
return;
}
else
{
effect.Scroll("Invalid option. Please Try again!");
magicWeaponChange(magicWeapon, magicWeaponStrength);
}
}
public void attackPhys()//deal damage using the player's physical weapon. The different types of attacks are almost purely cosmetic, save for one case
{
int typeOfAttack = (int)(Math.random() * 100); //creates a random number between 0 and 100
System.out.print("\n-----------------------------\n");
if(typeOfAttack < 25)
{
effect.Scroll("\n-----------------------------\n" + name + " Slashes blindly with " + gender + " " + physicalWeapon + "!");
}
else if(typeOfAttack < 45)
{
effect.Scroll(name + " Stabs with " + gender + " " + physicalWeapon + " all " + gender + " force!");
}
else if(typeOfAttack < 65)
{
effect.Scroll(name + " performs an impressive jump strike with " + gender + " " + physicalWeapon + "!");
}
else if(typeOfAttack < 80)
{
effect.Scroll(name + " Spins wildly into the enemy with " + gender + " " + physicalWeapon + "!");
}
else if(typeOfAttack < 95)
{
effect.Scroll(name + " Charges and slices off a limb using " + gender + " " + physicalWeapon + "!");
}
else if(typeOfAttack < 100 && !(physicalWeapon == "Fists"))
{
effect.Scroll(name + " holds " + physicalWeapon + " by the blade and hammers the enemy!\n" + name + " Takes some damage from this dangerous stunt!");
health -= 25;
}
attackType = "Physical";
damage = (int)(Math.random() * 100) * (strength + physicalWeaponStrength);
}
public void attackMag()//Menu for attacking with magic
{
String choice;
Scanner ix = new Scanner(System.in);
effect.Scroll("Which spell would you like to cast?");
effect.pauseQuick();
System.out.printf("%20s %20s %20s %20s", "[B]lizzard", "[T]hunder", "[H]eal", "[C]ancel\n");
choice = ix.next();
if(choice.equals("B"))
{
blizzard();
}
else if(choice.equals("T"))
{
thunder();
}
else if(choice.equals("H"))
{
heal();
}
else if(choice.equals("C"))
{
Action();
}
else
{
effect.Scroll("Invalid option. Please Try again!");
attackMag();
}
}
public void blizzard()//deal damage using Blizzard
{
effect.Scroll(name + " points " + gender + " " + magicWeapon + " towards the enemy and unleashes an icy storm!");
effect.Blizzard(); //calls the Blizzard method to create an effect
damage = (int)(Math.random() * 100) * (magic + magicWeaponStrength); //the magic value of the weapon if factored in to determine the damage
energy -= 8; //decreases the amount of energy the player has
attackType = "Ice";
}
public void thunder()//deal damage using Thunder
{
effect.Scroll(name + " holds " + gender + " " + magicWeapon + " skyward and calls down a thunderstorm!");
effect.Thunder(); //calls the Thunder method to create an effect
int rand = (int)(Math.random() * 100); //creates a random number to test if the thunderbolt hits
damage = (int)((Math.random() * 100) * (magic + magicWeaponStrength) * 1.5); //the magic value of the weapon if factored in to determine the damage
energy -= 10; //decreases the amount of energy the player has
if(rand < 30) //the thunderbolt has a 30 percent chance to miss
{
damage = 0; //sets the damage to zero due to the miss
effect.Scroll("The thunderbolt missed!");
}
if(damage > 0)
{
attackType = "Lightning";
}
}
public void heal()//heal using Heal
{
effect.Scroll(name + " aims " + gender + " " + magicWeapon + " to " + gender + " chest and lets off a blinding light!");
effect.Heal(); //calls the Heal method to create an effect
int heal = (int)(Math.random() * 100 * (magic + magicWeaponStrength) * 1.5); //the magic value of the weapon if factored in to determine the damage
health += heal; //increases the player's health
damage = 0; //this is necessary to ensure the last attacks damage isn't used again
if(health > maxHealth) //check if the heal over heals the player
{
health = maxHealth; //if overheal occurs, it brings the current health to the max health
}
energy -= 15; //decreases the amount of energy the player has
effect.Scroll(name + " healed " + heal + "!");
}
public void isRunning()
{
int rand = (int)(Math.random() * 100);
effect.Scroll(name + " tries to run away!");
effect.pauseLong();
if(rand < 70)
{
effect.Scroll("Ran away successfully!");
running = true;
effect.pauseNorm();
effect.Scroll("Returning to the World Map!");
effect.pauseNorm();
}
else
{
effect.Scroll("Couldn't run!");
running = false;
effect.pauseNorm();
}
}
public void setRunning(boolean state)
{
running = state;
}
public boolean getRunning()
{
return running;
}
public void Action()//Main attacking menu
{
Scanner ix = new Scanner(System.in);
String choice;
attackType = null;
System.out.print("-----------------------------\n");
effect.Scroll("\nWhat will " + name + " do?");
effect.pauseQuick(); //pause for effect
System.out.printf("\n%10s %10s %10s %10s","[A]ttack", "[M]agic", "[I]tem", "[R]un\n");
choice = ix.next();
if(choice.equals("A"))
{
attackPhys();
}
else if(choice.equals("M"))
{
attackMag();
}
else if(choice.equals("I"))
{
chooseItem();
}
else if(choice.equals("R"))
{
isRunning();
}
else
{
effect.Scroll("Invalid option. Try again!");
Action(); //calls itself to reset the menu
}
}
public int dealDamage()//return damage dealt during this turn
{
return damage;
}
public void takeDamage(int healthLoss)//take damage and lose health
{
if(healthLoss > 0)
{
effect.Scroll(name + " loses " + healthLoss + " health!\n");
health -= healthLoss;
}
}
public String attackType()
{
return attackType;
}
public void showStats()//display player information
{
if(health < 0) //this if statement is used when the player dies, so the final stats doesn't have negative health
{
health = 0;
}
effect.Scroll("\nPlayer Stats:");
effect.pauseInstant();
effect.Scroll("Level: " + level);
effect.pauseInstant();
effect.Scroll("Health: " + health + "/" + maxHealth);
effect.pauseInstant();
effect.Bar(health, maxHealth);
effect.pauseInstant();
effect.Scroll("Energy: " + energy + "/" + maxEnergy);
effect.pauseInstant();
effect.Bar(energy, maxEnergy);
effect.pauseInstant();
effect.Scroll("Strength: " + (strength + physicalWeaponStrength));
effect.pauseInstant();
effect.Scroll("Magic: " + (magic + magicWeaponStrength));
effect.pauseInstant();
effect.Scroll("Physical Weapon: " + physicalWeapon);
effect.pauseInstant();
effect.Scroll("Magical Weapon: " + magicWeapon);
effect.pauseInstant();
}
public void victory()//display victory text
{
effect.Scroll("\nCongratulations! You win!");
battleComplete++;
}
public void areaComplete()
{
effect.Scroll("AREA COMPLETED!");
battleComplete = 1;
if(currentArea == areaComplete)
{
areaComplete++;
}
}
public int areaSelect()
{
Scanner ix = new Scanner(System.in);
int area;
effect.Map();
effect.Scroll("Which area would you like to go to?");
System.out.print("(1): Grassy Plains\t\n");
currentArea = 1;
if(areaComplete == 2)
{
System.out.print("(2): Dark Forest\t\n");
}
else
{
System.out.print("(2): LOCKED\t\n");
}
effect.pauseSuperQuick();
if(areaComplete == 3)
{
System.out.print("(3): Arid Desert\t\n");
}
else
{
System.out.print("(3): LOCKED\t\n");
}
effect.pauseSuperQuick();
if(areaComplete == 4)
{
System.out.print("(4): Frozen Wastelands\t\n");
}
else
{
System.out.print("(4): LOCKED\t\n");
}
effect.pauseSuperQuick();
if(areaComplete == 5)
{
System.out.print("(5): Rocky Mountainside\t\n");
}
else
{
System.out.print("(5): LOCKED\t\n");
}
effect.pauseSuperQuick();
if(areaComplete == 6)
{
System.out.print("(6): Underwater Palace\n");
}
else
{
System.out.print("(6): LOCKED\n");
}
area = ix.nextInt();
currentArea = area;
if(area > areaComplete)
{
effect.Scroll("Not a valid choice!");
area = 1;
areaSelect();
}
return area;
}
public void goldGain(int enemyLevel)//increase the amount of gold owned by player
{
int goldGained;
goldGained = (int)(20 + Math.random() * 100) * enemyLevel * 2; //the amount of gold the player earns is determined using the enemy level
effect.Scroll("Gold Gained: " + goldGained + "\n\n");
gold += goldGained;
}
public void shopItem(String choice)//change the player's items or physical weapon strength or magical weapon strength
{
int oldStrength;
int oldMagic;
if(choice.equals("U") && gold >= 80) //tests the choice of the player as well as the amount of gold the player has
{
items.add("[U]n-Weakness Brew");
effect.Scroll(name + "puts a Un-Weakness Brew in " + gender + " inventory!");
inventory();
}
else if(choice.equals("V") && gold >= 60)
{
items.add("[V]igor Tonic");
effect.Scroll(name + "puts a Vigor Tonic in " + gender + " inventory!");
inventory();
}
else if(choice.equals("W") && gold >= 100)
{
physicalWeapon = "Wooden Sword";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 10;
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 100;
physicalWeaponID = 1;
}
else if(choice.equals("C") && gold >= 350)
{
physicalWeapon = "Copper Longsword";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 20;
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 350;
physicalWeaponID = 2;
}
else if(choice.equals("I") && gold >= 600)
{
physicalWeapon = "Iron Broadsword";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 35;
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 600;
physicalWeaponID = 3;
}
else if(choice.equals("R") && gold >= 800)
{
physicalWeapon = "Razor Sabre";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 50;
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 800;
physicalWeaponID = 4;
}
else if(choice.equals("K") && gold >= 1000)
{
physicalWeapon = "Katana";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 75;
effect.Scroll(name + " equips the " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 1000;
physicalWeaponID = 5;
}
else if(choice.equals("E") && gold >= 5000)
{
physicalWeapon = "Excalibur";
oldStrength = strength + physicalWeaponStrength;
physicalWeaponStrength = 250;
effect.Scroll(name + " equips " + physicalWeapon + "!");
effect.Scroll(name + "'s strength changed from " + oldStrength + " to " + (strength + physicalWeaponStrength) + "!");
gold -= 5000;
physicalWeaponID = 6;
}
else if(choice.equals("P") && gold >= 100)
{
magicWeapon = "Plastic Stick";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 10;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 100;
magicWeaponID = 1;
}
else if(choice.equals("M") && gold >= 300)
{
magicWeapon = "Magician's Wand";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 25;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 300;
magicWeaponID = 2;
}
else if(choice.equals("G") && gold >= 550)
{
magicWeapon = "Golden Scepter";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 40;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 550;
magicWeaponID = 3;
}
else if(choice.equals("T") && gold >= 700)
{
magicWeapon = "Titanium Staff";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 65;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 700;
magicWeaponID = 4;
}
else if(choice.equals("H") && gold >= 950)
{
magicWeapon = "Holographic Rod";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 85;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 950;
magicWeaponID = 5;
}
else if(choice.equals("S") && gold >= 6000)
{
magicWeapon = "Strange Twig";
oldMagic = magic + magicWeaponStrength;
magicWeaponStrength = 200;
effect.Scroll(name + " equips the " + magicWeapon + "!");
effect.Scroll(name + "'s magic changed from " + oldMagic + " to " + (magic + magicWeaponStrength) + "!");
gold -= 6000;
magicWeaponID = 6;
}
else if(choice.equals("F") && gold >= 1000)
{
items.add("[F]eather of Resurrection");
numRevive++;
effect.Scroll(name + " puts a Feather of Resurrection in " + gender + " inventory!");
gold -= 1000;
inventory();
}
else if(choice.equals("N"))
{
effect.Scroll("Returning to the battle!");
}
else
{
effect.Scroll("Sorry " + name + ", I can't give credit. Come back when you're a little MMMM, richer!");
}
}
public void chooseItem()//menu for inventory for items
{
Scanner ix = new Scanner(System.in);
String choice;
damage = 0;
inventory();
effect.Scroll("Which Item would you like to use?\n");
System.out.printf("%10s", "[N]one\n");
choice = ix.next();
if(choice.equals("U") && Collections.frequency(items, "[U]n-Weakness Brew") > 0) //uses an Unweak potion, provided the player has one
{
items.remove("[U]n-Weakness Brew");
health += 200;
}
else if(choice.equals("V") && Collections.frequency(items, "[V]igor Tonic") > 0) //uses an Vigor potion, provided the player has one
{
items.remove("[V]igor Tonic");
energy += 50;
}
else if(choice.equals("F") && Collections.frequency(items, "[F]eather of Resurrection") > 0) //uses an Feather, provided the player has one
{
items.remove("[F]eather of Resurrection");
health += 500;
}
else if(choice.equals("N"))
{
Action(); //returns to the main Action method
}
else
{
effect.Scroll("Invalid choice. Please try again!");
chooseItem();
}
if(health > maxHealth) //if a healing item over healed, this statment will bring the player's health back down
{
health = maxHealth;
}
}
public void inventory() //displays the inventory
{
if(items.size() > 0)
{
effect.Scroll("\n-----------------------------\nInventory:\n");
for(int i = 0; i < items.size(); i++)
{
effect.Scroll(items.get(i));
}
}
else
{
System.out.println("You have no items in your inventory!");
}
System.out.println();
}
public void revive()
{
effect.Scroll(name + " recieves a fatal blow!");
effect.pauseLong();
if(Collections.frequency(items, "[F]eather of Resurrection") > 0) //revive the player if they have a feather
{
effect.Scroll("Huh?");
effect.pauseNorm();
effect.Scroll(name + "'s Feather of Resurrection glows brightly!");
effect.pauseQuick();
effect.Revive();
effect.pauseQuick();
effect.Scroll(name + " was revived!");
items.remove("[F]eather of Resurrection");
health = maxHealth;
return;
}
death();
}
public void death()//displays text when health = 0, and exits the game
{
effect.Dead(name); //calls the Dead method to create an effect
effect.Scroll("You died! Get better and come back!");
effect.Scroll("Final Stats\n");
showStats();
effect.Scroll("EXP: " + EXP);
effect.pauseInstant();
effect.Scroll("Gold: " + gold);
effect.pauseInstant();
System.exit(0); //exits the program
}
public void generatePassword(String choice) throws FileNotFoundException
{
if (choice.equals("Y"))
{
Password = name.substring(0, name.indexOf(" ")) + "~" + health * 42 + "~" + energy * 36 + "~" + strength * 64 + "~" + EXP * 11 + "~" + magic * 32 + "~" + level * 990 + "~" + gold / 1000 + "~" + maxHealth * 55 + "~" + maxEnergy * 22 + "~" + numHealthPot * 25 + "~" + numEnergyPot + "~" + numRevive * 2 + "~" + physicalWeaponID + "~" + magicWeaponID + "~" + areaComplete * 200 + "~" + classID + "~" + gender + "~";
effect.Scroll("Your password is: \n\n" + Password);
//save.delete();
File save = new File("C:/Users/Ahmed/Desktop/Ahmed's Folder/APCS Course Files/SimpleRPG/Saves/save.txt");
PrintWriter out = new PrintWriter("save.txt");
out.println(Password);
out.close();
effect.Scroll("Game saved successfully!");
}
else if(choice.equals("N"))
{
return;
}
else
{
effect.Scroll("Invalid response! Please try again!");
effect.Scroll("Would you like to visit the shop? (Y/N)");
}
}
public void passwordMenu() throws FileNotFoundException
{
String password = "";
File save = new File("C:/Users/Ahmed/Desktop/Ahmed's Folder/APCS Course Files/SimpleRPG/save.txt");
int sectionNew;
int error = 0;
effect.Scroll("Loading your save file...");
Scanner ix = new Scanner(save);
password = ix.nextLine();
sectionNew = password.indexOf("~");
setPlayerName(password.substring(0, sectionNew));
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerHealth(Integer.parseInt(password.substring(0, sectionNew)) / 42);
if(Integer.parseInt(password.substring(0, sectionNew)) / 42 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerEnergy(Integer.parseInt(password.substring(0, sectionNew)) / 36);
if(Integer.parseInt(password.substring(0, sectionNew)) / 36 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerStrength(Integer.parseInt(password.substring(0, sectionNew)) / 64);
if(Integer.parseInt(password.substring(0, sectionNew)) / 64 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerEXP(Integer.parseInt(password.substring(0, sectionNew)) / 11);
if(Integer.parseInt(password.substring(0, sectionNew)) / 11 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerMagic(Integer.parseInt(password.substring(0, sectionNew)) / 32);
if(Integer.parseInt(password.substring(0, sectionNew)) / 32 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerLevel(Integer.parseInt(password.substring(0, sectionNew)) / 990);
if(Integer.parseInt(password.substring(0, sectionNew)) / 990 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerGold(Integer.parseInt(password.substring(0, sectionNew)) * 1000);
if(Integer.parseInt(password.substring(0, sectionNew)) * 1000 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerMaxHealth(Integer.parseInt(password.substring(0, sectionNew)) / 55);
if(Integer.parseInt(password.substring(0, sectionNew)) / 55 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerMaxEnergy(Integer.parseInt(password.substring(0, sectionNew)) / 22);
if(Integer.parseInt(password.substring(0, sectionNew)) / 22 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerNumHealthPot(Integer.parseInt(password.substring(0, sectionNew)) / 25);
if(Integer.parseInt(password.substring(0, sectionNew)) / 25 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerNumEnergyPot(Integer.parseInt(password.substring(0, sectionNew)));
if(Integer.parseInt(password.substring(0, sectionNew)) % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerNumRevive(Integer.parseInt(password.substring(0, sectionNew)) / 2);
if(Integer.parseInt(password.substring(0, sectionNew)) / 2 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerPhysicalWeapon(Integer.parseInt(password.substring(0, sectionNew)));
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerMagicWeapon(Integer.parseInt(password.substring(0, sectionNew)));
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerAreaComplete(Integer.parseInt(password.substring(0, sectionNew)) / 200);
if(Integer.parseInt(password.substring(0, sectionNew)) / 200 % 1 != 0)
{
error++;
}
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerClassPass(Integer.parseInt(password.substring(0, sectionNew)));
password = password.substring(sectionNew + 1, password.length());
sectionNew = password.indexOf("~");
setPlayerGenderPass(password.substring(0, sectionNew));
password = password.substring(sectionNew + 1, password.length());
if(error != 0)
{
effect.Scroll("Invalid password! Please try again!");
error = 0;
passwordMenu();
}
}
}
|
package cn.bdqn.stumanage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MgrBackFrontApplication {
public static void main(String[] args) {
SpringApplication.run(MgrBackFrontApplication.class, args);
}
}
|
package org.jre.sandbox;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout, Model model, Locale locale) {
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
if (error != null) {
model.addAttribute("error", "Invalid username and password!");
}
if (logout != null) {
model.addAttribute("msg", "You have been logged out successfully.");
}
return "login";
}
}
|
package com.flyusoft.apps.jointoil.action;
import java.util.List;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.flyusoft.apps.jointoil.entity.MachineRoom;
import com.flyusoft.apps.jointoil.service.MachineRoomService;
import com.flyusoft.common.action.CrudActionSupport;
import com.flyusoft.common.orm.Page;
import com.flyusoft.common.orm.PropertyFilter;
import com.flyusoft.common.utils.web.struts2.Struts2Utils;
@Controller
@Scope("prototype")
public class MachineRoomAction extends CrudActionSupport<MachineRoom> {
private static final long serialVersionUID = -1054713032698360047L;
private MachineRoom machineRoom;
private String id;
private List<String> ids;
private Page<MachineRoom> page = new Page<MachineRoom>(10);
@Autowired
private MachineRoomService machineRoomService;
@Override
public MachineRoom getModel() {
return machineRoom;
}
@Override
public String list() throws Exception {
List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
// 设置默认排序方式
if (!page.isOrderBySetted()) {
page.setOrderBy("id");
page.setOrder(Page.ASC);
}
page = machineRoomService.searchMachineRoom(page, filters);
return SUCCESS;
}
@Override
public String input() throws Exception {
return INPUT;
}
@Override
public String save() throws Exception {
try {
machineRoomService.saveMachineRoom(machineRoom);
addActionMessage("保存成功");
} catch (ConstraintViolationException e) {
addActionMessage("保存失败");
}
return RELOAD;
}
@Override
public String delete() throws Exception {
try {
machineRoomService.deleteMachineRoom(ids);
addActionMessage("删除成功");
} catch (Exception e) {
addActionMessage("删除失败");
}
return RELOAD;
}
@Override
protected void prepareModel() throws Exception {
if (id != null && !id.equals("")) {
machineRoom = machineRoomService.getMachineRoom(id);
} else {
machineRoom = new MachineRoom();
}
}
public void setId(String id) {
this.id = id;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
public Page<MachineRoom> getPage() {
return page;
}
}
|
package com.lucianoscilletta.battleship.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import com.lucianoscilletta.battleship.graphics.*;
import com.lucianoscilletta.battleship.*;
import com.lucianoscilletta.battleship.ui.*;
public class CannonLight extends GameComponent {
private BufferedImage imageOn = null;
private BufferedImage imageOff = null;
private static boolean lit = false;
public CannonLight(){
super();
GameGraphics gr = new CannonReadyOn();
imageOn = GameUtils.classToImage(gr);
imageOff = GameUtils.classToImage(new CannonReadyOff());
lit = false;
Dimension size = new Dimension(gr.getOrigWidth(), gr.getOrigHeight());
this.setSize(size);
this.setMinimumSize(size);
this.setMaximumSize(size);
this.setPreferredSize(size);
this.setLocation(gr.getOrigX(), gr.getOrigY());
}
public void paintComponent(Graphics2D g){
if (lit){
g.drawImage(imageOn, 0, 0, null);
} else {
g.drawImage(imageOff, 0, 0, null);
}
}
public static void light(boolean value){
lit = value;
GraphicsEngine.repaint();
}
}
|
/*
* Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.petrinator.editor.filechooser;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.filechooser.FileFilter;
import org.petrinator.petrinet.Document;
import org.petrinator.petrinet.PetriNet;
import org.petrinator.util.StringTools;
/**
*
* @author Martin Riesz <riesz.martin at gmail.com>
*/
public abstract class FileType extends FileFilter {
public static Set<FileType> getAllFileTypes() {
Set<FileType> allFileTypes = new HashSet<FileType>();
allFileTypes.add(new EpsFileType());
allFileTypes.add(new PflowFileType());
allFileTypes.add(new PflowxFileType());
allFileTypes.add(new PngFileType());
allFileTypes.add(new ViptoolPnmlFileType());
return allFileTypes;
}
public abstract String getExtension();
public abstract String getName();
public abstract void save(Document document, File file) throws FileTypeException;
public abstract Document load(File file) throws FileTypeException;
public abstract Icon getIcon();
public BufferedImage getPreview(File file) {
try {
Document document = load(file);
PetriNet petriNet = document.petriNet;
BufferedImage image = petriNet.getRootSubnet().getPreview(petriNet.getInitialMarking());
return image;
} catch (FileTypeException ex) {
}
return null;
}
public String getDescription() {
return getName() + " (*." + getExtension() + ")";
}
public boolean accept(File file) {
if (file.isDirectory()) { //Show also directories in the filters
return true;
}
String extension = StringTools.getExtension(file);
if (extension != null) {
if (extension.equals(getExtension())) {
return true;
}
}
return false;
}
public static FileType getAcceptingFileType(File file, Collection<FileType> fileTypes) {
for (FileType fileType : fileTypes) {
if (fileType.accept(file)) {
return fileType;
}
}
return null;
}
}
|
package com._08_method_Reference;
import java.util.function.BiFunction;
@FunctionalInterface
interface Calculater1 {
public int carpmaMessage1(int a, int b);
}
class Calculater {
public static int carpma(int a, int b) {
return a * b;
}
}
public class Example_2 {
public static void main(String[] args) {
Calculater1 a = Calculater::carpma;
System.out.println(a.carpmaMessage1(5,5));
BiFunction<Integer,Integer, Integer> b = Calculater::carpma;
System.out.println(b.apply(6,6));
}
}
|
import java.util.Vector;
public class Controllo {
private Passeggero passeg;
private TipoEsito esito;
private Vector<Merce> merci;
public Controllo(Passeggero passeg, Merce merci, TipoEsito esito){
this.passeg = passeg;
this.merci = merci;
this.esito = esito;
}
public Merce getMerci() {
return merci;
}
public float getDazio(){
if(passeg = this.passeg){
}
}
}
|
package az.itcity.etaskify.mapper;
import az.itcity.etaskify.dto.OrganizationDto;
import az.itcity.etaskify.entity.Organization;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@Mapper
public interface OrganizationDtoMapper {
OrganizationDtoMapper INSTANCE = Mappers.getMapper(OrganizationDtoMapper.class);
@Mappings(
value = {
@Mapping(source = "name", target = "orgName"),
@Mapping(source = "phoneNumber", target = "number")
}
)
OrganizationDto OrganizationToOrganizationDto(Organization organization);
@Mappings(
value = {
@Mapping(target = "name", source = "orgName"),
@Mapping(target = "phoneNumber", source = "number")
}
)
Organization OrganizationDtoToOrganization(OrganizationDto organizationDto);
}
|
package com.example.forcatapp.Group;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.forcatapp.R;
import com.example.forcatapp.util.BottomNavBarHelper;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
public class GroupActivity extends AppCompatActivity {
private static final int ACTIVITY_NUMBER = 0;
private Context mContext = GroupActivity.this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group);
setupBottomNavigationView();
getSupportFragmentManager().beginTransaction().replace(R.id.group_center,new GroupListFragment()).commit();
}
//하단바 설정
private void setupBottomNavigationView(){
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bottomNavViewBar);
BottomNavBarHelper.setupBottomNavBarView(bottomNavigationViewEx);
BottomNavBarHelper.enableNavigation(mContext, bottomNavigationViewEx );
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUMBER);
menuItem.setChecked(true);
}
public void replaceFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.group_center,fragment).commit();
}
} |
package com.hoanganhtuan95ptit.awesomekeyboard.view.model;
import java.io.Serializable;
/**
* Created by DuyPC on 5/23/2017.
*/
public class Photo implements Serializable {
private String url;
private long time;
private boolean select=false;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public boolean isSelect() {
return select;
}
public void setSelect(boolean select) {
this.select = select;
}
}
|
package fr.ecole.eni.lokacar.bddHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import fr.ecole.eni.lokacar.contract.ClientContract;
import fr.ecole.eni.lokacar.contract.GlobalContract;
import fr.ecole.eni.lokacar.contract.SalarieContract;
public class ClientHelper extends SQLiteOpenHelper {
public ClientHelper(Context context) {
super(context, GlobalContract.DATABASE_NAME,null,GlobalContract.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(ClientContract.CLIENT_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(ClientContract.QUERY_DELETE_TABLE_CLIENT);
onCreate(db);
}
}
|
package com.metoo.core.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import com.metoo.core.annotation.Lock;
/**
*
* <p>
* Title: IdEntity.java
* </p>
*
* <p>
* Description:
* 系统域模型基类,该类包含3个常用字段,其中id为自增长类型,该类实现序列化,只有序列化后才可以实现tomcat集群配置session共享
* </p>
*
* <p>
* Copyright: Copyright (c) 2014
* </p>
*
* <p>
* Company: 湖南创发科技有限公司 www.koala.com
* </p>
*
* @author erikzhang
*
* @date 2014-4-24
*
* @version koala_b2b2c v2.0 2015版
*
* @warning
* 1.标注为@MappedSuperclass的类将不是一个完整的实体类,他将不会映射到数据库表,但是他的属性都将映射到其子类的数据库字段中。
*
* 2.标注为@MappedSuperclass的类不能再标注@Entity或@Table注解,也无需实现序列化接口。
*
* 3.可以将超类的JPA注解传递给子类,使子类能够继承超类的JPA注解
*
* IDENTITY:采用数据库 ID自增长的方式来自增主键字段,Oracle 不支持这种方式;
* AUTO: JPA自动选择合适的策略,是默认选项;
* SEQUENCE:通过序列产生主键,通过 @SequenceGenerator 注解指定序列名,MySql 不支持这种方式;
* TABLE:通过表产生主键,框架借由表模拟序列产生主键,使用该策略可以使应用更易于数据库移植。
*
*/
@MappedSuperclass
public class IdEntity implements Serializable {
/**
* 序列化接口,自动生成序列号
*/
private static final long serialVersionUID = -7741168269971132706L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(unique = true, nullable = false)
protected Long id;// 域模型id,这里为自增类型
private Date addTime;// 添加时间,这里为长时间格式
@Lock
@Column(columnDefinition = "int default 0")
private int deleteStatus;// 是否删除,默认为0未删除,-1表示删除状态
public IdEntity() {
super();
}
public IdEntity(Long id, Date addTime) {
super();
this.id = id;
this.addTime = addTime;
}
public IdEntity(Long id) {
super();
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
public int getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(int deleteStatus) {
this.deleteStatus = deleteStatus;
}
}
|
package com.huadin.huadin;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.huadin.biz.FeedbackBiz;
import com.huadin.utils.ExceptionUtil;
import com.huadin.utils.LogUtil;
import com.huadin.utils.NetworkUtil;
import com.huadin.utils.ToastUtil;
import com.zhy.autolayout.AutoLayoutActivity;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List;
@EActivity(R.layout.activity_feedback)
public class FeedbackActivity extends AutoLayoutActivity implements FeedbackBiz.onContactListener
{
private static final String TAG = "FeedbackActivity";
private String phone;
private String content;
private Context context;
@ViewById(R.id.feedback_progressBar)
ProgressBar mBar;
@ViewById(R.id.tvTitle)
TextView title;
@ViewById(R.id.feedback_phone)
EditText etPhone;
@ViewById(R.id.feedback_content)
EditText etContent;
@ViewById(R.id.send)
TextView send;
@ViewById(R.id.feedback_layout)
LinearLayout layout;
@Bean
FeedbackBiz mBiz;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.context = this;
// setContentView(R.layout.activity_feedback);
}
@AfterViews
public void setTitle()
{
try
{
title.setText(R.string.system_setting_feedback);
send.setVisibility(View.VISIBLE);
mBiz.setOnContactListener(this);
}catch (Exception e)
{
ExceptionUtil.handleException(e);
}
}
@Click(R.id.send)
public void submitContent()
{
phone = etPhone.getText().toString();
content = etContent.getText().toString();
if (phone.equals("") || phone == null)
{
ToastUtil.mToast(context , getResources().getString(R.string.feedback_activity_contact));
return;
}else
{
//匹配邮箱及电话号码
String rep = "(([0][1][0]|)?\\d{8})|([1]{1}[34578]{1}\\d{9})|(\\w{3,}@\\w+\\.(com|org|cn|net|gov))";
if (!phone.matches(rep))
{
ToastUtil.mToast(context,getResources().getString(R.string.feedback_contact));
return;
}
}
if (content.equals("") || content == null)
{
ToastUtil.mToast(context , getResources().getString(R.string.feedback_print_feedback));
return;
}
if (NetworkUtil.isNetwork(this))
{
List<String> list = new ArrayList<>();
list.add(phone);
list.add(content);
mBiz.submitBiz(list);
mBar.setVisibility(View.VISIBLE);
}else
{
ToastUtil.mToast(this ,getResources().getString(R.string.network_emport));
}
}
@Click(R.id.title_btn_back)
public void back()
{
finish();
}
@Click(R.id.feedback_layout)
public void clearFocus()
{
layout.findFocus();
}
@Override
public void onSuccess()
{
mBar.setVisibility(View.GONE);
ToastUtil.mToast(context , getResources().getString(R.string.feedback_activity_send_success));
finish();
}
@Override
public void onError()
{
ToastUtil.mToast(context , getResources().getString(R.string.register_socket_error));
mBar.setVisibility(View.GONE);
}
@Override
protected void onDestroy()
{
super.onDestroy();
LogUtil.log(TAG , "feedbackActivity - onDestroy");
etPhone.setText("");
etContent.setText("");
}
}
|
package com.robin.springboot.demo.db.jdbc;
import com.robin.springboot.demo.db.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Service
public class JDBCService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> getAllUsers() {
String sql = "select * from robin_test.t_user";
List<User> users = jdbcTemplate.query(sql, new RowMapper<User>() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
user.setCreateTime(rs.getDate("create_time"));
user.setUpdateTime(rs.getDate("update_time"));
return user;
}
});
return users;
}
}
|
package com.dbs.util;
public class PaddingUtil {
public static final int PADDING_NONE = 0;
public static final int PADDING_LEFT = 1;
public static final int PADDING_RIGHT = 2;
public static String paddingLeftItem(String target, String item, int length){
String output = target;
if (output != null && output.length() < length){
for (int i = output.length() ; i < length ; i++){
output = item + output;
}
}
return output;
}
public static String paddingRightItem(String target, String item, int length){
String output = target;
if (output != null && output.length() < length){
for (int i = output.length() ; i < length ; i++){
output = output + item;
}
}
return output;
}
}
|
package Actions;
import Articles.*;
import Attributes.Attribute;
import Utils.Data;
import java.util.ArrayList;
public class Fetch extends Action {
Article type;
ArrayList<Attribute> limiters = new ArrayList<>();
boolean noLimit=true;
ArrayList<Integer> attributeIDs;
boolean allAtt=true;
public Fetch(){}
public Fetch(Article a,ArrayList<Attribute> l, ArrayList<Integer> at){
type=a;
limiters=l;
attributeIDs=at;
noLimit=false;
allAtt=false;
if(l==null){
noLimit=true;
}
if(at==null){
allAtt=true;
}
}
public String action(){
ArrayList<Article> items = new ArrayList<>();
if(type instanceof Lecture) {
ArrayList<ArrayList<Boolean>> checklist = new ArrayList<>();
for (Lecture l : Data.lectures) {
if(noLimit){
items.add(l);
}else {
ArrayList<Boolean> temp = new ArrayList<>();
for (Attribute limit : limiters) {
boolean t = false;
for (Attribute a : l.attributes) {
if(a.equalsTo(limit)){
t=true;
}
}
temp.add(t);
}
checklist.add(temp);
}
}
for(int i=0;i<checklist.size();i++){
boolean allTrue=true;
for(boolean b:checklist.get(i)){
if (!b) {
allTrue = false;
break;
}
}
if(allTrue){
items.add(Data.lectures.get(i));
}
}
}
if(type instanceof Event){
ArrayList<ArrayList<Boolean>> checklist = new ArrayList<>();
for (Event l : Data.events) {
if(noLimit){
items.add(l);
}else {
ArrayList<Boolean> temp = new ArrayList<>();
for (Attribute limit : limiters) {
boolean t = false;
for (Attribute a : l.attributes) {
if(a.equalsTo(limit)){
t=true;
}
}
temp.add(t);
}
checklist.add(temp);
}
}
for(int i=0;i<checklist.size();i++){
boolean allTrue=true;
for(boolean b:checklist.get(i)){
if (!b) {
allTrue = false;
break;
}
}
if(allTrue){
items.add(Data.events.get(i));
}
}
}
if(type instanceof Notification){
ArrayList<ArrayList<Boolean>> checklist=new ArrayList<>();
for(Notification n:Data.notifications){
if(noLimit){
items.add(n);
} else{
ArrayList<Boolean> temp=new ArrayList<>();
for(Attribute limit:limiters){
boolean t=false;
for(Attribute a:n.attributes){
if(a.equalsTo(limit)){
t=true;
}
}
temp.add(t);
}
checklist.add(temp);
}
}
for(int i=0;i<checklist.size();i++){
boolean allTrue=true;
for(boolean b:checklist.get(i)){
if (!b) {
allTrue = false;
break;
}
}
if(allTrue){
items.add(Data.notifications.get(i));
}
}
}
if(type instanceof Medication) {
ArrayList<ArrayList<Boolean>> checklist=new ArrayList<>();
for(Medication n:Data.medications){
if(noLimit){
items.add(n);
} else{
ArrayList<Boolean> temp=new ArrayList<>();
for(Attribute limit:limiters) {
boolean t=false;
for(Attribute a:n.attributes){
if(a.equalsTo(limit)){
t=true;
}
}
temp.add(t);
}
checklist.add(temp);
}
}
for(int i=0;i<checklist.size();i++){
boolean allTrue=true;
for(boolean b:checklist.get(i)){
if (!b) {
allTrue = false;
break;
}
}
if(allTrue){
items.add(Data.medications.get(i));
}
}
}
ArrayList<String> toReturn = new ArrayList<>();
for(Article a:items){
String toAdd = "";
if(!allAtt) {
for (Integer i : attributeIDs) {
if(i<a.attributes.size()) {
if(!a.attributes.get(i).toBeInputted) {
toAdd += a.attributes.get(i).toString() + " ";
}
}
}
}else{
for(Attribute at:a.attributes){
if(!at.toBeInputted) {
toAdd += at.toString() + " ";
}
}
}
toReturn.add(toAdd);
}
String realToReturn="";
for(String s:toReturn){
realToReturn+=s+'\n';
}
return realToReturn;
}
@Override
public String toString(){
return "Fetch";
}
}
|
package cn.hellohao.dao;
import cn.hellohao.pojo.Group;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author Hellohao
* @version 1.0
* @date 2019/8/19 16:11
*/
@Mapper
public interface GroupMapper {
List<Group> grouplist();
Group idgrouplist(@Param("id") Integer id);
Integer addgroup(Group group);
Integer delegroup(@Param("id") Integer id);
Integer setgroup(Group group);
}
|
package com.vincent.thread;
/**
* Created by chenjun on 2020-03-10 22:10 ,变量可见性测试
*/
public class VariableVisibleTest {
private static boolean initFlag = false;
public static void monitor() {
while (!initFlag) {
}
System.out.println("监听状态被另外的线程更改就行啦");
}
public static void modifyFlag() {
initFlag = true;
}
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread(() -> monitor());
threadA.start();
Thread.sleep(5000l);
Thread threadB = new Thread(() -> modifyFlag());
threadB.start();
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.index;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.ClassUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
/**
* Provide access to the candidates that are defined in {@code META-INF/spring.components}.
*
* <p>An arbitrary number of stereotypes can be registered (and queried) on the index: a
* typical example is the fully qualified name of an annotation that flags the class for
* a certain use case. The following call returns all the {@code @Component}
* <b>candidate</b> types for the {@code com.example} package (and its sub-packages):
* <pre class="code">
* Set<String> candidates = index.getCandidateTypes(
* "com.example", "org.springframework.stereotype.Component");
* </pre>
*
* <p>The {@code type} is usually the fully qualified name of a class, though this is
* not a rule. Similarly, the {@code stereotype} is usually the fully qualified name of
* a target type but it can be any marker really.
*
* @author Stephane Nicoll
* @since 5.0
* @deprecated as of 6.1, in favor of the AOT engine.
*/
@Deprecated(since = "6.1", forRemoval = true)
public class CandidateComponentsIndex {
private static final AntPathMatcher pathMatcher = new AntPathMatcher(".");
private final MultiValueMap<String, Entry> index;
CandidateComponentsIndex(List<Properties> content) {
this.index = parseIndex(content);
}
private static MultiValueMap<String, Entry> parseIndex(List<Properties> content) {
MultiValueMap<String, Entry> index = new LinkedMultiValueMap<>();
for (Properties entry : content) {
entry.forEach((type, values) -> {
String[] stereotypes = ((String) values).split(",");
for (String stereotype : stereotypes) {
index.add(stereotype, new Entry((String) type));
}
});
}
return index;
}
/**
* Return the candidate types that are associated with the specified stereotype.
* @param basePackage the package to check for candidates
* @param stereotype the stereotype to use
* @return the candidate types associated with the specified {@code stereotype}
* or an empty set if none has been found for the specified {@code basePackage}
*/
public Set<String> getCandidateTypes(String basePackage, String stereotype) {
List<Entry> candidates = this.index.get(stereotype);
if (candidates != null) {
return candidates.parallelStream()
.filter(t -> t.match(basePackage))
.map(t -> t.type)
.collect(Collectors.toSet());
}
return Collections.emptySet();
}
private static class Entry {
private final String type;
private final String packageName;
Entry(String type) {
this.type = type;
this.packageName = ClassUtils.getPackageName(type);
}
public boolean match(String basePackage) {
if (pathMatcher.isPattern(basePackage)) {
return pathMatcher.match(basePackage, this.packageName);
}
else {
return this.type.startsWith(basePackage);
}
}
}
}
|
package org.sayesaman.app3;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.Fullscreen;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.ViewById;
import org.sayesaman.R;
import org.sayesaman.database.dao.GoodsDao;
import org.sayesaman.database.model.Goods;
import org.sayesaman.dialog.Statics;
import java.util.ArrayList;
@EActivity(R.layout.app3)
@NoTitle
@Fullscreen
public class MyActivity3 extends Activity {
@Bean
GoodsDao goodsDao;
ArrayList<Goods> list = null;
LayoutInflater inflater;
LinearLayout parent1;
@ViewById
TextView app3_header_desc1;
String groupId1;
String groupName1;
String groupId2;
String groupName2;
@AfterViews
public void afterViews() {
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
parent1 = (LinearLayout) findViewById(R.id.app3_list);
Bundle extras = getIntent().getExtras();
if (extras != null) {
groupId1 = extras.getString("groupId1");
groupName1 = extras.getString("groupName1");
groupId2 = extras.getString("groupId2");
groupName2 = extras.getString("groupName2");
String prevString = (String) app3_header_desc1.getText();
app3_header_desc1.setText(prevString + " > " + groupName1 + " > " + groupName2);
}
list = goodsDao.getAllBySubGroup(groupId2);
if (list.size() == 0) {
TextView v = new TextView(this);
v.setText("رکوردی يافت نشد.");
v.setTypeface(Statics.getFontTypeFace_Titr());
v.setTextSize(30);
v.setTextColor(Color.RED);
parent1.addView(v);
} else {
for (int i = 0; i < list.size(); i++) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(String.valueOf(i));
}
}
}
private class AsyncTaskRunner extends AsyncTask<String, Void, View> {
@Override
protected View doInBackground(String... params) {
/*
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
return getNewView(Integer.valueOf(params[0]));
}
@Override
protected void onPostExecute(View view) {
parent1.addView(view);
}
}
private View getNewView(int i) {
View view = inflater.inflate(R.layout.app3_row_list, null, false);
if (i % 2 == 0) {
view.setBackgroundColor(Statics.getColorOdd());
} else {
view.setBackgroundColor(Statics.getColorEven());
}
Goods goods = list.get(i);
ImageView goodsGroupImage = (ImageView) view.findViewById(R.id.goodsGroupImage);
TextView goodsGroupQty = (TextView) view.findViewById(R.id.goodsQtyActive);
TextView rownum = (TextView) view.findViewById(R.id.rownum);
TextView goodsGroupName = (TextView) view.findViewById(R.id.goodsGroupName);
rownum.setText(String.valueOf(++i));
goodsGroupName.setText(goods.getCode() + " : " + goods.getName());
goodsGroupQty.setText(goods.getCode());
Statics.setImg2(goodsGroupImage, "Goods", goods.getCode());
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TextView bpp1_code = (TextView) view.findViewById(R.id.goodsQtyActive);
TextView bpp1_name = (TextView) view.findViewById(R.id.goodsGroupName);
final Dialog dialog = new Dialog(MyActivity3.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_goods);
dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
dialog.show();
ImageView imageView123 = (ImageView) dialog.findViewById(R.id.imageView123);
Statics.setImg3(imageView123, "Goods", bpp1_code.getText().toString(), 200, 400);
TextView custCode2 = (TextView) dialog.findViewById(R.id.app3_header_desc2);
custCode2.setTypeface(Statics.getFontTypeFace_Titr());
custCode2.setText(bpp1_code.getText().toString());
TextView custName2 = (TextView) dialog.findViewById(R.id.app3_header_desc1);
custName2.setTypeface(Statics.getFontTypeFace_Titr());
custName2.setText(bpp1_name.getText().toString());
}
});
return view;
}
} |
package sk.somvprahe.client;
import java.util.Date;
public class SvpEntity {
protected Date parseDate(String date) {
return new Date( Long.parseLong( date ) * 1000 );
}
}
|
package com.xue.trainingclass.activity;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.EmailVerifyListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.ResetPasswordByEmailListener;
import com.xue.trainingclass.bean.User;
import com.xue.trainingclass.tool.CommonTools;
import com.xue.trainingclass.tool.DataFormat;
public class PassResetActivity extends Activity {
private TextView mBack;
private EditText mEmail;
private Button mSendEmail;
private User mCurrentUser;
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_passreset);
mBack=(TextView) findViewById(R.id.back);
mEmail=(EditText) findViewById(R.id.E_email_resetPass);
mSendEmail=(Button) findViewById(R.id.sendEmail);
mBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
mCurrentUser=BmobUser.getCurrentUser(PassResetActivity.this, User.class);
if(null!=mCurrentUser){
//已登录
mEmail.setText(mCurrentUser.getEmail());
mEmail.setEnabled(false);
}
mSendEmail.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String email=mEmail.getText().toString();
if(email.equals("")){
Toast.makeText(getApplicationContext(), getResources().getString(R.string.inputEmail), 1).show();
}else if(!DataFormat.isEmail(email)){
Toast.makeText(getApplicationContext(), getResources().getString(R.string.emailFormatError), 1).show();
}else {
CommonTools.createLoadingDialog(PassResetActivity.this);
getCurrentUser();
}
}
});
};
/**
* 获取最新用户信息(非本地缓存)
*/
public void getCurrentUser(){
User user=BmobUser.getCurrentUser(PassResetActivity.this, User.class);
BmobQuery<User> query = new BmobQuery<User>();
query.addWhereEqualTo("username", user.getUsername());
query.findObjects(PassResetActivity.this, new FindListener<User>() {
@Override
public void onSuccess(List<User> object) {
CommonTools.cancleDialog();
mCurrentUser=(User) object.get(0);
if(!mCurrentUser.getEmailVerified()){
//邮箱未验证
AlertDialog.Builder builder=new AlertDialog.Builder(PassResetActivity.this);
builder.setTitle(getResources().getString(R.string.prompt));
builder.setMessage(getResources().getString(R.string.emailHaveNotVerified));
builder.setPositiveButton(getResources().getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 发送验证邮件
BmobUser.requestEmailVerify(PassResetActivity.this, mEmail.getText().toString(), new EmailVerifyListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
}
@Override
public void onFailure(int arg0, String arg1) {
// TODO Auto-generated method stub
}
});
dialog.dismiss();
}
});
builder.create();
builder.show();
}else{
// 发送邮件,修改密码
BmobUser.resetPasswordByEmail(PassResetActivity.this, mEmail.getText().toString(), new ResetPasswordByEmailListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sendEmailSucceed), 1).show();
finish();
}
@Override
public void onFailure(int arg0, String arg1) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), getResources().getString(R.string.sendEmailFail)+":"+arg1, 1).show();
}
});
}
}
@Override
public void onError(int code, String msg) {
CommonTools.cancleDialog();
}
});
}
}
|
package com.example.consumer.mapper;
import com.example.consumer.entity.MessageTest;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MessageTestMapper {
List<MessageTest> findAll();
}
|
package org.bridgedb.webservicetesting.BridgeDbWebservice;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
public class NoMatch extends RestletResource {
@Get
public Representation getNoMatchResult() {
String error = "Unrecognized query<p><font size='+1'><i>Double check the spelling and syntax. We are expecting "
+ "something like: <a href='http://webservice.bridgedb.org/Human/xrefs/L/1234'>webservice.bridgedb.org/Human/xrefs/L/1234</a></i></font></p>";
StringRepresentation sr = new StringRepresentation(error);
sr.setMediaType(MediaType.TEXT_HTML);
return sr;
}
}
|
package com.alibaba.druid.pool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Properties;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
public class MemTest {
HashMap m = new HashMap();
HashMap m1 = new HashMap(1);
ConcurrentHashMap cm = new ConcurrentHashMap();
ConcurrentHashMap cm1 = new ConcurrentHashMap(1, 0.75f, 1);
ConcurrentSkipListMap csm = new ConcurrentSkipListMap();
Hashtable ht = new Hashtable();
Properties p = new Properties();
TreeMap t = new TreeMap();
LinkedHashMap l = new LinkedHashMap();
TreeSet ts = new TreeSet();
HashSet hs = new HashSet();
LinkedHashSet lhs = new LinkedHashSet();
ArrayList list = new ArrayList();
ArrayList list1 = new ArrayList(1);
CopyOnWriteArrayList cpl = new CopyOnWriteArrayList();
CopyOnWriteArraySet cps = new CopyOnWriteArraySet();
Vector v = new Vector();
LinkedList ll = new LinkedList();
Stack stack = new Stack();
PriorityQueue pq = new PriorityQueue();
ConcurrentLinkedQueue clq = new ConcurrentLinkedQueue();
public static void main(String[] args) throws Exception {
MemTest o = new MemTest();
Thread.sleep(1000 * 1000);
System.out.println(o);
}
}
|
package edu.sjsu.assignment3;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.time.LocalDate;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class AppointmentTest {
@Test
public void testOccursOn() {
PrintStream original = System.out;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
OnetimeAppointment.occursOn(LocalDate.parse("2021-06-05"));
assertEquals(false, outputStream.toString().trim());
System.setOut(original);
}
@Test
public void testCompareTo() {
PrintStream original = System.out;
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
LocalDate startDate = LocalDate.parse("2021-06-01");
LocalDate endDate = LocalDate.parse("2021-08-05");
LocalDate date = LocalDate.parse("2021-08-01");
Appointment a1 = new OnetimeAppointment("Class starts", startDate);
Appointment a2 = new OnetimeAppointment("Class ends", endDate);
Appointment a3 = new DailyAppointment("Class", startDate, endDate);
Appointment a4 = new MonthlyAppointment("Code meeting", startDate, date);
Appointment a5 = new MonthlyAppointment("Assignment", startDate, endDate);
Appointment[] appointment = {a1, a2, a3, a4, a5};
Arrays.sort(appointment);
assertEquals("[Class starts from 2021-06-01 to 2021-06-01, Code meeting from 2021-06-01 to 2021-08-01, Assignment from 2021-06-01 to 2021-08-05, Class from 2021-06-01 to 2021-08-05, Class ends from 2021-08-05 to 2021-08-05]", outputStream.toString().trim());
System.setOut(original);
}
} |
package use_collection.use_list;
public class UseArrayList {
}
|
package org.jenkinsci.test.acceptance.docker.fixtures;
import org.jenkinsci.test.acceptance.docker.DockerContainer;
import org.jenkinsci.test.acceptance.docker.DockerFixture;
import java.io.IOException;
import java.net.URL;
/**
* Runs Foreman container.
*
*/
//CS IGNORE MagicNumber FOR NEXT 2 LINES. REASON: Mock object.
@DockerFixture(id = "foreman" , ports = 32768)
public class ForemanContainer extends DockerContainer {
/**
* URL of Foreman.
* @return URL.
* @throws IOException if occurs.
*/
//CS IGNORE MagicNumber FOR NEXT 2 LINES. REASON: Mock object.
public URL getUrl() throws IOException {
return new URL("http://" + getIpAddress() + ":3000");
}
}
|
package com.beike.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @ClassName: PartnerUtil
* @Description: 分销商加密解密
* @author yurenli
* @date 2012-6-4 下午06:42:13
* @version V1.0
*/
public class PartnerUtil {
private static final Log logger = LogFactory.getLog(PartnerUtil.class);
/**
* 分销商Des3Encryption加密
*
* @param source
* @param partnerDesKeyFilePath
* @return
* @throws Exception
*/
public static String cryptDes(String source, String secretKey) {
if (source == null || secretKey == null) {
return null;
}
String retTemp = "";
try {
retTemp = URLEncoder.encode(source, "UTF-8");
retTemp = DES58.encrypt(retTemp, secretKey);// des加密
retTemp = new String(com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(retTemp.getBytes()));// base64加密
retTemp = URLEncoder.encode(retTemp, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.info("++++++++++++++++++URLEncoder.encode++++Exception+++++" + source);
e.printStackTrace();
}
return retTemp;
}
/**
* 分销商Des3Encryption解密
*
* @param source
* @param partnerDesKeyFilePath
* @return
* @throws UnsupportedEncodingException
*/
public static String decryptDes(String source, String secretKey) {
if (source == null || secretKey == null) {
return null;
}
String decTemp = "";
try {
decTemp = URLDecoder.decode(source, "UTF-8");
byte[] tmp = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(decTemp);// base64解密
decTemp = DES58.decrypt(new String(tmp), secretKey);// des解密
decTemp = URLDecoder.decode(decTemp, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.info("++++++++++++++++++URLDecoder.decode++++Exception+++++");
e.printStackTrace();
}
return decTemp;
}
public static void main(String[] args) throws Exception {
String str = "ZDc3NWM3MDMyMDhjN2Y5MGQ4YjgxNTA0ODAyYWMyYzk1MzY3NzUyZTk1MWE0NmMwYzI4OTAxNDViNWE2YzgyNDZiMGMyMGIwNDY2YmQ4YTgwOWRlNjgwMWY3ZTRmYmMzYzgxZTNlYTI3YTk5MzA4MGRjMjIzMzhkYWFmZmVkN2E1MzY3NzUyZTk1MWE0NmMwYzI4OTAxNDViNWE2YzgyNGE3YjczNzA1MzVhNzg2MDA0ZGEyNTkxY2QwMmRhNTVkMmMyOWY3ZmMwZGNhNzM4ZWNiODI4ZmEwMTUxMTdmYWE3ZmIwN2YwMWE3NGZiYjJjYmZhZmVkMGMyNWVjMDgwNTM3OThkYWI0ZjcwZDhiMzAzMjQxNzZlNDBkNGJlYThlYmE5NDFjZjg1NDU3OGVkYmI1YWY0OWNkNTI0MTllOTFiZGM5MzE2MTRmOTdjZTljMWYyYzIwZjFiYzkyOTE5ZWY4ZDVhMjNhOTQ2YjQ5ZmIxOTgyNjQ1NzQ2NTU3YmYwZGZmZDAzNTI1MTk3M2FlMjRhNDIxMWIxOGIzNWRlZjJjNGNkODJiMjVkMGZkOTFjZDRlZGIxNWZkYjAzZjZiM2EyYjlhOTAxNWMxNmJmOTgzMTBiYjgwMTE5ZDBiODBmMGU2OTVmMGU5MGI1YjcxZmZlMTU5OGVkOTQ1NzY1ZTc0NTY2MmJiMWM3NTM1MjZjYWE5OTc3ODU0ZGYxMDg1MzBkMGY1MWJiNTYxYjk0YmY2MmY1NzRlMTAxZTY3ZTMxNmRhNmRhZDZhNmU5YzdlZGYxN2FiNmY0ZjA5YmIwMDNlNmFjZWY3ZmEwYWYyOGY4NGExNDNjYWE5ZWQ4ZTFmNDM0N2M1MzMxMTEzNjQ2ZGNjYmUwODI0Y2QyNTJlOTAzNzZjY2FmMmMwNjllZTkxYjEwNjIyMTBlMGYyNjdjMGY5NzZkNWM4MDVjOGYwZDE3NmQ2ZTJkZTI2Y2FiMjcxYWZiZDlkYzZiNzEyYmU1YjYzZDQ1MzY0YTk3MWFlZDQ5YjJmNmU4MzJmOGJhMzQ5NzBmOGQxODk4MTVkYzk3ZTc5MjMzMTIxMjk1ZTNiM2MyYTNmZmVlODc1NDI0OGU2MDNiODU3YTFkYzdmYjg1NDI5ZmFmYmU0OGRiMDc2ODk0ZjMzN2Y1MWEzZDE3NmE0MDNmNzUyYjliZmFjYzFiMjEyMjZhOGNhMjIxOTM3YmE0";
String str1 = decryptDes(str, "4c21d3d0b88e451aa8516e8894a85cfe");
System.out.println(str1);
}
/**
* 对字符串进行MD5签名,首尾放secret。
*
* @param params明文
*
* @return 密文
*/
public static String md5Signature(TreeMap<String, String> params, String secret) {
String result = null;
StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
if (orgin == null) {
return result;
}
orgin.append(secret);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
} catch (Exception e) {
throw new java.lang.RuntimeException("sign error !");
}
return result;
}
/**
* 对字符串进行MD5验签,首放secret,尾部不放secret。
*
* @param params明文
*
* @return 密文
*/
public static String md5SignatureSecret(TreeMap<String, String> params, String secret) {
String result = null;
StringBuffer orgin = getBeforeSign(params, new StringBuffer(secret));
if (orgin == null) {
return result;
}
// orgin.append(secret);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
result = byte2hex(md.digest(orgin.toString().getBytes("GBK")));
} catch (Exception e) {
throw new java.lang.RuntimeException("sign error !");
}
return result;
}
public static String md5SignatureSecret(String params, String appKey, String privateKey) {
String result = null;
if (StringUtils.isEmpty(params)) {
return result;
}
StringBuilder sb = new StringBuilder();
sb.append(appKey).append("|").append(privateKey).append("|").append(params);
try {
MessageDigest md = MessageDigest.getInstance("MD5");
result = byte2hex(md.digest(sb.toString().getBytes("GBK")));
} catch (Exception e) {
throw new java.lang.RuntimeException("sign error !");
}
return result;
}
/**
* 二行制转字符串
*/
private static String byte2hex(byte[] b) {
StringBuffer hs = new StringBuffer();
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs.append("0").append(stmp);
} else {
hs.append(stmp);
}
}
return hs.toString().toUpperCase();
}
/**
*
* 添加参数的封装方法
*/
private static StringBuffer getBeforeSign(TreeMap<String, String> params, StringBuffer orgin) {
if (params == null)
return null;
Map<String, String> treeMap = new TreeMap<String, String>();
treeMap.putAll(params);
Iterator<String> iter = treeMap.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
orgin.append(name).append(params.get(name));
}
return orgin;
}
/**
* 数据加密
*
* @param sArray
* @return
*/
public static String buildMysign(Map<String, String> sArray) {
String prestr = createLinkString(sArray); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
prestr = prestr + "123qwe456rty"; // 把拼接后的字符串再与安全校验码直接连接起来
String mysign = md5(prestr);
return mysign;
}
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
public static String md5(String text) {
return DigestUtils.md5Hex(getContentBytes(text, "utf-8"));
}
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
}
|
package com.pmikee.kir;
import java.io.Serializable;
import java.math.BigDecimal;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
String id;
String name;
String description;
BigDecimal stock;
BigDecimal unitPrice;
protected Product() {
}
public Product(String name, String description, BigDecimal stock, BigDecimal sellPrice) {
super();
this.name = name;
this.description = description;
this.stock = stock;
this.unitPrice = sellPrice;
}
@Override
public String toString() {
return "(" + id + ")" + name + ", leírás: " + description + ", készleten: " + stock + ", ára: " + unitPrice;
}
}
|
package selenium;
import selenium.helpers.SeleniumHelpersAnswers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Iteration2Answers {
private WebDriver driver;
private SeleniumHelpersAnswers selenium = new SeleniumHelpersAnswers();
@Before
public void startBrowser() {
System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
public void DoLoanRequest_UsingAmountsBeyondLimits_ShouldBeDenied() {
// Load page
driver.get("http://parabank.parasoft.com");
// Log in
selenium.sendKeys(driver, By.name("username"), "john");
selenium.sendKeys(driver, By.name("password"), "demo");
selenium.click(driver, By.xpath("//input[@value='Log In']"));
// Select Request Loan option from menu
selenium.click(driver, By.linkText("Request Loan"));
// Fill in form to request loan
selenium.sendKeys(driver, By.id("amount"), "1000");
selenium.sendKeys(driver, By.id("downPayment"), "100");
selenium.select(driver, By.id("fromAccountId"), "54321");
selenium.click(driver, By.xpath("//input[@value='Apply Now']"));
// Verify feedback
String actualStatus = selenium.getElementText(driver, By.id("loanStatus"));
Assert.assertEquals("Denied", actualStatus);
}
@After
public void closeBrowser() {
driver.quit();
}
}
|
package Instantiation;
public class Airplane {
public static void main(String[] args)
{
Boeing B = new Boeing();
B.takeOff();
B.takeDown();
Airbus A = new Airbus();
A.takeOff();
A.takeDown();
}
}
class Boeing extends Airplane implements Flight
{
public void takeOff()
{
System.out.println("Boeing class takeOff method running..");
}
public void takeDown()
{
System.out.println("Boeing class takeDown method running..");
}
}
class Airbus extends Airplane implements Flight
{
public void takeOff()
{
System.out.println("Airbus class takeoff method running..");
}
public void takeDown()
{
System.out.println("Airbus class takeDown method running..");
}
} |
package com.sai.one.config;
import com.sai.one.constants.PropertyConstants;
import com.sai.one.dto.User;
import com.sai.one.mq.RabbitMQ.listeners.RegisterListenerRabbitMQ;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* Created by shravan
*/
@Configuration
public class RabbitMQConfig {
@Bean
public ConnectionFactory connectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory(PropertyConstants.RabbitMQ.URL);
connectionFactory.setUsername(PropertyConstants.RabbitMQ.USERNAME);
connectionFactory.setPassword(PropertyConstants.RabbitMQ.PASSWORD);
return connectionFactory;
}
@Bean
DirectExchange registerExchange() {
return new DirectExchange(PropertyConstants.RabbitMQ.REGISTER_EXCHANGE, true, false);
}
@Bean
public Queue registerQueue() {
return new Queue(PropertyConstants.RabbitMQ.REGISTER_QUEUE, true);
}
@Bean
Binding registerExchangeBinding(DirectExchange registerExchange, Queue registerQueue) {
return BindingBuilder.bind(registerQueue).to(registerExchange).with(PropertyConstants.RabbitMQ.REGISTER_ROUTINGKEY);
}
@Bean
public RabbitTemplate rabbitTemplate() {
RabbitTemplate r = new RabbitTemplate(connectionFactory());
r.setExchange(PropertyConstants.RabbitMQ.REGISTER_EXCHANGE);
r.setRoutingKey(PropertyConstants.RabbitMQ.REGISTER_ROUTINGKEY);
r.setMessageConverter(jsonMessageConverter());
return r;
}
@Bean
public SimpleMessageListenerContainer registerListenerContainer() {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory());
container.setQueues(registerQueue());
container.setMessageConverter(jsonMessageConverter());
container.setConcurrentConsumers(PropertyConstants.RabbitMQ.REGISTER_CONSUMERS);
container.setMessageListener(registerListenerAdapter(registerReceiver()));
return container;
}
@Bean
public MessageConverter jsonMessageConverter() {
Jackson2JsonMessageConverter jsonConverter = new Jackson2JsonMessageConverter();
jsonConverter.setClassMapper(typeMapper());
return jsonConverter;
}
@Bean
RegisterListenerRabbitMQ registerReceiver() {
return new RegisterListenerRabbitMQ();
}
@Bean
MessageListenerAdapter registerListenerAdapter(RegisterListenerRabbitMQ receiver) {
return new MessageListenerAdapter(receiver, jsonMessageConverter());
}
@Bean
public DefaultClassMapper typeMapper() {
DefaultClassMapper typeMapper = new DefaultClassMapper();
Map<String, Class<?>> idClassMapping = new HashMap<>();
idClassMapping.put(PropertyConstants.RabbitMQ.TYPE_MAPPER, User.class);
typeMapper.setIdClassMapping(idClassMapping);
return typeMapper;
}
}
|
package com.taim.content.mapper;
import com.taim.backendservice.model.Staff;
import com.taim.content.model.StaffOverviewView;
import org.springframework.stereotype.Component;
@Component
public class StaffOverviewMapperImpl implements StaffOverviewMapper {
@Override
public StaffOverviewView map(Staff staff) {
return StaffOverviewView.builder()
.firstName(staff.getFirstName())
.lastName(staff.getLastName())
.email(staff.getEmail())
.phone(staff.getPhone())
.position(staff.getPosition().getValue())
.id(staff.getId())
.build();
}
}
|
package im.compIII.exghdecore.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/")
public class Index extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("WEB-INF/Index.jsp").forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String acao = (String) req.getParameter("navegacao");
if (acao == null) acao = "";
switch (acao) {
case "Comodo":
req.getRequestDispatcher("ServicoListarComodo").forward(req, resp);
break;
case "Mobilia":
req.getRequestDispatcher("ServicoListarMobilia").forward(req,resp);
break;
case "Ambiente":
req.getRequestDispatcher("ServicoListarAmbiente").forward(req,resp);
break;
case "Contrato":
req.getRequestDispatcher("ServicoListarContrato").forward(req,resp);
break;
default:
req.getRequestDispatcher("WEB-INF/Index.jsp").forward(req, resp);
}
}
}
|
package com.myvodafone.android.model.service;
import com.myvodafone.android.utils.GlobalData;
import com.myvodafone.android.utils.StaticTools;
import com.myvodafone.android.utils.VFPreferences;
import java.io.Serializable;
import java.util.ArrayList;
public class Bundle_item extends BundlesAddons implements Serializable {
public StringBuffer isactive = null;
public StringBuffer deactivation = null;
public StringBuffer activation = null;
public StringBuffer activation_Action = null;
public StringBuffer provisioning = null;
public StringBuffer activation_shortcode_tel = null;
public StringBuffer conf_msg_upon_deact_Gr = null;
public StringBuffer conf_msg_upon_deact_En = null;
public StringBuffer activation_inst_msg = null;
public StringBuffer deactivation_Command = null;
public StringBuffer category = null;
public StringBuffer activation_sms_text = null;
public StringBuffer nameGR = null;
public StringBuffer nameEN = null;
public StringBuffer code = null;
public StringBuffer short_descGR = null;
public StringBuffer short_descEN = null;
public StringBuffer long_descGR = null;
public StringBuffer long_descEN = null;
public StringBuffer price = null;
public StringBuffer priceGr = null;
public StringBuffer will_expire = null;
public StringBuffer expiration_date = null;
public StringBuffer new_category = null;
public StringBuffer has_recurring = null;
public StringBuffer recurring_code = null;
public StringBuffer bundleType = null;
public StringBuffer modDate = null;
public StringBuffer isNextBill = null;
public StringBuffer teaserEN = null;
public StringBuffer teaserGR = null;
public StringBuffer shortBundleNameEN = null;
public StringBuffer shortBundleNameGR = null;
public StringBuffer errorMsgEn = null;
public StringBuffer errorMsgGr = null;
// helpful variable for header
public int header = 0;
public int getHeader() {
return header;
}
public void setHeader(int header) {
this.header = header;
}
ArrayList<Asset_msisdn> msisdns = null;
public Bundle_item(String isactive, String iselligible, String isrecurring, String nameGR, String nameEN, String code,
String short_descGR, String short_descEN, String long_descGR, String long_descEN, String price, String priceGr) {
this.isactive = new StringBuffer(isactive);
this.nameGR = new StringBuffer(nameGR);
this.nameEN = new StringBuffer(nameEN);
this.code = new StringBuffer(code);
this.short_descGR = new StringBuffer(short_descGR);
this.short_descEN = new StringBuffer(short_descEN);
this.long_descGR = new StringBuffer(long_descGR);
this.long_descEN = new StringBuffer(long_descEN);
this.price = new StringBuffer(price);
this.priceGr = new StringBuffer(priceGr);
}
public Bundle_item() {
this.isactive = new StringBuffer();
this.deactivation = new StringBuffer();
this.activation = new StringBuffer();
this.activation_Action = new StringBuffer();
this.provisioning = new StringBuffer();
this.activation_shortcode_tel = new StringBuffer();
this.conf_msg_upon_deact_En = new StringBuffer();
this.conf_msg_upon_deact_Gr = new StringBuffer();
this.activation_inst_msg = new StringBuffer();
this.deactivation_Command = new StringBuffer();
this.category = new StringBuffer();
this.new_category = new StringBuffer();
this.activation_sms_text = new StringBuffer();
this.nameGR = new StringBuffer();
this.nameEN = new StringBuffer();
this.code = new StringBuffer();
this.short_descGR = new StringBuffer();
this.short_descEN = new StringBuffer();
this.long_descGR = new StringBuffer();
this.long_descEN = new StringBuffer();
this.price = new StringBuffer();
this.priceGr = new StringBuffer();
this.will_expire = new StringBuffer();
this.expiration_date = new StringBuffer();
this.has_recurring = new StringBuffer();
this.recurring_code = new StringBuffer();
this.bundleType = new StringBuffer();
this.modDate = new StringBuffer();
this.isNextBill = new StringBuffer();
this.teaserEN = new StringBuffer();
this.teaserGR = new StringBuffer();
this.shortBundleNameEN = new StringBuffer();
this.shortBundleNameGR = new StringBuffer();
this.errorMsgEn = new StringBuffer();
this.errorMsgGr = new StringBuffer();
}
// start
public String getDeactivation() {
return deactivation.toString();
}
public void setDeactivation(String deactivation) {
this.deactivation.append(deactivation.trim());
}
public String getActivation() {
return activation.toString();
}
public void setActivation(String activation) {
this.activation.append(activation.trim());
}
public String getActivation_Action() {
return activation_Action.toString();
}
public void setActivation_Action(String activation_Action) {
this.activation_Action.append(activation_Action.trim());
}
public String getProvisioning() {
return provisioning.toString();
}
public void setProvisioning(String provisioning) {
this.provisioning.append(provisioning.trim());
}
public String getActivation_shortcode_tel() {
return activation_shortcode_tel.toString();
}
public void setActivation_shortcode_tel(String activation_shortcode_tel) {
this.activation_shortcode_tel.append(activation_shortcode_tel.trim());
}
public String getConf_msg_upon_deact_En() {
return conf_msg_upon_deact_Gr.toString();
}
public void setConf_msg_upon_deact_En(String conf_msg_upon_deact_En) {
this.conf_msg_upon_deact_En.append(conf_msg_upon_deact_En.trim());
}
public void setConf_msg_upon_deact_Gr(String conf_msg_upon_deact_Gr) {
this.conf_msg_upon_deact_Gr.append(conf_msg_upon_deact_Gr.trim());
}
public String getConf_msg_upon_deact_Gr() {
return conf_msg_upon_deact_Gr.toString();
}
public String getConf_msg_upon_deact() {
if (VFPreferences.getLanguage()!= GlobalData.LANGUAGE_GR){
return conf_msg_upon_deact_En.toString();
} else {
return conf_msg_upon_deact_Gr.toString();
}
}
public String getActivation_inst_msg() {
return activation_inst_msg.toString();
}
public void setActivation_inst_msg(String activation_inst_msg) {
this.activation_inst_msg.append(activation_inst_msg.trim());
}
public String getDeactivation_Command() {
return deactivation_Command.toString();
}
public void setDeactivation_Command(String deactivation_Command) {
this.deactivation_Command.append(deactivation_Command.trim());
}
public String getCategory() {
return category.toString();
}
public void setCategory(String category) {
this.category.append(category.trim());
}
public String getNew_Category() {
return new_category.toString();
}
public void setNew_Category(String category) {
this.new_category.append(category.trim());
}
public String getActivation_sms_text() {
return activation_sms_text.toString();
}
public void setActivation_sms_text(String activation_sms_text) {
this.activation_sms_text.append(activation_sms_text.trim());
}
// /end
public String getIsactive() {
return isactive.toString();
}
public void setIsactive(String isactive) {
this.isactive = new StringBuffer(isactive);
}
public String getNameGR() {
return nameGR.toString();
}
public void setNameGR(String nameGR) {
this.nameGR.append(nameGR.trim());
}
public String getNameEN() {
return nameEN.toString();
}
public String getName() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return nameEN.toString();
} else {
return nameGR.toString();
}
}
public String getShortBundleName() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return shortBundleNameEN.toString();
} else {
return shortBundleNameGR.toString();
}
}
public void setNameEN(String nameEN) {
this.nameEN.append(nameEN.trim());
}
public String getCode() {
return code.toString();
}
public void setCode(String code) {
this.code.append(code.trim());
}
public String getShort_descGR() {
return short_descGR.toString();
}
public void setShort_descGR(String short_descGR) {
this.short_descGR.append(short_descGR.trim());
}
public void setShort_descEn(String short_descEN) {
this.short_descEN.append(short_descEN.trim());
}
public String getShort_descEn() {
return short_descEN.toString();
}
public String getShort_desc() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return short_descEN.toString();
} else {
return short_descGR.toString();
}
}
public String getLong_descGR() {
return long_descGR.toString();
}
public void setLong_descGR(String long_descGR) {
this.long_descGR.append(long_descGR.trim());
}
public String getLong_desc() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return long_descEN.toString();
} else {
return long_descGR.toString();
}
}
public String getLong_descEN() {
return long_descEN.toString();
}
public void setLong_descEN(String long_descEN) {
this.long_descEN.append(long_descEN.trim());
}
public String getPriceGr() {
return priceGr.toString();
}
public String getPrice() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return price.toString();
} else {
return priceGr.toString();
}
}
public void setPriceGr(String priceGr) {
this.priceGr.append(priceGr.trim());
}
public void setPrice(String price) {
this.price.append(price.trim());
}
public void setExpirationDate(String expirationdate) {
this.expiration_date.append(expirationdate.trim());
}
public String getExpirationDate() {
return expiration_date.toString();
}
public void setWillExpire(String will_expire) {
this.will_expire.append(will_expire.trim());
}
public String getWillExpire() {
return will_expire.toString();
}
public void setHas_recurring(String has_recurring) {
this.has_recurring.append(has_recurring);
}
public String getHas_recurring() {
return has_recurring.toString();
}
public String getRecurring_code() {
return recurring_code.toString();
}
public void setRecurring_code(String recurring_code) {
this.recurring_code.append(recurring_code);
}
public String getBundleType() {
return bundleType.toString();
}
public void setBundleType(String bundleType) {
this.bundleType.append(bundleType);
}
public void setModDate(String modDate) {
this.modDate.append(modDate);
}
public String getModDate() {
return modDate.toString();
}
public String getIsNextBill() {
return isNextBill.toString();
}
public void setIsNextBill(String isNextBill) {
this.isNextBill.append(isNextBill);
}
public void setTeaserEN(String teaserEN) {
this.teaserEN.append(teaserEN);
}
public String getTeaserEN() {
return teaserEN.toString();
}
public void setTeaserGR(String teaserGR) {
this.teaserGR.append(teaserGR);
}
public String getTeaserGR() {
return teaserGR.toString();
}
public String getTeaser() {
if (VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return teaserEN.toString();
} else {
return teaserGR.toString();
}
}
public String getShortBundleNameEN() {
return shortBundleNameEN.toString();
}
public String getShortBundleNameGR() {
return shortBundleNameGR.toString();
}
public void setShortBundleNameEN(String shortBundleNameEN) {
this.shortBundleNameEN.append(shortBundleNameEN);
}
public void setShortBundleNameGR(String shortBundleNameGR) {
this.shortBundleNameGR.append(shortBundleNameGR);
}
public StringBuffer getErrorMsgEn() {
return errorMsgEn;
}
public void setErrorMsgEn(String errorMsgEn) {
this.errorMsgEn.append(errorMsgEn);
}
public String getErrorMsgGr() {
return errorMsgGr.toString();
}
public void setErrorMsgGr(String errorMsgGr) {
this.errorMsgGr.append(errorMsgGr);
}
public String getErrorMsg() {
if(VFPreferences.getLanguage() != GlobalData.LANGUAGE_GR) {
return errorMsgEn.toString();
}
else {
return errorMsgGr.toString();
}
}
// PRINT
public void print() {
StaticTools.Log("ITEM BANNER:: ", " ");
// StaticTools.Log("ITEM BANNER:: ", "price: " + price);
// StaticTools.Log("ITEM BANNER:: ", "priceGr: " + priceGr);
// StaticTools.Log("ITEM BANNER:: ", " isactive " + isactive);
// StaticTools.Log("ITEM BANNER:: ", " nameGR " + nameGR);
// StaticTools.Log("ITEM BANNER:: ", "nameEN " + nameEN);
// StaticTools.Log("ITEM BANNER:: ", "code" + code);
// StaticTools.Log("ITEM BANNER:: ", "short_descGR " + short_descGR);
// StaticTools.Log("ITEM BANNER:: ", "short_descEN " + short_descEN);
// StaticTools.Log("ITEM BANNER:: ", "long_descGR " + long_descGR);
// StaticTools.Log("ITEM BANNER:: ", "long_descEN " + long_descEN);
//
// StaticTools.Log("ITEM BANNER:: ", "deactivation " + deactivation);
// StaticTools.Log("ITEM BANNER:: ", "activation " + activation);
// StaticTools.Log("ITEM BANNER:: ", "activation_Action " +
// activation_Action);
// StaticTools.Log("ITEM BANNER:: ", "provisioning " + provisioning);
// StaticTools.Log("ITEM BANNER:: ", "conf_msg_upon_deact " +
// getConf_msg_upon_deact());
// StaticTools.Log("ITEM BANNER:: ", "activation_shortcode_tel " +
// activation_shortcode_tel);
// StaticTools.Log("ITEM BANNER:: ", "activation_inst_msg " +
// activation_inst_msg);
// StaticTools.Log("ITEM BANNER:: ", "deactivation_Command " +
// deactivation_Command);
StaticTools.Log("ITEM BANNER:: ", "category " + category);
StaticTools.Log("ITEM BANNER:: ", "activation_sms_text " + activation_sms_text);
StaticTools.Log("ITEM BANNER:: ", "##########################");
}
} |
package com.petclinicspring.com.services.map;
import com.petclinicspring.com.models.Owner;
import com.petclinicspring.com.services.PetService;
import com.petclinicspring.com.services.PetTypeService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class OwnerMapServiceTest {
@Mock
PetTypeService petTypeService;
@Mock
PetService petService;
@InjectMocks
OwnerMapService service;
Owner owner;
@BeforeEach
void setUp() {
owner = Owner.builder().id(1L).address("DAT NAGAR").lastName("Bundhe").build();
service.save(owner);
}
@Test
void findAll() {
Set<Owner> ownerSet = service.findAll();
assertNotNull(ownerSet);
assertEquals(ownerSet.size(), 1);
}
@Test
void findById() {
Owner owner1= service.findById(1l);
assertEquals(owner1,owner);
}
@Test
void save() {
Long id= 2L;
Owner owner2= Owner.builder().id(2L).firstName("Kishor").build();
service.save(owner2);
assertEquals(id,owner2.getId());
}
@Test
void delete() {
service.delete(owner);
assertEquals(0,service.findAll().size());
}
@Test
void deleteById() {
service.deleteById(owner.getId());
assertEquals(0,service.findAll().size());
}
@Test
void findByLastName() {
Owner owner1= service.findByLastName("Bundhe");
assertEquals( owner,owner1);
}
@Test
void findByLastNameNotExist() {
Owner owner1= service.findByLastName("Bundhe1");
assertNull(owner1);
}
} |
package com.pan.al.graph;
import java.util.ArrayList;
import java.util.List;
public class minlu {
/**
* 从一顶点到其余各顶点的最短路径 o(n2)
* @param gr
* @param i
* @param dist
* @param path
*/
public static void Dijkstra(AdjacencyGraph gr,int i,int [] dist,List[] path)
{
//利用迪克斯特拉算法求图gr中从顶点i到其余各顶点的最短距离和最短路径
//它们分别被保存在dist和path数组中
int n=gr.getVertices(); //取出图gr对象中的顶点个数并赋给n
if(i<0||i>n-1)
{
System.out.println("源点序号i的值不在有效范围内,退出运行!");
System.exit(1);
}
int [][] a=gr.getArray(); //取出gr对象中邻接矩阵的引用
boolean []s=new boolean[n]; //定义保存顶点集合的数组s
//分别给s,dist和path数组赋初值
for(int v=0;v<n;v++)
{
if(v==i)
{
s[v]=true;
}
else
{
s[v]=false;
}
}
for(int v=0;v<n;v++)
{
dist[v]=a[i][v];
}
for(int v=0;v<n;v++)
{
path[v]=new ArrayList();
if(a[i][v]!=gr.getMaxValue() && v!=i)
{
path[v].add(i,1);
path[v].add(v, 2);
}
}
//共进行n-2次循环,每次求出从源点i到终点m的最短路径及长度
for(int k=1;k<=n-2;k++)
{
//求出第k次运算的终点m
int w=gr.getMaxValue();
int m=i;
for(int j=0;j<n;j++)
{
if(s[j]==false && dist[j]<w)
{
w=dist[j];
m=j;
}
}
//若条件成立,则把顶点m并入集合数组s中,否则退出循环,因为剩余顶点
//其最短路径长度均为MaxValue,无须再计算下去
if(m!=i)
{
s[m]=true;
}
else
{
break;
}
//对s元素为false的对应dist和path中的元素作必要修改
for(int j=0;j<n;j++)
{
if(s[j]==false && dist[m]+a[m][j]<dist[j])
{
dist[j]=dist[m]+a[m][j];
path[j].clear();
for(int pos=1;pos<=path[m].size();pos++)
{
path[j].add((int)path[m].get(pos),pos);
}
path[j].add(j,path[j].size()+1);
}
}
}
}
}
|
package net.klonima.reddittechnicaltest.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import net.klonima.reddittechnicaltest.R;
import net.klonima.reddittechnicaltest.adapters.subredditListAdapter;
import net.klonima.reddittechnicaltest.constants.GeneralConstants;
import net.klonima.reddittechnicaltest.constants.HandlerConstants;
import net.klonima.reddittechnicaltest.constants.RedditConstants;
import net.klonima.reddittechnicaltest.managers.RedditManager;
import net.klonima.reddittechnicaltest.models.Responses.RedditListingResponse;
import net.klonima.reddittechnicaltest.models.Responses.SubRedditResponse;
import net.klonima.reddittechnicaltest.models.adapters.SubredditListItemDTO;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by:
* Oscar Andres Dussan Garcia - oadussang@gmail.com.
* Bogota Colombia - 23/02/2017
*/
public class SubRedditListActivity extends Activity {
private ListView subredditListLV;
private ProgressBar subredditListPB;
private ArrayList<SubredditListItemDTO> subredditsList;
private static Handler subRedditListHandler;
private RedditManager redditManager;
private Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
setContentView(R.layout.fragment_subreddit_list);
initViews();
initVars();
initHandlers();
initManagers();
setClickListeners();
redditManager.getRedditListings();
}
private void initViews() {
subredditListLV = (ListView) findViewById(R.id.subreddit_list_lv);
subredditListPB = (ProgressBar)findViewById(R.id.subreddit_list_pb);
}
private void initVars() {
if(subredditsList==null){
subredditsList = new ArrayList<>();
}
}
private void initManagers() {
if (redditManager == null) {
redditManager = new RedditManager(subRedditListHandler);
}
}
private void setClickListeners() {
subredditListLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(activity, SubRedditDetailActivity.class);
intent.putExtra(GeneralConstants.INTENT_EXTRA_SELECTED_ITEM,subredditsList.get(i));
startActivity(intent);
}
});
}
private void setAdapters(ArrayList<SubredditListItemDTO> subredditsList) {
subredditListAdapter adapter = new subredditListAdapter(this, subredditsList);
subredditListLV.setAdapter(adapter);
}
private void initHandlers() {
if (subRedditListHandler == null) {
subRedditListHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case HandlerConstants.REDDIT_LISTING_RESPONSE_SUCCESS_CODE:
List<SubRedditResponse> subredditResponseList = ((RedditListingResponse) msg.obj).getData().getChildren();
for (SubRedditResponse responseItems:subredditResponseList) {
subredditsList.add(new SubredditListItemDTO(
responseItems.getData().getIconImage(),
responseItems.getData().getBannerImage(),
responseItems.getData().getTitle(),
responseItems.getData().getPublicDescription(),
responseItems.getData().getDescription(),
responseItems.getData().getDisplayNamePrefixed(),
String.format(RedditConstants.SUBSCRIBERS_TEXT, NumberFormat.getNumberInstance(Locale.US).format(responseItems.getData().getSubscribersNumber())),
responseItems.getData().getSubmitText(),
responseItems.getData().isAgeResctricted()
));
}
if (subredditsList != null) {
setAdapters(subredditsList);
subredditListPB.setVisibility(View.INVISIBLE);
}
break;
case HandlerConstants.REDDIT_LISTING_RESPONSE_FAILURE_CODE:
//TODO inform bad connection
break;
}
}
};
}
}
}
|
package io.github.satr.aws.lambda.bookstore.entity;
// Copyright © 2020, github.com/satr, MIT License
import java.util.UUID;
public class Book {
private String isbn;
private String title;
private String author;
private int issueYear;
private double price = 0.0;
public Book() {
this.isbn = String.valueOf(Math.abs(UUID.randomUUID().toString().hashCode()));//fake ISBN
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public void setIssueYear(int issueYear) {
this.issueYear = issueYear;
}
public int getIssueYear() {
return issueYear;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
|
package tree;
import java.util.List;
public interface Tree {
List<TreeNode> preOrder(boolean withRec, TreeNode currentNode);
List<TreeNode> inOrder(boolean withRec, TreeNode currentNode);
List<TreeNode> postOrder(boolean withRec, TreeNode currentNode);
List<TreeNode> levelOrder(TreeNode currentNode);
int getHeight(TreeNode currentNode);
List<TreeNode> getAllAncestors(TreeNode currentNode);
TreeNode getRoot();
}
|
package quizapp.core;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UserTest {
private User user;
@BeforeEach
public void setUser() {
user = new User("Hallvard", "Trætteberg");
user.addQuiz("quiz1", 1);
user.addQuiz("quiz2", 0);
user.setCurrentQuiz(new Quiz("test quiz", new Question(), new Question(), new Question()));
}
@Test
public void darkmodeTest() {
assertFalse(user.getDarkMode());
user.setDarkMode(true);
assertTrue(user.getDarkMode());
}
@Test
public void currentQuizTest() {
assertEquals("test quiz", user.getCurrentQuiz().getName());
user.setCurrentQuiz(new Quiz("test quiz2", new Question(), new Question(), new Question()));
assertEquals("test quiz2", user.getCurrentQuiz().getName());
}
@Test
public void equalsTest() {
assertTrue(user.equals(user));
User newUser = new User();
newUser.setUsername("Hallvard");
newUser.setPassword("Trætteberg");
assertTrue(user.equals(newUser));
User secondUser = new User("Hallvard2", "Trætteberg");
assertFalse(user.equals(secondUser));
Quiz quiz = new Quiz();
assertFalse(user.equals(quiz));
}
@Test
public void makeUserfromUserTest() {
User newUser = new User(user);
assertEquals("Hallvard", newUser.getUsername());
assertEquals("Trætteberg", newUser.getPassword());
assertEquals(user.getDarkMode(), newUser.getDarkMode());
assertEquals(user.getCurrentQuiz(), newUser.getCurrentQuiz());
assertEquals(user.getQuizzesTaken(), newUser.getQuizzesTaken());
}
@Test
public void correctUsernameAndPassword() {
// Tests the getter methods
assertEquals(user.getUsername(), "Hallvard");
assertEquals(user.getPassword(), "Trætteberg");
}
@Test
public void correctMeanScore() {
// Checks User.meanScore() method
assertEquals(user.meanScore(), 0.5);
}
@Test
public void hasTakenQuiz() {
// Checks if User.quizTaken() works properly
assertTrue(user.quizTaken("quiz1"));
}
@Test
public void hasNotTakenQuiz() {
// Checks if User.quizTaken() works properly
assertFalse(user.quizTaken("quiz3"));
}
@Test
public void getCorrectScore() {
// Checks if User.getScore() works properly
assertEquals(1.0, user.getScore("quiz1"));
}
@Test
public void retakeQuiz() {
user.addQuiz("quiz1", 0);
assertEquals(0, user.getScore("quiz1"));
}
@Test
public void toStringTest() {
assertEquals("Hallvard Trætteberg", user.toString());
}
} |
package nju.joytrip.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import nju.joytrip.R;
import nju.joytrip.activity.PicWordSharePublish;
import nju.joytrip.activity.ShareDetail;
import nju.joytrip.adapter.ShareAdapter;
import nju.joytrip.entity.PWShare;
public class UpdatesFragment extends Fragment {
private ListView lv;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle saveInstanceState){
View view = inflater.inflate(R.layout.fragment_updates, container, false);
setHasOptionsMenu(true);
lv = (ListView)view.findViewById(R.id.share_item_list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PWShare h = (PWShare) parent.getItemAtPosition(position);
String eventId = h.getObjectId();
Intent intent = new Intent(getActivity(), ShareDetail.class);
intent.putExtra("id", eventId);
startActivity(intent);
}
});
init();
return view;
}
public void init(){
BmobQuery<PWShare> bmobQuery = new BmobQuery<PWShare>();
bmobQuery.include("user");
bmobQuery.order("-createdAt");
bmobQuery.findObjects(new FindListener<PWShare>() {
@Override
public void done(List<PWShare> list, BmobException e) {
if (e == null) {
lv.setAdapter(new ShareAdapter(getActivity(), R.layout.share_item, list));
}
}
});
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.share_menu,menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Intent intent;
switch(id){
case R.id.menu_item_pw_share:
intent = new Intent(getActivity(), PicWordSharePublish.class );
startActivity(intent);
return true;
case R.id.menu_item_v_share:
Toast.makeText(getActivity(), "敬请期待", Toast.LENGTH_SHORT).show();
return true;
// intent = new Intent(getActivity(), PicWordSharePublish.class);
// startActivity(intent);
// return true;
}
return false;
}
}
|
/*
* 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 edu.uha.miage.core.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author victo
*/
@Entity
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = {"libelle"})})
public class Departement implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Size(min = 2, max = 50)
// Nom du Département
private String libelle;
@OneToMany(mappedBy = "departement")
private List<Fonction> fonctions;
public Departement(String libelle) {
this.libelle = libelle;
}
public Departement() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public List<Fonction> getFonctions() {
return fonctions;
}
public void setFonctions(List<Fonction> fonctions) {
this.fonctions = fonctions;
}
@Override
public String toString() {
return libelle;
}
}
|
package com.eshop.models;
import com.eshop.exceptions.InvalidInputException;
public class Mouse extends Article {
private String resolution;
public Mouse(String label, String model, double price, String resolution, String image, int id)
throws InvalidInputException {
super(label, model, price, image, id);
setResolution(resolution);
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) throws InvalidInputException {
if (resolution != null && !resolution.isEmpty()) {
this.resolution = resolution;
} else {
throw new InvalidInputException("Invalid resolution!");
}
}
@Override
public String toString() {
return "Mouse [resolution=" + resolution + ", toString()=" + super.toString() + "]";
}
}
|
//this is just like the Main.java file in the Treehouse coursework
public class Example{
public static void main(String args[]){
//Person is a data type
//create persons
Person student1 = new Person("Josh",30);
Person student2 = new Person("Sandie",20);
Person student3 = new Person("Mimi",15);
Person student4 = new Person("Jim",40);
Animal animal1 = new Animal("Nala","Cat");
Animal animal2 = new Animal("Cuddles","Cat");
Animal animal3 = new Animal("Fluffy","Cat");
Animal animal4 = new Animal("Dopey","Cat");
animal1.attacks(student1.getName());
animal2.attacks(student3.getName());
animal3.attacks(student2.getName());
animal4.attacks(student4.getName());
student1.printP();
student2.printP();
student3.printP();
student4.printP();
//variables
student1.sayHello(student2.getName());
}
} |
package restaurant;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Main {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
Session session = null;
try {
// This step will read hibernate.cfg.xml and prepare hibernate for use
sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
}
catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
finally{
session.flush();
session.close();
}
ManageOrder MO = new ManageOrder();
MO.lisOrders();
}
}
|
package com.lesports.albatross.adapter.learn;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lesports.albatross.R;
import com.lesports.albatross.entity.user.UserEntity;
import com.lesports.albatross.utils.ToActivityUtil;
import java.util.List;
/**
* 观看者适配器 -抽取(和比赛详情一样)
* 1 全部观看者+名字
* 2 部分观看者 +不加名字
* Created by zhouchenbin on 16/6/21.
*/
public class ViewersAdapter extends RecyclerView.Adapter<ViewersAdapter.ViewersHolder> {
private Context mContext;
private List<UserEntity> mList;
private ViewerType viewerType;
private String videoId =""; //得到更多
public ViewersAdapter(Context context, List<UserEntity> viewersViewHolders, ViewerType type,String videoId){
this.mContext = context;
this.mList = viewersViewHolders;
this.viewerType = type;
this.videoId = videoId;
}
public void updata(List<UserEntity> list){
if (mList==null)
return;
mList.clear();
mList.addAll(list);
notifyDataSetChanged();
}
@Override
public ViewersHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.activity_viewers_list_item,parent,false);
return new ViewersHolder(view);
}
@Override
public void onBindViewHolder(ViewersHolder holder, final int position) {
UserEntity userEntity = mList.get(position);
if (userEntity==null)
return;
switch (viewerType){
//没有名字
case NO_NAME:
// holder.name.setVisibility(View.GONE);
if (userEntity.getAvatarUri().equals("moreimage")){
//设置更多
holder.header.setImageResource(R.drawable.game_detaile_btn_more);
}else {
holder.header.setImageURI(userEntity.getAvatarUri());
}
break;
//正常
case NORMAL:
holder.name.setVisibility(View.VISIBLE);
String nickname = userEntity.getNickname();
if (nickname!=null&& nickname.length()>=6){
nickname = nickname.substring(0,3)+"...";
}
holder.name.setText(nickname);
holder.header.setImageURI(userEntity.getAvatarUri());
break;
default:
break;
}
//设置监听器
holder.header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (viewerType==ViewerType.NO_NAME&&position==mList.size()-1){
//去更多,单行显示并且最后一个
ToActivityUtil.goToViewedUsers(mContext,videoId);
}else {
//去个人主页
ToActivityUtil.goToUserActivity(mContext,mList.get(position).getUserId());
}
}
});
}
@Override
public void onViewRecycled(ViewersHolder holder) {
super.onViewRecycled(holder);
}
@Override
public int getItemCount() {
return mList==null?0:mList.size();
}
public class ViewersHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView name;
private SimpleDraweeView header;
public ViewersHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.name);
header = (SimpleDraweeView) itemView.findViewById(R.id.header);
}
// @Override
public void onClick(View v) {
// //进入个人主页
// Intent i = new Intent(mContext, MineDynamicActivity.class);
// mContext.startActivity(i);
//
//// ToActivityUtil.goToUserActivity(mContext,mList.get(p));
//
//
}
}
//viewer的类型 nornal:含名字 no_name:不含名字,只含头像
public enum ViewerType{
NO_NAME,NORMAL
}
}
|
package pathfinding;
import java.util.ArrayList;
public class Simulator {
private PF_Core pf;
private PF_Core pf2;
private PathFinding PFS;
private double[] Position = {1,0.8};
private double step = 100;
private boolean is_simulated = false;
private ArrayList<Integer> waypointListX = new ArrayList<Integer>();
private ArrayList<Integer> waypointListY = new ArrayList<Integer>();
private ArrayList<Integer> waypointDirection = new ArrayList<Integer>();
private ArrayList<Integer> waypointShortListX = new ArrayList<Integer>();
private ArrayList<Integer> waypointShortListY = new ArrayList<Integer>();
public Simulator(double[] StartPos,double[] EndPos,double step){
is_simulated = false;
step *= 100;//convert m -> cm
this.step = step;
Position[0] = StartPos[0];
Position[1] = StartPos[1];
//initialize
waypointListX = new ArrayList<Integer>();
waypointListY = new ArrayList<Integer>();
waypointDirection = new ArrayList<Integer>();
waypointShortListX = new ArrayList<Integer>();
waypointShortListY = new ArrayList<Integer>();
pf = new PF_Core();
pf2 = new PF_Core();
PFS = new PathFinding((int)(StartPos[0]*100),(int)(StartPos[1]*100),(int)(EndPos[0]*100),(int)(EndPos[1]*100),false,30,8);
}
public double[][] Simulate2(){
PFS.findPath(waypointListX, waypointListY, waypointDirection, false,waypointShortListX,waypointShortListY);
int count = waypointShortListX.size();
double[][] val = new double[count-1][2];
for (int i = 0; i < count - 1; i++){
val[i][0] = waypointShortListX.get(i+1) * 0.01d;
val[i][1] = waypointShortListY.get(i+1) * 0.01d;
}
return val;
}
public boolean Simulate(){
PFS.findPath(waypointListX, waypointListY, waypointDirection, false,waypointShortListX,waypointShortListY);
int waypoint_count = 0,interval = 0;
double sum = 0;
for(int i=1; i<waypointShortListX.size();i++){
sum += Math.hypot((waypointShortListX.get(i) - waypointShortListX.get(i-1)),(waypointShortListY.get(i)-waypointShortListY.get(i-1)));
}
waypoint_count = (int) Math.ceil((sum / step));
double[] waypointX = new double[waypoint_count];
double[] waypointY = new double[waypoint_count];
interval = (int)Math.floor((waypointListX.size()-1) / (waypoint_count -1));
for (int i = 0;i < waypoint_count -1;i++){
waypointX[i] = waypointListX.get(i * interval);
waypointY[i] = waypointListY.get(i * interval);
}
waypointX[waypoint_count-1] = waypointShortListX.get(waypointShortListX.size()-1);
waypointY[waypoint_count-1] = waypointShortListY.get(waypointShortListY.size()-1);
for (int i = 1; i < waypoint_count; i++){
waypointX[i] /= 100;
waypointY[i] /= 100;
double[] val = {waypointX[i],waypointY[i]};
pf.addGoal(val);
pf2.addGoal(val);
}
//Switch,Scale,Switch
double[] pos1 = {4.11,4.26};
double[] pos2 = {4.11,8.22};
double[] pos3 = {4.11,12.19};
//field frame
double[] posleft = {0,8.22};
double[] posright = {8.22,8.22};
double[] posup = {4.11,16.44};
double[] posdown = {4.11,0};
//obstacles
pf.addObstacle(pos1, 1.42,3.89,0);
pf.addObstacle(pos2, 3.17,3.39,0);
pf.addObstacle(pos3, 1.42,3.89,0);
//frames
pf.addObstacle(posleft, 16.44,0.05,0);
pf.addObstacle(posright, 16.44,0.05,0);
pf.addObstacle(posup, 0.05,8.22,0);
pf.addObstacle(posdown, 0.05,8.22,0);
//obstacles
pf2.addObstacle(pos1, 1.42,3.89,0);
pf2.addObstacle(pos2, 3.17,3.39,0);
pf2.addObstacle(pos3, 1.42,3.89,0);
//frames
pf2.addObstacle(posleft, 16.44,0.05,0);
pf2.addObstacle(posright, 16.44,0.05,0);
pf2.addObstacle(posup, 0.05,8.22,0);
pf2.addObstacle(posdown, 0.05,8.22,0);
for (int i = 0; i < 500; i++){
double[] F = {0,0};
F = pf.update(Position);
Position[0] += F[0] / Math.hypot(F[0], F[1]) * 0.05;
Position[1] += F[1] / Math.hypot(F[0], F[1]) * 0.05;
System.out.print(F[0]);
System.out.print("\t");
System.out.println(F[1]);
if (pf.isReached()){
break;
}
}
is_simulated = true;
boolean reached = pf.isReached();
pf.resetGoal();
for (int i = 1; i < waypoint_count; i++){
waypointX[i] /= 100;
waypointY[i] /= 100;
double[] val = {waypointX[i],waypointY[i]};
pf.addGoal(val);
}
return reached;
}
public double[] getForce(double[] Position){
double[] val = {0,0};
if (this.is_simulated){
val = this.pf2.update(Position);
}
return val;
}
public static double[] Rotate(double[] Vector,double Radius){
double[] ans = {0,0};
ans[0] = Math.cos(Radius) * Vector[0] - Math.sin(Radius) * Vector[1];
ans[1] = Math.sin(Radius) * Vector[0] + Math.cos(Radius) * Vector[1];
return ans;
}
}
|
package com.pescamillam.ewavefem.window;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import com.pescamillam.ewavefem.solver.elem.Element;
import com.pescamillam.ewavefem.solver.model.FeLoad;
import com.pescamillam.ewavefem.solver.processor.FemProcessor;
import com.pescamillam.ewavefem.solver.reader.FeScanner;
import com.pescamillam.ewavefem.solver.writer.FePrintWriter;
import com.pescamillam.ewavefem.window.canvas.FemCanvas;
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger("Window");
private static final JTextArea logTextArea = new JTextArea("");
private static final JScrollPane logTextAreaScroll = new JScrollPane(logTextArea);
public static FemCanvas canvas;
private Properties properties = new Properties();
private File propertiesFile = new File("config.properties");
public Window() throws IOException {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
JButton loadFileButton = new JButton("Load File");
loadFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!propertiesFile.exists()) {
saveFileProperty("/home/peter/Peter/projects/fem/examples/example02");
} else {
try {
FileInputStream fis = new FileInputStream(propertiesFile);
properties.load(new FileInputStream(propertiesFile));
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
JFileChooser fileSelector = new JFileChooser(properties.getProperty("file"));
int returnVal = fileSelector.showOpenDialog(Window.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileSelector.getSelectedFile();
saveFileProperty(file.getParent());
logTextArea.append("Archivo cargado: ");
logTextArea.append(file.getAbsolutePath());
LOGGER.info("Abriendo: " + file.getAbsolutePath());
long inicio = System.nanoTime();
FeScanner reader = new FeScanner(file.getAbsolutePath());
PrintWriter writer = new FePrintWriter().getPrinter(file.getAbsolutePath() + ".out");
FemProcessor processor = new FemProcessor();
processor.process(reader, writer, file.getParentFile().getAbsolutePath());
logTextArea.append("\nNumero de nodos " + processor.getFem().nNod);
logTextArea.append("\nnodos ");
// System.out.println("Elements:");
// for (Element a : processor.getFem().elems) {
// for (int b : a.ind) {
// System.out.print(b + " ");
// }
// System.out.println();
// }
// int nodeCounter = 0;
// System.out.println("Nodes:");
// for (double[] a : Element.xy) {
// if (nodeCounter >= processor.getFem().nNod) {
// break;
// }
// for (double b : a) {
// System.out.print(b + " ");
// }
// System.out.println();
// nodeCounter++;
// }
writer.close();
logTextArea.append("\nTomó " + (System.nanoTime() - inicio)/1000000 + "ms");
logTextArea.append("\nArchivo generado ");
logTextArea.append(file.getAbsolutePath() + ".out\n");
LOGGER.info("Archivo procesado " + file.getParentFile().getAbsolutePath());
canvas.clearImage();
drawInitial(file.getAbsolutePath(), canvas, Element.xy, processor);
} else {
LOGGER.info("Open command cancelled by user.");
}
}
});
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.ipady = 400;
BufferedImage myPicture = ImageIO.read(new File("Logo.png"));
canvas = new FemCanvas();
canvas.setSize(400, 400);
panel.add(canvas, constraints);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.weightx = 1;
panel.add(loadFileButton, constraints);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 3;
constraints.ipady = 100;
panel.add(logTextAreaScroll, constraints);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.add(panel, BorderLayout.NORTH);
this.setSize(500, 600);
}
protected void drawInitial(String absolutePath, FemCanvas canvas2, double[][] xy, FemProcessor processor) {
File file = new File(absolutePath);
System.out.println("Nodes:");
int nodeCounter = 0;
System.out.println("nNod: " + processor.getFem().nNod);
for (int i = 0; i < processor.getFem().nNod; i++) {
if (nodeCounter >= processor.getFem().nNod) {
break;
}
for (int j = 0; j < processor.getFem().nDim; j++) {
System.out.print(processor.getFem().xyz[i*2+j] + " ");
}
canvas2.drawPoint((int)(processor.getFem().xyz[i*2]*100+5), (int)(processor.getFem().xyz[i*2+1]*100+5));
canvas2.drawPoint2((int)((processor.getFem().xyz[i*2]+FeLoad.sDispl[i*2])*100+5), (int)((processor.getFem().xyz[i*2+1]+FeLoad.sDispl[i*2+1])*100+5));
System.out.println();
nodeCounter++;
}
}
private void saveFileProperty(String folder) {
try {
properties.setProperty("file", folder);
FileOutputStream fos;
fos = new FileOutputStream(propertiesFile);
properties.store(fos, null);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package com.udacity.gradle.builditbigger.utils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.zsergei.joke.backend.myApi.MyApi;
import java.io.IOException;
/**
* Created by Sergei Zarochentsev on 26.03.2016.
*
*/
public class ApiBuilder {
private static final String URL = "http://10.0.2.2:8085/_ah/api/";
public static synchronized MyApi getApi() {
final MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
.setRootUrl(URL)
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(
final AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws
IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
return builder.build();
}
}
|
public class HorseChessProblem1 {
public static void main(String[] args) {
int a[][] = new int[8][8];
int i=3;
int j = 4;
a[3][4] = 1;
if (i - 2 >= 0 && j + 1 <a.length) {
a[i - 2][j + 1] = 2;
}System.out.println();
if(i-2>=0 && j-1>=0)
{
a[i-2][j-1]=2;
}
if(i-1>=0 && j-2>=0)
{
a[i-1][j-2]=2;
}
if(i+1<a.length && j-2>=0)
{
a[i+1][j-2]=2;
}
if(i+2<a.length && j-1>=0)
{
a[i+2][j-1]=2;
}
if(i+2<a.length && j+1<a.length)
{
a[i+2][j+1]=2;
}
if(i+1<a.length && j+2<a.length)
{
a[i+1][j+2]=2;
}
if(i-1>=0 && j+2<a.length)
{
a[i-1][j+2]=2;
}
for(int n =0;n<a.length;n++)
{
for(int m=0;m<a.length;m++)
{
System.out.print(" "+a[n][m]);
}
System.out.println();
}
}
}
|
package com.atguigu.edu.controller;
import com.atguigu.commonutils.R;
import com.atguigu.edu.entity.subject.OneSubject;
import com.atguigu.edu.service.EduSubjectService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 课程科目 前端控制器
* </p>
*
* @author testjava
* @since 2020-07-27
*/
@CrossOrigin
@RestController
@RequestMapping("/eduservice/subject")
public class EduSubjectController {
@Resource
EduSubjectService eduSubjectService;
@PostMapping("add")
public R addSubject(MultipartFile file){
eduSubjectService.addSubject(file,eduSubjectService);
return R.ok();
}
//课程分类列别
@GetMapping("getAllSubject")
public R getAllSubject(){
List<OneSubject> allSubject = eduSubjectService.getAllSubject();
return R.ok().data("allSubject",allSubject);
}
}
|
package com.example.geoquiz;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class Output extends AppCompatActivity {
private TextView mScore;
//total score show on the last page and button link to the first page
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_output);
final String getScore=getIntent().getExtras().getString("score");
mScore=findViewById(R.id.score_text_view);
mScore.setText(getScore);
Button mButton = (Button) findViewById(R.id.buttonback);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(Output.this, choose_quiz.class);
startActivity(myIntent);
finishAffinity();
}
});
}
}
|
package count_vowels;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
/*-*
Count Vowels –
Enter a string and the program counts the number of vowels in the text.
For added complexity have it report a sum of each vowel found.
*/
/**
*
* @author jingchen
*
*/
public class CountVowels {
public static String count(String str) {
if (str == null || str.trim().length() < 2) {
return "";
}
str = str.trim().toLowerCase();
int len = str.length();
HashMap<Character, Integer> vowel = new HashMap<Character, Integer>();
vowel.put('a', 0);
vowel.put('e', 0);
vowel.put('i', 0);
vowel.put('o', 0);
vowel.put('u', 0);
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (vowel.containsKey(c)) {
vowel.put(c, vowel.get(c) + 1);
}
}
StringBuilder sb = new StringBuilder();
Set<Entry<Character, Integer>> set = vowel.entrySet();
for (Entry<Character, Integer> entry : set) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
String str = "commit ai39532o61a6cb6e8caf16ub904f8724odce219af34cc8fa63";
System.out.println(count(str));
}
}
/*-----------------------------Output------
a: 5
e: 2
u: 1
i: 2
o: 3
*/ |
package com.soldevelo.vmi.scheduler.validation;
import com.soldevelo.vmi.config.acs.model.HostParams;
import com.soldevelo.vmi.enumerations.TestProtocol;
import com.soldevelo.vmi.packets.TestRequestPhase2;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
public class TestRequestValidatorTest {
private static final String DOWNLOAD_URL = "http://download.url";
private static final String UPLOAD_URL = "http://upload.url";
private static final String NDT_URL = "http://ndt.url";
private static final String WPR_URL = "http://google.com";
private static final String DNS_SERVER = "4.4.4.4";
@Mock
private TestRequestPhase2 testRequest;
@Mock
private HostParams hostParams;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(hostParams.isVerizonProtocolEnabled()).thenReturn(true);
}
@Test
public void shouldAcceptValidHttpRequest() {
when(testRequest.isHTTPRequest()).thenReturn(true);
when(testRequest.getDTR()).thenReturn(true);
when(testRequest.getUTR()).thenReturn(true);
when(hostParams.getDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(hostParams.getUploadUrl()).thenReturn(UPLOAD_URL);
assertTrue(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
when(testRequest.getDTR()).thenReturn(false);
when(hostParams.getDownloadUrl()).thenReturn("");
assertTrue(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
when(testRequest.getUTR()).thenReturn(false);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(hostParams.getUploadUrl()).thenReturn("");
assertTrue(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
}
@Test
public void shouldRejectInvalidHttpRequests() {
when(testRequest.isHTTPRequest()).thenReturn(true);
when(testRequest.getDTR()).thenReturn(false);
when(testRequest.getUTR()).thenReturn(true);
when(hostParams.getUploadUrl()).thenReturn(null);
assertFalse(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
when(testRequest.getUTR()).thenReturn(false);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getDownloadUrl()).thenReturn(null);
assertFalse(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
when(hostParams.getDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(testRequest.isHTTPRequest()).thenReturn(false);
assertFalse(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
when(testRequest.isHTTPRequest()).thenReturn(true);
when(testRequest.getDTR()).thenReturn(false);
assertFalse(TestRequestValidator.validateHttpRequest(testRequest, hostParams));
}
@Test
public void shouldAcceptValidFtpRequest() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.FTP);
when(testRequest.getDTR()).thenReturn(true);
when(testRequest.getUTR()).thenReturn(true);
when(hostParams.getFtpDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(hostParams.getFtpUploadUrl()).thenReturn(UPLOAD_URL);
assertTrue(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
when(testRequest.getDTR()).thenReturn(false);
when(hostParams.getFtpDownloadUrl()).thenReturn("");
assertTrue(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
when(testRequest.getUTR()).thenReturn(false);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getFtpDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(hostParams.getFtpUploadUrl()).thenReturn("");
assertTrue(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
}
@Test
public void shouldRejectInvalidFtpRequests() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.FTP);
when(testRequest.getDTR()).thenReturn(false);
when(testRequest.getUTR()).thenReturn(true);
when(hostParams.getFtpUploadUrl()).thenReturn(null);
assertFalse(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
when(testRequest.getUTR()).thenReturn(false);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getFtpDownloadUrl()).thenReturn(null);
assertFalse(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
when(hostParams.getFtpDownloadUrl()).thenReturn(DOWNLOAD_URL);
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.DNS);
assertFalse(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.FTP);
when(testRequest.getDTR()).thenReturn(false);
assertFalse(TestRequestValidator.validateFtpRequest(testRequest, hostParams));
}
@Test
public void shouldAcceptValidNdtRequests() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.NDT);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getNdtUrl()).thenReturn(NDT_URL);
assertTrue(TestRequestValidator.validateNdtRequest(testRequest, hostParams));
}
@Test
public void shouldRejectInvalidNdtRequest() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.NDT);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getNdtUrl()).thenReturn("");
assertFalse(TestRequestValidator.validateNdtRequest(testRequest, hostParams));
when(hostParams.getNdtUrl()).thenReturn(NDT_URL);
when(testRequest.getDTR()).thenReturn(false);
assertFalse(TestRequestValidator.validateNdtRequest(testRequest, hostParams));
when(testRequest.getDTR()).thenReturn(true);
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.DNS);
assertFalse(TestRequestValidator.validateNdtRequest(testRequest, hostParams));
}
@Test
public void shouldAcceptValidWprRequests() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.WPR);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getWebPageResponseUrl()).thenReturn(WPR_URL);
assertTrue(TestRequestValidator.validateWprRequest(testRequest, hostParams));
}
@Test
public void shouldRejectInvalidWprRequest() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.WPR);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getWebPageResponseUrl()).thenReturn("");
assertFalse(TestRequestValidator.validateWprRequest(testRequest, hostParams));
when(hostParams.getWebPageResponseUrl()).thenReturn(WPR_URL);
when(testRequest.getDTR()).thenReturn(false);
assertFalse(TestRequestValidator.validateWprRequest(testRequest, hostParams));
when(testRequest.getDTR()).thenReturn(true);
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.DNS);
assertFalse(TestRequestValidator.validateNdtRequest(testRequest, hostParams));
}
@Test
public void shouldAcceptValidDnsRequests() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.DNS);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getDnsHostname()).thenReturn(DNS_SERVER);
assertTrue(TestRequestValidator.validateDnsRequest(testRequest, hostParams));
}
@Test
public void shouldRejectInvalidDnsRequest() {
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.DNS);
when(testRequest.getDTR()).thenReturn(true);
when(hostParams.getDnsHostname()).thenReturn("");
assertFalse(TestRequestValidator.validateDnsRequest(testRequest, hostParams));
when(hostParams.getDnsHostname()).thenReturn(DNS_SERVER);
when(testRequest.getDTR()).thenReturn(false);
assertFalse(TestRequestValidator.validateDnsRequest(testRequest, hostParams));
when(testRequest.getDTR()).thenReturn(true);
when(testRequest.getTestProtocol()).thenReturn(TestProtocol.FTP);
assertFalse(TestRequestValidator.validateDnsRequest(testRequest, hostParams));
}
}
|
package org.example.DataStreams.service;
import java.util.Collections;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.example.DataStreams.domain.Event;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.Builder;
@Builder
public class RepeaterPauseHandler extends Handler<Event, Event> {
private static final Logger log = LoggerFactory.getLogger(RepeaterPauseHandler.class);
private Long timeOut;
public void run(Long time) {
}
void run() {
}
@Override
public KafkaProducer<String, Event> getProducer() {
return null;
}
@Override
public KafkaConsumer<String, Event> getConsumer() {
return null;
}
}
|
package Network_Module;
public class NetworkConstant {
//将本机服务端的ip地址,和port搭配启动Netty服务
public static String serverIp = "192.168.1.207";
//默认为8080.但是在Netty服务启动之后就会被改变为一个[9000-49152]之间的任意一个数值
public static int serverPort = 8088;
//最大数据节点数
public static final int MAX_IN_NODES = 10;
//最大数据节点数
public static final int MAX_OUT_NODES = 10;
//节点成功连接之后握手消息
public static final String HANDSHAKE_SUCCESS_MESSAGE = "0";
//节点成功连接之后握手失败消息
public static final String HANDSHAKE_FAIL__MESSAGE = "00";
//获取新节点消息
public static final String GET_NEW_CONNECTION_NODE_MESSAGE = "1";
//获取新节点失败消息
public static final String GET_NEW_CONNECTION_NODE_FAIL_MESSAGE = "10";
//获取新节点成功消息
public static final String GET_NEW_CONNECTION_NODE_SUCCESS_MESSAGE = "11";
//获取区块高度的消息
public static final String GET_BLOCK_HEIGHT_MESSAGE = "2";
//返回区块高度的消息
public static final String GET_BLOCK_HEIGHT_MESSAGE_SUCCESS = "20";
//获取一个指定的区块消息
public static final String GET_BLOCK_MESSAGE = "3";
//prepare消息,用于区块共识验证
public static final String CONSENSUS_PREPARE_MESSAGE = "40";
//commited消息,用于区块共识验证
public static final String CONSENSUS_COMMITED_MESSAGE = "41";
//共识节点消息
public static final String CONSENSUS_NODE_MESSAGE = "5";
}
|
package com.git.cloud.common.exception;
public class RollbackableBizException extends BizException{
/**
* 异常版本号
*/
private static final long serialVersionUID = 1L;
/**
* 一般的异常构造,由于不包含异常代码,不建议使用
*/
public RollbackableBizException() {
super();
}
public RollbackableBizException(String message) {
super(message);
}
/**
* @param message
* @param cause
*/
public RollbackableBizException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
* @param cause
*/
public RollbackableBizException(SysMessage msg, String message,Throwable cause) {
super(msg,message, cause);
}
/**
* @param msg
*/
public RollbackableBizException(SysMessage msg) {
super(msg);
}
/**
* @param msg
* @param cause
*/
public RollbackableBizException(SysMessage msg, Throwable cause) {
super(msg, cause);
}
/**
* @param cause
*/
public RollbackableBizException(Throwable cause) {
super(cause);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.service;
import com.innovaciones.reporte.dao.DetalleReporteInstalacionNuevaDAO;
import com.innovaciones.reporte.model.DetalleReporteInstalacionNueva;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author pisama
*/
@Service
@ManagedBean(name = "detalleReporteInstalacionNuevaDAOService")
@ViewScoped
public class DetalleReporteInstalacionNuevaServiceImpl implements DetalleReporteInstalacionNuevaService, Serializable {
@Setter
private DetalleReporteInstalacionNuevaDAO detalleReporteInstalacionNuevaDAO;
@Override
@Transactional
public DetalleReporteInstalacionNueva addDetalleReporteInstalacionNueva(DetalleReporteInstalacionNueva detalleReporteInstalacionNueva) {
return detalleReporteInstalacionNuevaDAO.addDetalleReporteInstalacionNueva(detalleReporteInstalacionNueva);
}
@Override
@Transactional
public DetalleReporteInstalacionNueva update(DetalleReporteInstalacionNueva detalleReporteInstalacionNueva) {
return detalleReporteInstalacionNuevaDAO.update(detalleReporteInstalacionNueva);
}
}
|
package com.outfitterandroid;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
/**
* Created by MaguireM on 4/22/15.
*
* This class involves functionality for commenting. Has a comments adapter for the customized
* comment item view. Also has a comparator by which to sort the comments. By defualt it sorts
* most upvotes to least upvotes and then least recent to most recent.
*
*/
public class CommentsActivity extends Activity{
public static final String EXTRA_SUBMISSION_ID = "com.outfitterandroid.submissionId";
private static final String TAG = "CommentsActivity";
final String COMMENT_EMPTY = "comment text is empty";
final String COMMENT_NAUGHTY = "that is a naughty word";
String mSubmissionId;
List<ParseObject> mComments;
ListView mCommentsListView;
EditText mCommentEditText;
Button mAddCommentButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comments);
mSubmissionId = getIntent().getStringExtra(EXTRA_SUBMISSION_ID);
mCommentsListView = (ListView) findViewById(R.id.comments_list_view);
mCommentEditText = (EditText) findViewById(R.id.comment_edit_text);
mAddCommentButton = (Button) findViewById(R.id.add_comment_button);
mComments = getComments();
mComments = sortComments(mComments);
mCommentsListView.setAdapter(new CommentsAdapter(mSubmissionId, mComments));
mAddCommentButton.setOnClickListener(addComment());
}
/**
* private function return
* @return a list of parse objects representing the comments associated with
* the current submission
*/
private List<ParseObject> getComments() {
List<ParseObject> comments = null;
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
query.whereEqualTo("submissionId", mSubmissionId);
comments = query.find();
for(ParseObject comment : comments){
comment.put("numUpvotes", getNumUpvotes(comment.getObjectId())) ;
}
}
catch(ParseException e){
Log.d(TAG, "bad comment save");
}
return comments;
}
/**
* @param comments list of comments to be sorted
* @return comments sorted first by number of upvotes then in chronological order from
* least recent to most
*/
private List<ParseObject> sortComments(List<ParseObject> comments) {
if (null != comments) Collections.sort(comments, new CommentComparator());
return comments;
}
private View.OnClickListener addComment() {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
String commentText = mCommentEditText.getText().toString();
if (commentText.isEmpty()) {
Toast.makeText(CommentsActivity.this, COMMENT_EMPTY, Toast.LENGTH_SHORT).show();
}
else if (isNaughty(commentText)){
Toast.makeText(CommentsActivity.this, COMMENT_NAUGHTY, Toast.LENGTH_SHORT).show();
}
else{
mCommentEditText.setText("");
hideKeyboard();
ParseObject comment = new ParseObject("Comment");
comment.put("comment", commentText);
//comment.put("numUpvotes", 0);
comment.put("submissionId", mSubmissionId);
comment.put("userId", ParseUser.getCurrentUser().getObjectId());
try {
comment.save();
comment.put("numUpvotes", 0);
mComments.add(comment);
CommentsAdapter ca = (CommentsAdapter) mCommentsListView.getAdapter();
ca.notifyDataSetChanged();
}
catch(ParseException e){
Log.d(TAG, "bad comment save");
}
}
}
};
}
/**
* @param commentText text to be analyze
* @return true if comment text contains word from prohibited list
*/
private boolean isNaughty(String commentText) {
if (commentText.contains("fuck") ||
commentText.contains("suck") ||
commentText.contains("shit") ||
commentText.contains("dick") ||
commentText.contains("cock") ||
commentText.contains("gay") ||
commentText.contains("fag")){
return true;
}
else return false;
}
/**
* hides on screen keyboard
*/
private void hideKeyboard() {
View focusedView = CommentsActivity.this.getCurrentFocus();
if (null != focusedView){
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(focusedView.getWindowToken(), 0);
}
}
private int getNumUpvotes(String commentId) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("CommentActivity");
query.whereEqualTo("commentId", commentId);
try {
int numUpvotes = query.find().size();
Log.d(TAG, String.format("commentId : %s\tnumUpvotes : %d", commentId, numUpvotes));
return numUpvotes;
}
catch (ParseException e){
Log.d(TAG, "bad commentId");
return 0;
}
}
public class CommentsAdapter extends BaseAdapter {
private static final String TAG = "CommentsAdapter";
String mSubmissionId;
ParseObject mSubmission;
List<ParseObject> mComments;
public CommentsAdapter(String submissionId, List<ParseObject> comments) {
mSubmissionId = submissionId;
try{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Submission");
query.whereEqualTo("submissionId", mSubmissionId);
mSubmission = query.getFirst();
}
catch (ParseException e){
Log.d(TAG, String.format("bad submissionId %s", submissionId));
}
mComments = comments;
}
@Override
public int getCount() {
return mComments.size();
}
@Override
public Object getItem(int position) {
if (null == mComments) {
return null;
}
else{
return mComments.get(position);
}
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (null == convertView){
convertView = getLayoutInflater().inflate(R.layout.comment_element, null);
}
Button deleteCommentButton = (Button) convertView.findViewById(R.id.delete_comment_button);
//collect data
final ParseObject comment = (ParseObject) getItem(position);
String commentId = comment.getObjectId();
String commentText = comment.getString("comment");
String numUpvotes = Integer.toString(comment.getInt("numUpvotes"));
String userId, username;
userId = username = comment.getString("userId");
SimpleDateFormat dt = new SimpleDateFormat("hh:mm MM-dd-yyyy");
String createdAt = dt.format(comment.getCreatedAt());
try {
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
username = query.get(userId).getString("username");
}
catch (ParseException e){
Log.d(TAG, String.format("bad user objectId %s", userId));
}
//fill views
TextView numUpvotesTextView = (TextView) convertView.findViewById(R.id.num_upvotes_text_view);
TextView commenterCommentTextView = (TextView) convertView.findViewById(R.id.commenter_comment_text_view);
TextView commenterUsernameTextView = (TextView) convertView.findViewById(R.id.commenter_username_text_view);
TextView commenterCommentCreatedAtTextView = (TextView) convertView.findViewById(R.id.commenter_created_at_text_view);
LinearLayout upvoteLinearLayout = (LinearLayout) convertView.findViewById(R.id.upvote_linear_layout);
numUpvotesTextView.setText(numUpvotes);
commenterCommentTextView.setText(commentText);
commenterUsernameTextView.setText(username);
commenterCommentCreatedAtTextView.setText(createdAt);
upvoteLinearLayout.setOnClickListener(trySubmitCommentUpvote(comment));
//don't show delete button if user not authorized to delete
if (isAuthorizedToDelete(comment)){
deleteCommentButton.setOnClickListener(tryDeleteComment(position, comment));
}
else{
deleteCommentButton.setVisibility(View.INVISIBLE);
}
convertView.setClickable(false);
return convertView;
}
private View.OnClickListener tryDeleteComment(final int position, final ParseObject comment) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
comment.delete();
mComments.remove(position);
notifyDataSetChanged();
}
catch (ParseException e){
Log.d(TAG, "could not delete comment");
}
}
};
}
private boolean isAuthorizedToDelete(ParseObject comment) {
ParseUser curUser = ParseUser.getCurrentUser();
if (comment.getString("userId").equals(curUser.getObjectId())||
mSubmission.getString("submittedByUser").equals(curUser.getObjectId())||
mSubmission.getString("submittedByUser").equals(curUser.getString("name"))) {
return true;
}
return false;
}
private View.OnClickListener trySubmitCommentUpvote(final ParseObject comment) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "upvote clicked");
String commentId = comment.getObjectId();
String userId = ParseUser.getCurrentUser().getObjectId();
if (hasNotVoted(userId, commentId)) {
ParseObject upvote = new ParseObject("CommentActivity");
upvote.put("commentId", commentId);
upvote.put("userId", userId);
try {
upvote.save();
Log.d(TAG, "upvote saved");
comment.put("numUpvotes", comment.getInt("numUpvotes") + 1);
notifyDataSetChanged();
} catch (ParseException e) {
Log.d(TAG, "upvote not submitted");
}
}
}
};
}
/**
*
* @param userId
* @param commentId
* @return returns true if user has not submitted an upvote for the comment
* he or she is attempting to upvote
*/
private boolean hasNotVoted(String userId, String commentId) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("CommentActivity");
query.whereEqualTo("commentId", commentId);
query.whereEqualTo("userId", userId);
try {
int voteCount = query.find().size();
Log.d(TAG, String.format("in has not voted commentId : %s\tuserId : %s\tvoteCount : %d", commentId, userId, voteCount));
return voteCount == 0 ? true : false;
}
catch (ParseException e){
Log.d(TAG, "bad commentId or userId ");
return false;
}
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
Collections.sort(mComments, new CommentComparator());
}
}
public class CommentComparator implements Comparator{
@Override
public int compare(Object lhs, Object rhs) {
ParseObject lhsComment = (ParseObject) lhs;
ParseObject rhsComment = (ParseObject) rhs;
int lhsUpvotes = lhsComment.getInt("numUpvotes");
int rhsUpvotes = rhsComment.getInt("numUpvotes");
Date lhsCreatedAt = lhsComment.getCreatedAt();
Date rhsCreatedAt = rhsComment.getCreatedAt();
if( lhsUpvotes != rhsUpvotes){
return rhsUpvotes - lhsUpvotes;
}
else{
return lhsCreatedAt.after(rhsCreatedAt) ? 1 : -1;
}
}
}
}
|
package com.cg.go.greatoutdoor.dto.salesReport;
public class CreateSalesReportRequest {
private String productId;
private String productName;
private Integer quantitySold;
private double totalSale;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Integer getQuantitySold() {
return quantitySold;
}
public void setQuantitySold(Integer quantitySold) {
this.quantitySold = quantitySold;
}
public double getTotalSale() {
return totalSale;
}
public void setTotalSale(double totalSale) {
this.totalSale = totalSale;
}
}
|
package dk.webbies.tscreate.paser.AST;
import com.google.javascript.jscomp.parsing.parser.util.SourceRange;
import dk.webbies.tscreate.paser.ExpressionVisitor;
import java.util.Arrays;
/**
* Created by erik1 on 23-05-2016.
*/
public class RegExpExpression extends Expression {
private final String value;
public RegExpExpression(SourceRange loc, String value) {
super(loc);
this.value = value;
}
public String getValue() {
return value;
}
@Override
public <T> T accept(ExpressionVisitor<T> visitor) {
return visitor.visit(this);
}
}
|
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class BankAccountTests {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test_initial_account_balance_is_zero() {
Account account = new Account(new Money(0));
Money money = account.getBalance();
assertThat(new Money(0), is(equalTo(money)));
}
@Test
public void test_deposit()
{
Account account = new Account(new Money(0));
Money deposit = new Money(50);
account.Deposit(deposit);
assertThat(new Money(50), is(equalTo(account.getBalance())));
}
@Test
public void test_withdrawal()
{
Account account = new Account(new Money(0));
Money withdrawal = new Money(30);
account.Withdraw(withdrawal);
assertThat(new Money(-30), is(equalTo(account.getBalance())));
}
@Test
public void test_transfer()
{
Account source = new Account(new Money(50));
Account destination = new Account(new Money(0));
TransactionOps.Transfer(source, destination, new Money(30));
assertThat(new Money(30), is(equalTo(destination.getBalance())));
assertThat(new Money(20), is(equalTo(source.getBalance())));
}
} |
package com.ifeng.recom.mixrecall.common.constant;
import com.ifeng.recom.mixrecall.common.util.IPUtil;
/**
* Created by jibin on 2017/12/26.
*/
public class GyConstant {
/**
* 本机ip,用作系统缓存分片使用
*/
public final static String linuxLocalIp = IPUtil.getLinuxLocalIp();
/**
* 头条实时调用的流量,设置超时时间为300ms
*/
public static final int timeout_Toutiao_Online = 150;
/**
* 头条实时调用的流量,设置超时时间为150ms
*/
public static final int timeout_Toutiao_First = 150;
/**
* 画像超时时间,设置超时时间为1200ms
*/
public static final int timeout_UserModel_long = 1200;
/**
* 获取usercf的超时控制
*/
public static final int timeout_UserCF = 500;
/**
* 获取实时画像信息的超时控制
*/
public static final int timeout_UserModel_last = 800;
public static final int timeout_Toutiao_Online_cotag = 200;
/**
* 兴趣试探超时时间,设置超时时间为100ms
*/
public static final int timeout_explore_long = 100;
/**
* 正反馈调用超时
*/
public static final int timeout_positiveFeed = 500;
/**
* 符号 空格
*/
public static final String Symb_blank = " ";
/**
* 符号 es使用的分隔符
*/
public static final String Symb_es_split = "\\^";
public static final String Symb_brackets_left = "(";
public static final String Symb_brackets_right = ")";
/**
* 符号 冒号
*/
public static final String Symb_Colon = ":";
/**
* 符号 小于号
*/
public static final String Symb_Less = "<";
/**
* 符号 大于号
*/
public static final String Symb_Greater = ">";
/**
* 符号 逗号
*/
public static final String Symb_Comma = ",";
/**
* 符号 分号
*/
public static final String Symb_Semicolon = ";";
/**
* 符号 井号
*/
public static final String Symb_Pound = "#";
/**
* 符号 等号
*/
public static final String Symb_equal = "=";
/**
* 符号 下划线
*/
public static final String Symb_Underline = "_";
/**
* 左 花括号
*/
public static final String Symb_openBrace = "{";
/**
* 右 花括号
*/
public static final String Symb_closeBrace = "}";
/**
* 正反馈强插的上限设置 20条
*/
public static final int itemcf_limit = 20;
/**
* guid的长度 32位 md5值
*/
public static final int GUID_Length = 32;
/**
* 解析topic用来查询,设置对应的限制上限,避免超时
*/
public static final int topicQueryLimit = 5;
/**
* solr查询时效过滤
*/
public static final String quer_solr_available = " AND (available:true)";
public static final String quer_solr_or = " OR ";
public static final String quer_solr_key_topic1 = "topic1:";
public static final String quer_solr_key_topic3 = "topic3:";
public static final String quer_solr_key_date = "date";
public static final String quer_solr_key_doctype = "doctype:";
public static final String quer_solr_key_itemid="itemid";
public static final String quer_solr_key_simID="simID";
public static final String quer_solr_and = " AND ";
public static final int quer_solr_limit = 5;
/**
* 增量结果条数
*/
public static final int ResultSize_IncreasedateMerge = 700;
/**
* 头条实时调用的流量,设置超时时间为300ms
*/
public static final int num_Sub = 70;
/**
* 订阅频道出150条 订阅
*/
public static final int num_Sub_Momentsnew = 300;
/**
* 每个帖子的召回量
*/
public static final int eacheNum_Sub_Momentsnew = 15;
/**
* 其他频道cotags,S级媒体默认出50条
*/
public static final int cotags_Total_Default = 50;
/**
* 头条频道S级媒体默认出500条
*/
public static final int cotags_Total_Headline = 500;
/**
* 正反馈强插的标记,透传给头条标记,使用简写
*/
public final static String strategyPositiveFeed = "posi"; //正反馈强插的前缀source
/**
* 处理ctr默认值,使用hotBoost*阈值进行补全
*/
public static final double CTRQ_hotBoost_threshold = 0.01;
/**
* HotBoostCtr格式,保留5位小数
*/
public static final String HotBoostCtr_Format="%.5f";
/**
* 处理类型转换失败的情况,设置默认值-1
*/
public static final long timeSensitive_null = -1;
/**
* 长效标记
*/
public static final String timeSensitive_nt = "nt";
public static final String dateTimeSensitive_nt = "2300-1-1 23:59:00";
public static final boolean isNewResult = true;
public static final boolean isOldResult = false;
public static final String uid_Jibin = "867305035296545";
public static final String uid_pd = "865969031431182";
public static final String uid_madi = "867463030265112";
public static final String OK = "OK";
/**
* 设置simIdMapping 过期时间,一天
*/
public static final int ttl_SimIdMapping = 3600 * 24;
/**
* 趣头条抓取过滤规则
*/
public static final String needQttFilter = "needQttFilter";
/**
* 小视频过滤规则
*/
public static final String needMinVideoFilter = "needMinVideoFilter";
public static final String isBeiJingUserNotWxb = "isBeiJingUserNotWxb";
public static final String isColdNotBj = "isColdNotBj";
/**
* 小视频的标记
*/
public static final String miniVideo = "miniVideo";
/**
* 世界杯标记
*/
public static final String worldCup = "worldCup";
/**
* 趣头条抓取 标记
*/
public static final String qutt = "qutt";
/**
* 负反馈使用的 来源
*/
public static final String UserNegs_Src = "src";
/**
* 最多渠道标签数
*/
public static final int sourceTagNum = 15;
/**
* debugType: userModel
*/
public static final String debugType_userModel = "userModel";
public static final String bossUsers= "65357bb574334ad683d459ee20eb119e|829584937ae04994b028008a3bdbab75|27d7344be6c44fc880db8ec6de6fc7a5|5e192a33f6804f5592c98f5d6f2809de|debug237|debugmadi3|869456039950054";
/**
* debugType: userCF
*/
public static final String debugType_userCf = "userCF";
/**
* debugType: userCFDetail
*/
public static final String debugType_userCf_detail = "userCFDetail";
/**
* doc持久化的最大文件数
*/
public static final int doc_txt_Num = 5;
/**
* 本机缓存的目录
*/
public static final String localCacheDir = "/data/prod/service/mix-recall/cache_dump/";
public static final String personalcacheOfpath = localCacheDir + "DocPreloadCache.txt";
/**
* cotag小于50条则认为cotag不足
*/
public static final int cotagLongNotEnough = 50;
/**
* docpic prefix
*/
public static final String docpic_prefix = "d-";
/**
* video prefix
*/
public static final String video_prefix = "v-";
/**
* video jx_suffix
*/
public static final String jx_suffix = "_jx";
/**
* cate prefix
*/
public static final String cate_prefix = "c-";
/**
* subcate prefix
*/
public static final String subcate_prefix = "sc-";
/**
* docpic 后缀
*/
public static final String d_suffix = "_d";
/**
* video 后缀
*/
public static final String v_suffix = "_v";
public static final String key_Source = "source=";
//ffm调用url
public static final String FFM_URL = "http://local.recom.ifeng.com/recall/ffm/user";
public static final String FFM_URL_V = "http://local.recom.ifeng.com/recall/ffmv/user";
}
|
package com.snapup.service;
import com.snapup.pojo.SeatTicket;
import java.util.List;
public interface TicketService {
double EARTH_RADIUS = 6378.137; //地球半径(单位:千米)
//真正的初始化:
public int initial(int run_serial);
//创建座位价格信息:
public void createTicket(int run_serial, String depart_station_code,
String arrival_station_code);
//票量加一:
public int addTicket(int run_serial, String depart_station_code,
String arrival_station_code, char seat_type);
//票量减一:
public int subTicket(int run_serial, String depart_station_code,
String arrival_station_code, char seat_type);
//购票:
public int buyTicket(int run_serial, String depart_station_code,
String arrival_station_code, char seat_type);
//退票:
public int returnTicket(int run_serial, String depart_station_code,
String arrival_station_code, char seat_type);
//根据列车流水,出发站和目标站查询座位类型,座位价格,余票
public List<SeatTicket> findSeatTicket(int run_serial, String depart_station_code, String arrival_station_code);
//计算票价:
public float tickets_price_produce(char train_type, char seat_type,float latitude_x,
float longitude_x, float latitude_y, float longitude_y,
int remain);
//距离计算函数
public double from_loc_cal_distance(float latitude_x, float longitude_x,
float latitude_y, float longitude_y);
//弧度计算函数
public double rad(double d);
}
|
package com.study.yf.grpc.Server;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import learn_grpc.LearnGrpc;
import learn_grpc.ServiceGrpc;
import java.io.IOException;
/**
* @author: YangFei
* @description:
* @create:2020-12-02 15:33
*/
public class ServiceServer {
private final Server server;
private final int port;
//初始化server,指定端口号和服务
public ServiceServer(int port) {
this.port = port;
server = ServerBuilder.forPort(port).addService(new Service()).build();
}
public void start() throws IOException, InterruptedException {
server.start();
System.out.println("server started");
blockUntilShutdown();
}
public void stop() {
server.shutdown();
System.out.println("server stopped");
}
//服务器启动后进入等待状态
public void blockUntilShutdown() throws InterruptedException {
System.out.println("server blocked");
server.awaitTermination();
}
//定义服务,实现方法
static class Service extends ServiceGrpc.ServiceImplBase {
//单个消息-单个消息
@Override
public void sayHello(LearnGrpc.SayHelloRequest request, StreamObserver<LearnGrpc.SayHelloReply> responseObserver) {
String name = request.getName();
//onNext方法里填写要返回的消息
LearnGrpc.SayHelloReply build = LearnGrpc.SayHelloReply.newBuilder().setReply("Welcome, " + name + "!").build();
responseObserver.onNext(build);
responseObserver.onCompleted();
}
//单个消息-消息流
@Override
public void getServerPeopleList(LearnGrpc.GetServerPeopleListRequest request, StreamObserver<LearnGrpc.GetServerPeopleListReply> responseObserver) {
//多次执行onNext方法,返回消息流
LearnGrpc.GetServerPeopleListReply build_1 = LearnGrpc.GetServerPeopleListReply.newBuilder().setName("彭于晏").build();
LearnGrpc.GetServerPeopleListReply build_2 = LearnGrpc.GetServerPeopleListReply.newBuilder().setName("张震").build();
LearnGrpc.GetServerPeopleListReply build_3 = LearnGrpc.GetServerPeopleListReply.newBuilder().setName("靳东").build();
responseObserver.onNext(build_1);
responseObserver.onNext(build_2);
responseObserver.onNext(build_3);
responseObserver.onCompleted();
}
//消息流-单个消息
@Override
public StreamObserver<LearnGrpc.CountClientPeopleRequest> countClientPeople(final StreamObserver<LearnGrpc.CountClientPeopleReply> responseObserver) {
//初始化请求流
return new StreamObserver<LearnGrpc.CountClientPeopleRequest>() {
int count = 0;
//编写对请求流中每个请求的操作
public void onNext(LearnGrpc.CountClientPeopleRequest countClientPeopleRequest) {
count++;
}
public void onError(Throwable throwable) {
}
//请求流发送完成
public void onCompleted() {
//onNext方法里填写要返回的消息
LearnGrpc.CountClientPeopleReply build = LearnGrpc.CountClientPeopleReply.newBuilder().setCount(count).build();
responseObserver.onNext(build);
responseObserver.onCompleted();
}
};
}
//消息流-消息流
@Override
public StreamObserver<LearnGrpc.ChatContent>
chat(final StreamObserver<LearnGrpc.ChatContent> responseObserver) {
return new StreamObserver<LearnGrpc.ChatContent>() {
//每接受一个请求就返回一个响应
public void onNext(LearnGrpc.ChatContent chatContent) {
System.out.println(chatContent.getContent());
responseObserver.onNext(LearnGrpc.ChatContent.newBuilder().setContent("Hi, I'm server!").build());
}
public void onError(Throwable throwable) {
}
public void onCompleted() {
responseObserver.onCompleted();
}
};
}
}
public static void main(String[] args) throws IOException, InterruptedException {
ServiceServer serviceServer = new ServiceServer(5050);
serviceServer.start();
}
} |
package com.t11e.discovery.datatool;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.userdetails.memory.InMemoryDaoImpl;
public class ExampleConfigurationTest
{
private ConfigurationManager configurationManager;
private List<File> configFiles;
@Before
@SuppressWarnings("unchecked")
public void setup()
{
configFiles = new ArrayList<File>(
FileUtils.listFiles(new File("stage/examples"),
FileFilterUtils.suffixFileFilter(".xml"),
FileFilterUtils.prefixFileFilter("v")));
Assert.assertFalse(configFiles.isEmpty());
}
@Test
public void testConfigOnBoot()
{
for (final File configFile : configFiles)
{
testConfigOnBoot(configFile);
}
}
@Test
public void testConfigSwapBoot()
throws IOException
{
{
final File configFile = File.createTempFile("exampleConfigTest", ".xml");
FileUtils.copyFile(configFiles.get(configFiles.size() - 1), configFile);
testConfigOnBoot(configFile);
}
for (final File configFile : configFiles)
{
testConfigSwap(configFile, false);
}
for (final File configFile : configFiles)
{
testConfigSwap(configFile, true);
}
}
public void testConfigOnBoot(final File configFile)
{
configurationManager = new ConfigurationManager();
configurationManager.setWorkingDirectory("stage");
configurationManager.setConfigurationFile(configFile.getPath());
configurationManager.setBypassAuthenticationFilter(new BypassAuthenticationFilter());
configurationManager.setInMemoryDaoImpl(new InMemoryDaoImpl());
configurationManager.onPostConstruct();
Assert.assertNotNull(configurationManager.getBean(ChangesetPublisherManager.class));
}
private void testConfigSwap(final File configFile, final boolean persist)
throws FileNotFoundException
{
final boolean persisted =
configurationManager.loadConfiguration(new FileInputStream(configFile), persist);
if (persist)
{
Assert.assertTrue("Configuration was not saved", persisted);
}
else
{
Assert.assertFalse("Configuration should not have been saved", persisted);
}
}
}
|
package Termin9;
public class Addierer {
public static void main(String[] args) {
int[] zahl1 = {3, 4, 2};
int[] zahl2 = {6, 2, 9};
int[] erg = addiere(zahl1, zahl2);
for (int d : erg) {
System.out.print(d); //Gebe die Zahl aus
}
System.out.println();
}
public static int [] addiere(int[] zahl1, int[] zahl2) {
int tmp[] = new int[zahl1.length + 1];
int overflow = 0;
int value;
for (int i = zahl1.length - 1; i >= 0; i--) {
value = (zahl1[i] + zahl2[i] + overflow) % 10; //Addiere die Werte
overflow = (zahl1[i] + zahl2[i] + overflow) / 10; //Setze möglichen overflow
tmp[i + 1] = value;
}
tmp[0] = overflow; //füge dem MSB den overflow hinzu (der kann natürlich 0 sein)
int leadingZeroCount = 0;
for (int i = 0; i < tmp.length; i++) { //ermittle die Anzahl der führenden Nullen
if (tmp[i] == 0) leadingZeroCount++;
else break;
}
if (leadingZeroCount == 0) { //Wenn es keine führenden Nullen gibt, gebe tmp als ergebnis zurück
return tmp;
} else { //Es gibt führende Nullen
int[] result = new int[tmp.length - leadingZeroCount]; //Erzeuge neuen Array der um die Anzahl der führenden Nullen reduziert ist
for (int i = leadingZeroCount; i < tmp.length; i++) { //Fange ab der ersten Ziffer mit dem iterieren an
result[i - leadingZeroCount] = tmp[i]; //und fülle das Ergebnis Array
}
return result;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mx.appsw.frontend.ui;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import lombok.Data;
import mx.appsw.frontend.helper.UsuarioHelper;
/**
*
* @author kitto
*/
@Data
@Named
@SessionScoped
public class UsuarioUI implements Serializable {
private UsuarioHelper helper;
@PostConstruct
public void init() {
helper=new UsuarioHelper();
}
public static void main(String[] args) {
UsuarioUI ui=new UsuarioUI();
System.out.println(""+ui.helper.getUsuarioList().size());
}
}
|
package ru.innopolis.common;
/**
* CurruncyConventer.
*
* @author lifeandfree
*/
public interface CurrencyConverter {
double convert(double sum);
Money convertMoney(Money money);
}
|
package bupt.hpcn.onlinestandard.controller;
import bupt.hpcn.onlinestandard.domain.CityDO;
import bupt.hpcn.onlinestandard.domain.ProvinceDO;
import bupt.hpcn.onlinestandard.service.LocationService;
import com.alibaba.fastjson.JSONObject;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.swing.*;
import java.util.LinkedList;
import java.util.List;
@RestController
@RequestMapping("/api/location")
public class LocationController {
@Autowired
private LocationService locationService;
@GetMapping("/getLoc")
public Object getProv() throws Exception{
List<ProvinceDO> provList = locationService.getProvince();
List<CityDO> cityList = locationService.getCity();
List<JSONObject> resultprov = new LinkedList<>();
List<JSONObject> resultcity = new LinkedList<>();
for(ProvinceDO myprov : provList){
JSONObject temp = new JSONObject();
temp.put("label",myprov.getName());
temp.put("value",myprov.getName());
temp.put("id",myprov.getId());
resultprov.add(temp);
}
for(CityDO mycity : cityList){
JSONObject temp = new JSONObject();
temp.put("label",mycity.getName());
temp.put("id",mycity.getId());
for(ProvinceDO myprov : provList){
if(mycity.getProv_id() == myprov.getId()){
temp.put("prov",myprov.getName());
break;
}
}
resultcity.add(temp);
}
JSONObject resultobj = new JSONObject();
resultobj.put("provs", resultprov);
resultobj.put("allCities", resultcity);
resultobj.put("code",0);
return resultobj;
}
}
|
package common.solr;
import java.util.ArrayList;
public class ResultList<T> extends ArrayList<T> {
private long start = 0;
private long total = 0;
public ResultList() {
}
public ResultList(long total) {
this.setTotal(total);
}
public ResultList(long total, long start) {
this.setTotal(total);
this.setStart(start);
}
public long getStart() {
return start;
}
public long getTotal() {
if(total == 0)
total = size();
return total;
}
public void setTotal(long total) {
this.total = total;
}
public void setStart(long start) {
this.start = start;
}
}
|
package top.piao888.thrift;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFastFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import top.piao888.message.thrift.message.MessageService;
import javax.annotation.PostConstruct;
@Configuration
public class ThriftServer {
@Value("${server.port}")
private int port;
@Autowired
private MessageService.Iface message;
@PostConstruct
public void starThriftServer() throws TTransportException {
//将服务注册到thrift容器当中
TProcessor processor=new MessageService.Processor<>(message);
//创捷socket nio模式
TNonblockingServerSocket tNonblockingServerSocket=new TNonblockingServerSocket(port);
TNonblockingServer.Args args=new TNonblockingServer.Args(tNonblockingServerSocket);
//将 thrift 丢进socket中
args.processor(processor);
//设置传输方式 设置为真传输
args.transportFactory(new TFastFramedTransport.Factory());
// 传输格式 有二进制 有json 这个是二进制
args.protocolFactory(new TBinaryProtocol.Factory());
TServer server=new TNonblockingServer(args);
server.serve();
}
}
|
package com.example.kkopite.zhihudemo.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by forever 18 kkopite on 2016/7/1 21:01.
*/
public class DBHelper extends SQLiteOpenHelper {
public static final String TABLE_NAME = "daily_news_lists";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATE = "date";
public static final String COLUMN_CONTENT = "content";
public static final String TABLE_FAV = "daily_news_fav";
public static final String COLUMN_NEWS_ID = "news_id";
public static final String COLUMN_NEWS_TITLE = "news_title";
public static final String COLUMN_NEWS_IMAGE = "news_image";
public static final String DATABASE_NAME = "daily_news.db";
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE
= "CREATE TABLE " + TABLE_NAME
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_DATE + " CHAR(8) UNIQUE, "
+ COLUMN_CONTENT + " TEXT NOT NULL);";
public static final String DATABASE_CREATE_FAV
= "CREATE TABLE " + TABLE_FAV
+ "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NEWS_ID + " INTEGER UNIQUE, "
+ COLUMN_NEWS_TITLE + " TEXT, "
+ COLUMN_NEWS_IMAGE + " TEXT);";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE_FAV);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
|
package app.servlets;
import app.service.UserService;
import app.service.UserServiceImp;
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 java.io.IOException;
@WebServlet("/error")
public class ErrorServlet extends HttpServlet {
private UserService userService = UserServiceImp.getInstance();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("usersList", userService.getAllUsers());
resp.setStatus(HttpServletResponse.SC_OK);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("views/admin.jsp");
requestDispatcher.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
|
package com.lesports.airjordanplayer.utils;
/**
* Created by litzuhsien on 8/19/15.
*/
public class ExceptionUtils {
public static Throwable findRootCause(Throwable throwable) {
if (throwable == null) return null;
Throwable cause = throwable;
while (cause.getCause() != null) {
cause = cause.getCause();
}
return cause;
}
public static String getRootCauseMessage(Throwable throwable) {
Throwable rootCause = findRootCause(throwable);
if (rootCause != null) {
return rootCause.getMessage();
} else {
return "";
}
}
private ExceptionUtils() {}
}
|
package ch.mitti.geometrische_figuren;
import java.awt.geom.*; //Alle Klassen des Geometrie-Pakets
public class Ellipse extends Figur {
// Attribute
private int radius1;
private int radius2;
// Konstruktor
public Ellipse() {
super(50,50,"magenta");
this.radius1=15;
this.radius2=40;
this.draw();
}
public Ellipse(int xPosition, int yPosition, int radius1, int radius2, String color) {
super(xPosition, yPosition, color);
this.radius1=radius1;
this.radius2=radius2;
this.draw();
}
// Dienste
public void draw(){ //mit private und public ausprobieren
Canvas canvas = Canvas.getCanvas();
canvas.draw(this, super.getColor(), "Ellipse", new Ellipse2D.Double(super.getxPosition(), super.getyPosition(), radius1, radius2));
}
}
|
package algorithms.search.symboltable.client;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import algorithms.search.ST;
import algorithms.utils.TimeWatch;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
@Getter
@Setter
public class FrequencyCounter {
private Logger logger = LoggerFactory.getLogger(FrequencyCounter.class);
public static final String WORD_SEPARATOR = "\\s";
public static final String TAG_COUNT_WORDS = "TAG_COUNT_WORDS";
public static final String TAG_FIND_MAX = "TAG_FIND_MAX";
public static final String TAG_OTHER = "TAG_OTHER";
private ST<String, Integer> st;
private TimeWatch timeWatch;
public void count(String fileClassPath, int minLength) {
logger.info("start.");
timeWatch = new TimeWatch();
st.enableDraw(true);
countFile(fileClassPath, minLength);
st.enableDraw(false);
String maxKey = findMaxFrequencyKey(st);
logger.info("minLength={} words, st size:{}, max frequency word is: \"{}\" which occurs {} times.",
minLength, st.size(), maxKey, st.get(maxKey));
logger.info("total: {} ms, countWords: {} ms, findMax: {} ms.",
timeWatch.getTotalCostMs(),
timeWatch.getTagCostMs(TAG_COUNT_WORDS),
timeWatch.getTagCostMs(TAG_FIND_MAX));
}
private void countFile(String fileClassPath, int minLength) {
logger.info("countFile begin");
try (BufferedReader reader = newReader(fileClassPath)) {
timeWatch.tag(TAG_OTHER);
String line;
int totalWordCount = 0;
while ((line = reader.readLine()) != null) {
totalWordCount += processLine(line, minLength);
}
timeWatch.tag(TAG_COUNT_WORDS);
logger.info("total processed word count {}", totalWordCount);
} catch (Exception e) {
throw new IllegalStateException("read file error!", e);
}
}
private int processLine(final String line, final int minLength) {
String[] words = line.split(WORD_SEPARATOR);
if (words == null || words.length == 0) {
return 0;
}
int processedWordCount = 0;
for (String word : words) {
if (word.length() < minLength) {
continue;
}
processedWordCount++;
Integer frequency = st.get(word);
if (frequency == null) {
st.put(word, 1);
} else {
st.put(word, frequency + 1);
}
}
return processedWordCount;
}
private String findMaxFrequencyKey(ST<String, Integer> st) {
timeWatch.tag(TAG_OTHER);
String max = "";
st.put(max, -1);
for (String word : st.keys())
if (st.get(word).intValue() > st.get(max).intValue())
max = word;
timeWatch.tag(TAG_FIND_MAX);
return max;
}
private BufferedReader newReader(String fileClassPath) {
ClassPathResource cpr = new ClassPathResource(fileClassPath);
try {
return new BufferedReader(new FileReader(cpr.getFile()));
} catch (IOException e) {
throw new IllegalStateException("read file error!", e);
}
}
public static void main(String[] args) throws InterruptedException {
TimeWatch timeWatch = new TimeWatch();
timeWatch.tag("1");
Thread.sleep(800);
timeWatch.tag("2");
System.out.println(timeWatch.getTagCostMs("1"));
System.out.println(timeWatch.getTagCostMs("2"));
}
} |
package com.example.fileshare.service;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.List;
public interface StorageService {
void init();
String store(MultipartFile file);
Path load(String filename);
Resource loadAsResource(String filename);
void deleteAll();
List<Path> loadAll();
void delete(String path);
void update(String path, String oldName, String newName);
void create(String path, String name);
} |
package com.redsun.platf.util;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
public class PasswordUtil {
// static final String salt = "EPSALT";
static final String salt="admin" ;
private static final String password = "1234";
/**
* @param args
*/
public static void main(String[] args) {
String standardPasswordEncoder = EncryptUtil.encrypt(password);
System.out.println("StandardPasswordEncoder string:"+EncryptUtil.encrypt(password));
System.out.println("length:="+standardPasswordEncoder.length());
System.out.println("StandardPasswordEncoder mathch:"+ EncryptUtil.match(password, standardPasswordEncoder)); // true
// String salt = KeyGenerators.string().generateKey();
// System.out.println("salt random:"+salt);
// TextEncryptor encryptor =Encryptors.text(password,salt);
//
// System.out.println(encryptor.encrypt(password));
String md5 = EncryptUtil.md5Encrypt(password, salt);
System.out.println("md5 pass:" + md5);
System.out.println("md5 length:" + md5.length());
System.out.println("md5 match:"
+ EncryptUtil.md5Match(password, md5, salt));
System.out.println("md5 match:"
+ EncryptUtil.md5Match(md5, password, salt));
String sha = EncryptUtil.shaEncrypt(password, salt);
System.out.println("sha pass:" + sha);
System.out.println("sha length:" + sha.length());
System.out.println("sha match:"
+ EncryptUtil.shaMatch(password, sha, salt));
// System.out.println("sha match:"+EncryptUtil.shaMatch(sha, password,
// salt));
// DigestUtils.
}
/**
* 取得MD5加密后的字符
*
* @param source
* @return
*/
public static String enCoderMD5(String source) {
return enCoderMD5(source, salt);
}
/**
* 取得MD5加密后的字符
*
* @param source
* @param saltString 为空时用 salt
* @return
*/
public static String enCoderMD5(String source, String saltString) {
if (saltString == null) saltString = salt;
return EncryptUtil.md5Encrypt(source, saltString);
}
/**
* 取得SHA加密后的字符
*
* @param source
* @return
*/
public static String enCoderSHA(String source) {
return enCoderSHA(source, salt);
}
/**
* 取得SHA加密后的字符
*
* @param source
* @param saltString 为空时用 salt
* @return
*/
public static String enCoderSHA(String source, String saltString) {
if (saltString == null) saltString = salt;
return EncryptUtil.shaEncrypt(source, saltString);
}
}
/**
* 内部类
*/
class EncryptUtil {
private static final StandardPasswordEncoder encoder = new StandardPasswordEncoder();
private static final Md5PasswordEncoder md5Encoder = new Md5PasswordEncoder();
private static final MessageDigestPasswordEncoder shaEncoder = new ShaPasswordEncoder(
256);
/**
* 加密
*
* @param rawPassword
* @return
*/
public static String encrypt(String rawPassword) {
return encoder.encode(rawPassword);
}
public static String md5Encrypt(String rawPassword, String salt) {
return md5Encoder.encodePassword(rawPassword, salt);
}
public static String shaEncrypt(String rawPassword, String salt) {
return shaEncoder.encodePassword(rawPassword, salt);
}
/**
* 驗證
*
* @param rawPassword 原來的密碼
* @param password 加密後的密碼
* @return
*/
public static boolean match(String rawPassword, String password) {
return encoder.matches(rawPassword, password);
}
public static boolean md5Match(String rawPassword, String password,
String salt) {
return md5Encoder.isPasswordValid(password, rawPassword, salt);
}
public static boolean shaMatch(String rawPassword, String password,
String salt) {
return shaEncoder.isPasswordValid(password, rawPassword, salt);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.