text
stringlengths 10
2.72M
|
|---|
package com.radiant.rpl.testa.ExamSection;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.radiant.rpl.testa.LocalDB.DbAutoSave;
import java.util.ArrayList;
import radiant.rpl.radiantrpl.R;
public class CustomAdapter extends BaseAdapter{
String result[];
Context con;
String aa;
ArrayList<String> queidd=new ArrayList<>();
ArrayList<String> statussss=new ArrayList<>();
ArrayList<String> questatuss=new ArrayList<>();
String img[];
DbAutoSave dbAutoSave;
private static LayoutInflater inflater = null;
public CustomAdapter(ArrayList<String> queidd, Context con, ArrayList<String> statussss, ArrayList<String> questatuss) {
this.queidd = queidd;
this.con = con;
this.statussss=statussss;
this.questatuss=questatuss;
inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return queidd.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final holder hld = new holder();
View rowview;
rowview = inflater.inflate(R.layout.gdmainfortestquestion, null);
hld.tv = rowview.findViewById(R.id.txt2);
hld.tv.setText(queidd.get(position));
int ii=statussss.size();
if (position<ii){
if (statussss.get(position).equals("1")){
hld.tv.setTextColor(Color.GREEN);
}else if (statussss.get(position).equals("2")){
hld.tv.setTextColor(con.getResources().getColor(R.color.purple));
}else if (statussss.get(position).equals("0")){
hld.tv.setTextColor(Color.BLUE);
}else {
hld.tv.setTextColor(Color.BLACK);
}
}
else {
hld.tv.setTextColor(Color.BLACK);
}
/* if (queidd.get(position).equals(questatuss.get(position))){
hld.tv.setTextColor(Color.BLUE);
}
else
{
hld.tv.setTextColor(Color.GREEN);
}*/
return rowview;
}
public class holder
{
TextView tv;
}
}
|
package com.tkb.elearning.service.impl;
import java.util.List;
import com.tkb.elearning.dao.CramCaseDao;
import com.tkb.elearning.model.CramCase;
import com.tkb.elearning.service.CramCaseService;
public class CramCaseServiceImpl implements CramCaseService{
private CramCaseDao cramCaseDao;
public List<CramCase> getList(int pageCount, int pageStart, CramCase cramCase){
return cramCaseDao.getList(pageCount, pageStart, cramCase);
}
public Integer getCount(CramCase cramCase){
return cramCaseDao.getCount(cramCase);
}
public CramCase getData(CramCase cramCase){
return cramCaseDao.getData(cramCase);
}
public void add(CramCase cramCase){
cramCaseDao.add(cramCase);
}
public void update(CramCase cramCase){
cramCaseDao.update(cramCase);
}
public void delete(Integer id){
cramCaseDao.delete(id);
}
public void setCramCaseDao(CramCaseDao cramCaseDao) {
this.cramCaseDao = cramCaseDao;
}
}
|
/*
* 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 uptc.softMin.gui;
import javax.swing.*;
import java.awt.*;
public class PanelMainwindow extends JPanel {
private MainWindow mainWindow;
private JLabel titleSoft;
private JButton clOld;
private JButton clModern;
private JButton clScala;
private JButton grouppage;
private JButton exit;
public PanelMainwindow(MainWindow mainWindow) {
this.mainWindow = mainWindow;
setLayout(null);
beginComponents();
addComponents();
}
@Override
public void paintComponent(Graphics g){
Dimension dimension= getSize();
// ImageIcon ImageIcon = new ImageIcon("resours/images/mainWind.png");
ImageIcon ImageIcon = new ImageIcon("/uptc/softMin/imagen/mainWind.png");
Image image = ImageIcon.getImage();
g.drawImage(image, 0,0,dimension.width,dimension.height,null);
}
private void beginComponents() {
titleSoft = new JLabel("MINING TOOLS Y CLASIFICACIONES GEOMECANICAS");
titleSoft.setBounds(20, 35, 690, 30);
titleSoft.setForeground(Color.GREEN);
titleSoft.setFont(new Font("mi font", Font.BOLD, 25));
clOld = new JButton("Clasificaciones Antiguas");
clOld.setBounds(40, 330, 185, 30);
clOld.setActionCommand(HandlingEvents.clOLD);
clOld.addActionListener(mainWindow.getHandlingEvents());
clOld.setForeground(Color.BLACK);
clOld.setFont(new Font("mi font", Font.BOLD, 12));
clModern = new JButton("Clasificaciones Modernas");
clModern.setBounds(252, 330, 185, 30);
clModern.setActionCommand(HandlingEvents.clMODERN);
clModern.addActionListener(mainWindow.getHandlingEvents());
clModern.setForeground(Color.BLACK);
clModern.setFont(new Font("mi font", Font.BOLD, 12));
clScala = new JButton("Clasificaciones Excavabilidad");
clScala.setBounds(460, 330, 200, 30);
clScala.setActionCommand(HandlingEvents.clSCALAB);
clScala.addActionListener(mainWindow.getHandlingEvents());
clScala.setForeground(Color.BLACK);
clScala.setFont(new Font("mi font", Font.BOLD, 12));
grouppage = new JButton("Pagina del grupo");
grouppage.setBounds(340, 370, 180, 30);
grouppage.setActionCommand(HandlingEvents.gpPAGE);
grouppage.addActionListener(mainWindow.getHandlingEvents());
grouppage.setIcon(new ImageIcon("resours/inter.png"));
grouppage.setForeground(Color.BLACK);
grouppage.setFont(new Font("mi font", Font.BOLD, 12));
exit = new JButton("SALIR");
exit.setBounds(210, 370, 100, 30);
exit.setActionCommand(HandlingEvents.EXIT);
exit.addActionListener(mainWindow.getHandlingEvents());
exit.setIcon(new ImageIcon("resours/images/icExit.png"));
exit.setForeground(Color.BLACK);
exit.setFont(new Font("mi font", Font.BOLD, 12));
}
private void addComponents() {
add(titleSoft);
add(clOld);
add(clModern);
add(clScala);
add(grouppage);
add(exit);
}
}
|
package com.twitter.graphjet.demo;
import org.elasticsearch.common.joda.time.DateTimeUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Map;
/**
* Created by saurav on 22/03/17.
*/
public class CreateGraph extends AbstractServlet {
private static final SecureRandom random = new SecureRandom();
public CreateGraph(Map<String, SprGraph> graphs) {
super(graphs);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
SprGraph sprGraph = new SprGraph();
String identifier = DateTimeUtils.currentTimeMillis() + "" + random.nextLong();
graphs.put(identifier, sprGraph);
System.out.println("new graph created with Identifier: " + identifier);
response.getWriter().println(identifier);
}
}
|
package com.github.emailtohl.integration.core.auth;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.github.emailtohl.integration.core.config.CorePresetData;
import com.github.emailtohl.integration.core.coreTestConfig.CoreTestData;
import com.github.emailtohl.integration.core.coreTestConfig.CoreTestEnvironment;
import com.github.emailtohl.lib.encryption.myrsa.Encipher;
import com.github.emailtohl.lib.exception.InvalidDataException;
/**
* 业务类测试
* @author HeLei
*/
public class AuthenticationManagerImplTest extends CoreTestEnvironment {
@Inject
AuthenticationManager authenticationManager;// AuthenticationProviderImpl的实例
@Inject
CorePresetData cpd;
@Inject
CoreTestData td;
String password = "123456";
Encipher encipher = new Encipher();
String publicKey, privateKey;
@Before
public void setUp() throws Exception {
String[] pair = encipher.getKeyPairs(256);
publicKey = pair[0];
privateKey = pair[1];
((AuthenticationManagerImpl) authenticationManager).setPrivateKey(privateKey);
}
@After
public void tearDown() throws Exception {
}
@Test
public void testAuthenticateAuthentication() {
String crypted = encipher.encrypt(password, publicKey);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(td.bar.getEmpNum().toString(), crypted);
authenticationManager.authenticate(token);
}
@Test(expected = UsernameNotFoundException.class)
public void testUsernameNotFoundException() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("abc", password);
authenticationManager.authenticate(token);
}
@Test(expected = UsernameNotFoundException.class)
public void testUsernameNotFoundExceptionBot() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(cpd.user_bot.getEmpNum(), password);
authenticationManager.authenticate(token);
}
@Test(expected = UsernameNotFoundException.class)
public void testUsernameNotFoundExceptionAnonymous() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(cpd.user_anonymous.getEmail(), password);
authenticationManager.authenticate(token);
}
@Test(expected = InvalidDataException.class)
public void testInvalidDataException() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(td.bar.getEmpNum().toString(), "123");
authenticationManager.authenticate(token);
}
@Test(expected = BadCredentialsException.class)
public void testBadCredentialsException() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(td.bar.getEmpNum().toString(), encipher.encrypt("123", publicKey));
authenticationManager.authenticate(token);
}
}
|
package org.murinrad.android.musicmultiply.receiver;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
/**
* Created by Radovan Murin on 11.4.2015.
*/
public class DeviceNameAsker extends LinearLayout {
EditText text;
Button okButton;
DeviceNameAsker m_this;
DeviceNameAskerCallback callback;
public DeviceNameAsker(Context context) {
super(context);
// init();
}
public DeviceNameAsker(Context context, AttributeSet attrs) {
super(context, attrs);
// init();
}
void init() {
text = (EditText) findViewById(R.id.editText);
okButton = (Button) findViewById(R.id.button);
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String newName = text.getText().toString();
if (validateName(newName)) {
if (callback != null) {
callback.successInternal(newName);
}
} else {
text.setError(getResources().getString(R.string.device_name_error));
}
}
});
m_this = this;
}
public void setCallback(DeviceNameAskerCallback callback) {
this.callback = callback;
}
private boolean validateName(String text) {
if (text == null || text.length() <= 4) {
return false;
}
return true;
}
public static abstract class DeviceNameAskerCallback {
void successInternal(String newName) {
onSuccess(newName);
}
abstract void onSuccess(String newName);
}
}
|
package mine_mine_20;
public class FizzBuzz2 {
public static void main (String [] args ){
int num =25;
if (num % 5 ==0 && num % 6 ==0){
System.out.println("FizzBuzz");
}else if(num % 5 ==0){
System.out.println("Fizz");
}else if (num % 6 ==0){
System.out.println("Buzz");
}else{
System.out.println(num);
}
}
}
|
package de.zarncke.lib.io.store;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLConnection;
import de.zarncke.lib.err.Warden;
import de.zarncke.lib.io.IOTools;
import de.zarncke.lib.region.Region;
import de.zarncke.lib.region.RegionUtil;
/**
* Store which reads resources from an {@link URLConnection}.
*
* @author Gunnar Zarncke
*/
public class UrlStore extends AbstractStore {
// TODO add test
private static final String RESOURCE_SEPARATOR = "/";
private final Store parent;
private final URI uri;
public UrlStore(final URI uri) {
this(uri, null);
}
public UrlStore(final URI uri, final Store parent) {
this.uri = uri;
this.parent = parent;
}
@Override
public boolean exists() {
// TODO perform HEAD request
return canRead();
}
private InputStream getStream() throws IOException {
return this.uri.toURL().openStream();
}
@Override
public Store element(final String name) {
return new UrlStore(this.uri.resolve(name), this);
}
public String getName() {
if (this.uri == null) {
return null;
}
String path = this.uri.getPath();
int p = path.lastIndexOf(RESOURCE_SEPARATOR);
return path.substring(p + 1);
}
@Override
public Store getParent() {
return this.parent;
}
@Override
public boolean canRead() {
try {
return getStream() != null;
} catch (IOException e) {
Warden.disregard(e);
return false;
}
}
@Override
public InputStream getInputStream() throws IOException {
InputStream is = getStream();
if (is == null) {
throw new IOException("cannot read " + this.uri);
}
return is;
}
@Override
public Region asRegion() throws IOException {
// TODO consider returning a region which fills as the stream is read
return RegionUtil.asRegion(IOTools.getAllBytes(getStream()));
}
@Override
public String toString() {
return this.uri.toASCIIString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.uri == null ? 0 : this.uri.hashCode());
return result;
}
}
|
package Composition.Challange;
/**
* @Author pankaj
* @create 4/26/21 4:13 PM
*/
public class MainRunner {
public static void main(String[] args) {
Wall wall1 = new Wall("West");
Wall wal2= new Wall("East");
Wall wall3= new Wall("South");
Wall wall4 = new Wall("North");
Ceiling ceiling= new Ceiling(22,36);
Bed bed=new Bed("Modern",4,3,2,1);
Lamp lamp= new Lamp("Classic ",false,55);
BedRoom bedRoom=new BedRoom("Pankaj rooms",wall1,wal2,wall3,wall4,ceiling,bed,lamp);
bedRoom.makeBed();
bedRoom.getLamp().turnOn();
}
}
|
package br.usp.ffclrp.dcm.lssb.transformation_software.rulesprocessing;
public class FlagContentDirectionTSVColumn extends Flag {
private Enum<EnumContentDirectionTSVColumn> direction;
public FlagContentDirectionTSVColumn(Enum<EnumContentDirectionTSVColumn> direction){
this.direction = direction;
}
public Enum<EnumContentDirectionTSVColumn> getDirection() {
return direction;
}
}
|
package kodlamaio.hrms.api.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import kodlamaio.hrms.business.abstracts.AuthService;
import kodlamaio.hrms.core.utilities.result.Result;
import kodlamaio.hrms.entities.dtos.CandidateRegisterDto;
import kodlamaio.hrms.entities.dtos.EmployerRegisterDto;
@RestController
@RequestMapping(name = "/api/auth")
@CrossOrigin
public class AuthController {
private AuthService authService;
@Autowired
public AuthController(AuthService authService) {
super();
this.authService = authService;
}
@PostMapping("/register-candidate")
public Result add(@RequestBody CandidateRegisterDto candidateRegisterDto) {
return authService.registerCandidate(candidateRegisterDto);
}
@PostMapping("/register-employer")
public Result add(@RequestBody EmployerRegisterDto employerRegisterDto) {
return authService.registerEmployer(employerRegisterDto);
}
}
|
package io.bega.kduino.maps;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.overlay.OverlayItem;
import java.text.DecimalFormat;
/**
* Created by usuario on 03/08/15.
*/
public class KdUINOOverlayItem extends OverlayItem {
String plotKD;
String description;
String user;
GeoPoint point;
public KdUINOOverlayItem(String aTitle, String aSnippet, GeoPoint aGeoPoint, String plotKD, String user) {
super(aTitle, aSnippet, aGeoPoint);
this.plotKD = plotKD;
this.user = user;
this.point = aGeoPoint;
}
public String getPlotKD() {
return plotKD;
}
public String getDescription()
{
return description;
}
public String getUser()
{
return user;
}
public String getPosition()
{
String position = "";
if (point != null)
{
DecimalFormat form = new DecimalFormat("0.0000");
position = "Lat: " + form.format(this.point.getLatitude()) +
", Lon: " + form.format(this.point.getLongitude());
}
return position;
}
public KdUINOOverlayItem(String aUid, String aTitle, String aDescription, GeoPoint aGeoPoint, String plotKD, String user) {
super(aUid, aTitle, aDescription, aGeoPoint);
this.description = aDescription;
this.user = user;
this.plotKD = plotKD;
}
}
|
package com.zz.webflux.controller;
import com.zz.webflux.dao.StudentDao;
import com.zz.webflux.model.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
@RestController
public class StudentController {
private final StudentDao studentDao;
public StudentController(StudentDao studentDao) {
this.studentDao = studentDao;
}
@GetMapping("/Students")
public Flux<Student> findAll(){
List<Student> students = studentDao.findAll();
return Flux.fromIterable(students);
}
@GetMapping("/Student/{id}")
public Mono<Student> findById(@PathVariable("id") Long id){
Student student = studentDao.findById(id);
return Mono.justOrEmpty(student);
}
}
|
package net.lotrek.dynarec.devices;
import java.util.ArrayList;
public class InterruptController extends MemorySpaceDevice
{
/*
* byte status - (0000 -> error code)(0000 -> has record to process)
* byte command - (0 = add, 1 = remove)(0000000 -> interrupt id)
* byte regionLength - length of the region to watch in bytes (1-8)
*/
private Structure controlStructure = new Structure(Byte.class, Byte.class, Integer.class, Byte.class);
private Register[] instanceRegisters;
private ArrayList<int[]> monitorList = new ArrayList<>();
private ArrayList<Long> cachedValues = new ArrayList<>();
public int getOccupationLength()
{
return controlStructure.getLength();
}
public void executeDeviceCycle()
{
if(((byte)instanceRegisters[0].getValue() & 0xf) == 1)
{
if(((byte)instanceRegisters[1].getValue() >> 7 & 1) == 0) //add
{
// System.out.println("Added interrupt " + ((byte)instanceRegisters[1].getValue() & 0x7F) + " to address " + (int)instanceRegisters[2].getValue());
if(monitorList.size() > ((byte)instanceRegisters[1].getValue() & 0x7F))
monitorList.set((byte)instanceRegisters[1].getValue() & 0x7F, new int[]{(int)instanceRegisters[2].getValue(), (byte)instanceRegisters[3].getValue()});
else
monitorList.add((byte)instanceRegisters[1].getValue() & 0x7F, new int[]{(int)instanceRegisters[2].getValue(), (byte)instanceRegisters[3].getValue()});
if(cachedValues.size() > ((byte)instanceRegisters[1].getValue() & 0x7F))
cachedValues.set((byte)instanceRegisters[1].getValue() & 0x7F, (long)(byte)(Byte)Register.getTypeForBytes((byte)instanceRegisters[3].getValue(), this.getProcessor().getMemory(), (int)instanceRegisters[2].getValue()));
else
cachedValues.add((byte)instanceRegisters[1].getValue() & 0x7F, (long)(byte)(Byte)Register.getTypeForBytes((byte)instanceRegisters[3].getValue(), this.getProcessor().getMemory(), (int)instanceRegisters[2].getValue()));
}
else //remove
{
// System.out.println("Removed interrupt " + ((byte)instanceRegisters[1].getValue() & 0x7F));
monitorList.remove((byte)instanceRegisters[1].getValue() & 0x7F);
}
instanceRegisters[0].setValue(Byte.class, (byte)0);
}
int i = 0;
for (int[] area : monitorList)
{
if((long)(byte)(Byte)Register.getTypeForBytes(area[1], this.getProcessor().getMemory(), area[0]) != cachedValues.get(i))
{
cachedValues.set(i, (long)(byte)Register.getTypeForBytes(area[1], this.getProcessor().getMemory(), area[0]));
this.getProcessor().interrupt(0, i, area[0]);
}
i++;
}
}
public void initializeDevice()
{
instanceRegisters = controlStructure.getInstance(getOccupationAddr(), this.getProcessor().getMemory());
}
public void disposeDevice(){}
}
|
package com.xiaoxiao.service.backend.impl;
import com.xiaoxiao.feign.BlogsFeignServiceClient;
import com.xiaoxiao.pojo.XiaoxiaoAdminMessage;
import com.xiaoxiao.service.backend.AdminManagerService;
import com.xiaoxiao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/12/2:11:46
* @author:shinelon
* @Describe:
*/
@Service
public class AdminManagerServiceImpl implements AdminManagerService
{
@Autowired
private BlogsFeignServiceClient client;
/**
* 查找全部的后台管理菜单
* @return
*/
@Override
public Result findAllManager()
{
return this.client.findAllAdminManager();
}
/**
* 查询全
* @param page
* @param rows
* @return
*/
@Override
public Result findAllManager(Integer page, Integer rows)
{
return this.client.findAllManager(page,rows);
}
/**
* 插入
* @param message
* @return
*/
@Override
public Result insert(XiaoxiaoAdminMessage message)
{
return this.client.insert(message);
}
/**
* 删除
* @param adminId
* @return
*/
@Override
public Result deleteAdminManager(String adminId)
{
return this.client.deleteAdminManager(adminId);
}
/**
* 获取一个的
* @param adminId
* @return
*/
@Override
public Result findAdminManagerById(Long adminId)
{
return this.client.findAdminManagerById(adminId);
}
}
|
package com.yingying.distributed.hw2.writer;
import com.yingying.distributed.hw2.Config;
import com.yingying.distributed.hw2.distributedIO.DIOAction;
import com.yingying.distributed.hw2.distributedIO.nativeIO.PrintAction;
import com.yingying.distributed.hw2.distributedIO.nativeIO.RAFAction;
import com.yingying.distributed.hw2.distributedIO.nativeIO.StreamAction;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class MTWriter extends BaseWriter {
@Override
protected DIOAction initialize(Class<? extends DIOAction> clazz, String suffix) {
try {
Constructor ctos = clazz.getConstructor(String.class);
final String path = Config.nativePrefix + suffix;
final File out = new File(path);
if (out.exists()) out.delete();
return (DIOAction) ctos.newInstance(path);
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException("Initialize DIOAction failure");
}
}
private void rafTest() {
execute(RAFAction.class, "raf.txt");
}
private void printTest() {
execute(PrintAction.class, "print.txt");
}
private void streamTest() {
execute(StreamAction.class, "stream.txt");
}
public static void main(String args[]) {
MTWriter mtw = new MTWriter();
mtw.printTest();
mtw.rafTest();
mtw.streamTest();
}
}
|
package ch20.ex20_10;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import static java.io.StreamTokenizer.*;
import java.util.HashMap;
import java.util.Map;
public class WordsCount {
private HashMap <String, Integer> counts = new HashMap <String, Integer>();
public void result(){
for(Map.Entry <String, Integer> entry : counts.entrySet()){
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
public void count(String str){
Integer i;
if(counts.containsKey(str)){
i = counts.get(str);
i++;
}
else {
i = 1;
}
counts.put(str, i);
}
//入力ファイルを分析
public void analyze(Reader reader) throws IOException{
StreamTokenizer tokenizer = new StreamTokenizer(reader);
int tokenKind = TT_EOF;
//ファイルの終わりまで
while((tokenKind = tokenizer.nextToken()) != TT_EOF){
switch(tokenKind){
case TT_NUMBER:
String num = String.valueOf(tokenizer.nval);
count(num);
break;
case TT_WORD:
String value = tokenizer.sval;
count(value);
break;
default:
break;
}
}
}
}
|
package TransferValue;
public class demo {
public void changeInt(int age){
age = 20;
}
public void changeObject(Person p){
p.name = "例子";
}
public void changeString(String s){
s = "niuniuniu";
}
public static void main(String[] args) {
demo d = new demo();
int age = 10;
// 我们通过一个方法去修改main方法中我们定义的这个值
// 其实changeInt()方法中改变的是这个值的副本,原来的值不会改变的
d.changeInt(age);
System.out.println(age);
Person p = new Person("zhangsan",10);
// 但是这个却变了?????
// 基本类型一般传的是副本,而复杂类型的传的是引用。。。
d.changeObject(p);
System.out.println(p.name);
String name = "da";
// String也不是基本类型,为啥它不改变呢?????
// 这个和JVM的实现有关。JVM中有一个字符串常量池,没有的字符串就创建,有的话就复用
//public void changeString(String s){
// s = "niuniuniu";
// }
//
//所以上面这个方法,一开始传进去的s指向"da"字符串
// 但是后来创建了"niuniuniu",这个s又重新指向"niuniuniu"了
d.changeString(name);
System.out.println(name);
}
}
|
package january9;
import static org.testng.Assert.assertTrue;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.ITest;
import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(january9.Listeners.class) // You can mention the listener class in a specific class
// alternatively, you can use xml file to apply the listener for multiple classes
public class ListenersTestDemo {
static WebDriver driver;
@BeforeMethod
public void login() {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumFiles\\browserDrivers\\chromedriver.exe");
driver= new ChromeDriver();
driver.get("http://secure.smartbearsoftware.com/samples/TestComplete12/WebOrders/Login.aspx");
driver.findElement(By.id("ctl00_MainContent_username")).sendKeys("Tester");
driver.findElement(By.id("ctl00_MainContent_password")).sendKeys("test");
driver.findElement(By.name("ctl00$MainContent$login_button")).click();
}
@Test (testName = "test1")
public void test1() {
assertTrue(true);
}
@Test (testName = "test2")
public void test2() {
assertTrue(false);
}
@Test (testName = "test3")
public void test3() {
throw new SkipException("test is skipped");
}
}
|
package com.tencent.mm.plugin.emoji.g;
import com.tencent.mm.protocal.c.ta;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public final class b {
public static ArrayList<ta> zF(String str) {
if (bi.oW(str)) {
x.w("MicroMsg.emoji.EmojiBackupXMLParser", "[backup emotion parser] parse xml faild. xml is null.");
return null;
}
try {
Document parse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new ByteArrayInputStream(str.getBytes())));
parse.normalize();
NodeList elementsByTagName = parse.getDocumentElement().getElementsByTagName("EmojiMd5");
if (elementsByTagName == null || elementsByTagName.getLength() <= 0) {
return null;
}
ArrayList<ta> arrayList = new ArrayList();
int length = elementsByTagName.getLength();
for (int i = 0; i < length; i++) {
Node item = elementsByTagName.item(i);
ta taVar = new ta();
String toLowerCase = item.getTextContent().toLowerCase();
NamedNodeMap attributes = item.getAttributes();
Node namedItem = attributes.getNamedItem("thumburl");
if (namedItem != null) {
taVar.lPl = namedItem.getNodeValue();
}
namedItem = attributes.getNamedItem("cdnurl");
if (namedItem != null) {
taVar.jPK = namedItem.getNodeValue();
}
namedItem = attributes.getNamedItem("productid");
if (namedItem != null) {
taVar.rem = namedItem.getNodeValue();
}
namedItem = attributes.getNamedItem("designerid");
if (namedItem != null) {
taVar.rwl = namedItem.getNodeValue();
}
namedItem = attributes.getNamedItem("aeskey");
if (namedItem != null) {
taVar.rwn = namedItem.getNodeValue();
}
namedItem = attributes.getNamedItem("encrypturl");
if (namedItem != null) {
taVar.rwm = namedItem.getNodeValue();
}
item = attributes.getNamedItem("activityid");
if (item != null) {
taVar.rwq = item.getNodeValue();
}
taVar.rwk = toLowerCase;
arrayList.add(taVar);
}
return arrayList;
} catch (Exception e) {
x.e("MicroMsg.emoji.EmojiBackupXMLParser", "[parser] parseXML exception:%s", new Object[]{e.toString()});
return null;
}
}
public static ArrayList<String> zG(String str) {
if (bi.oW(str)) {
x.w("MicroMsg.emoji.EmojiBackupXMLParser", "[backup emotion parser] parse xml faild. xml is null.");
return null;
}
try {
Document parse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new ByteArrayInputStream(str.getBytes())));
parse.normalize();
NodeList elementsByTagName = parse.getDocumentElement().getElementsByTagName("ProductID");
if (elementsByTagName == null || elementsByTagName.getLength() <= 0) {
return null;
}
ArrayList<String> arrayList = new ArrayList();
int length = elementsByTagName.getLength();
for (int i = 0; i < length; i++) {
arrayList.add(elementsByTagName.item(i).getTextContent());
}
return arrayList;
} catch (Exception e) {
x.e("MicroMsg.emoji.EmojiBackupXMLParser", "[parser] parseXML exception:%s", new Object[]{e.toString()});
return null;
}
}
}
|
package design.mode.factory.abstractFactory;
public interface IFnShiKangFactory {
Phone producePhone();
Laptop produceLaptop();
}
|
package com.catalyst.selenium.pages;
import org.openqa.selenium.WebDriver;
import com.catalyst.selenium.framework.PageObject;
public class HomePage extends PageObject{
public HomePage(WebDriver driver) {
super(driver);
url = "http://localhost:8080/#/home";
goTo(url);
}
}
|
package com.cnk.travelogix.supplier.inventory.populator;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import java.math.BigDecimal;
import com.cnk.travelogix.accoinventory.core.model.AccoInventoryDefinitionModel;
import com.cnk.travelogix.supplier.inventory.data.SupplierInventoryData;
/**
* Class populate information from AccoInventoryDefinitionModel to SupplierInventoryData
*/
public class SupplierInventoryPopulator implements Populator<AccoInventoryDefinitionModel, SupplierInventoryData> {
@Override
public void populate(final AccoInventoryDefinitionModel source, final SupplierInventoryData target) throws ConversionException {
target.setSupplierID(source.getSupplier().getCode());
target.setAvailabiltyStatus("N");
target.setHotelCode(21);
target.setTotalPrice(BigDecimal.valueOf(5050.75d));
}
}
|
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class SquareTest {
private int side;
private Square square;
@Before
public void setup() {
side = 10;
square = new Square(side);
}
@Test
public void testComputeArea() {
Assert.assertEquals(side * side, square.computeArea());
}
@Test
public void testSideGetter() {
Assert.assertEquals(side, square.getSide());
}
@Test
public void testSideSetter() {
int newSide = 13;
square.setSide(newSide);
Assert.assertEquals(newSide, square.getSide());
}
@Test
public void testComputeAreaAfterModification() {
int newSide = 13;
square.setSide(newSide);
Assert.assertEquals(newSide * newSide, square.computeArea());
}
}
|
package gr.athena.innovation.fagi.core.function;
import org.apache.jena.rdf.model.Literal;
/**
* Interface for a condition function that takes two literals and one string parameter as input.
*
* @author nkarag
*/
public interface IFunctionThreeLiteralStringParameters extends IFunction{
/**
* Evaluates the three parameter function.
* @param literalA the literal of A.
* @param literalB the literal of B.
* @param parameter the string parameter.
* @return the evaluation result.
*/
public boolean evaluate(Literal literalA, Literal literalB, String parameter);
}
|
package com.jack.rookietest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.naming.Name;
@SpringBootApplication
public class RookieTestApplication implements CommandLineRunner{
@Value("${name}")
private String name;
@Value("${sex}")
private String sex;
@Value("${age}")
private String age;
/*@Value("${jack.hello}")
private String hello;*/
public static void main(String[] args) {
SpringApplication.run(RookieTestApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("*****************启动成功*****************"+name);
System.out.println("性别:"+sex);
System.out.println("年龄:"+age);
/*System.out.println("hello:"+hello);*/
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.corespi.scanner;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import org.apache.webbeans.config.OWBLogConst;
import org.apache.webbeans.config.OpenWebBeansConfiguration;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.corespi.scanner.xbean.CdiArchive;
import org.apache.webbeans.corespi.scanner.xbean.OwbAnnotationFinder;
import org.apache.webbeans.exception.WebBeansDeploymentException;
import org.apache.webbeans.logger.WebBeansLoggerFacade;
import org.apache.webbeans.spi.BDABeansXmlScanner;
import org.apache.webbeans.spi.BdaScannerService;
import org.apache.webbeans.spi.BeanArchiveService;
import org.apache.webbeans.spi.BeanArchiveService.BeanDiscoveryMode;
import org.apache.webbeans.util.ClassUtil;
import org.apache.webbeans.util.UrlSet;
import org.apache.webbeans.util.WebBeansUtil;
import org.apache.xbean.finder.AnnotationFinder;
import org.apache.xbean.finder.ClassLoaders;
import org.apache.xbean.finder.archive.Archive;
import org.apache.xbean.finder.filter.Filter;
import org.apache.xbean.finder.util.Files;
import jakarta.decorator.Decorator;
import jakarta.enterprise.context.Dependent;
import jakarta.interceptor.Interceptor;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class AbstractMetaDataDiscovery implements BdaScannerService
{
protected static final Logger logger = WebBeansLoggerFacade.getLogger(AbstractMetaDataDiscovery.class);
public static final String META_INF_BEANS_XML = "META-INF/beans.xml";
// via constant to also adopt to shading.
private static final String DEPENDENT_CLASS = Dependent.class.getName();
private Map<String, Boolean> annotationCache = new HashMap<>();
private BeanArchiveService beanArchiveService;
/**
* Location of the beans.xml files.
* Since CDI-1.1 (OWB-2.0) this also includes 'implicit bean archives.
* Means URLs of JARs which do not have a beans.xml marker file.
*/
private final UrlSet beanArchiveLocations = new UrlSet();
/**
* This Map contains the corresponding deployment URL for each beans.xml locations.
*
* key: the beans.xml externalForm
* value: the corresponding base URL
*
* We store this information since not all containers and storages do support
* new URL(...).
*/
private final Map<String, URL> beanDeploymentUrls = new HashMap<>();
/**
* for having proper scan mode 'SCOPED' support we need to know which bean class
* has which beans.xml.
*/
private Map<BeanArchiveService.BeanArchiveInformation, Set<Class<?>>> beanClassesPerBda;
protected String[] scanningExcludes;
protected ClassLoader loader;
protected CdiArchive archive;
protected OwbAnnotationFinder finder;
protected boolean isBDAScannerEnabled;
protected BDABeansXmlScanner bdaBeansXmlScanner;
protected WebBeansContext webBeansContext;
protected AnnotationFinder initFinder()
{
if (finder != null)
{
return finder;
}
final WebBeansContext webBeansContext = webBeansContext();
if (beanArchiveService == null)
{
beanArchiveService = webBeansContext.getBeanArchiveService();
}
final Filter userFilter = webBeansContext.getService(Filter.class);
Map<String, URL> beanDeploymentUrls = getBeanDeploymentUrls();
if (!webBeansContext.getOpenWebBeansConfiguration().getScanExtensionJars())
{
webBeansContext.getExtensionLoader().loadExtensionServices();
final Set<URL> extensionJars = webBeansContext.getExtensionLoader().getExtensionJars();
beanDeploymentUrls = extensionJars.isEmpty() ? beanDeploymentUrls : beanDeploymentUrls.entrySet().stream()
.filter(it -> !extensionJars.contains(it.getValue()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
extensionJars.clear(); // no more needed
}
archive = new CdiArchive(
beanArchiveService, WebBeansUtil.getCurrentClassLoader(),
beanDeploymentUrls, userFilter, getAdditionalArchive());
finder = new OwbAnnotationFinder(archive);
return finder;
}
protected Archive getAdditionalArchive()
{
return null;
}
/**
* @return list of beans.xml locations or implicit bean archives
* @deprecated just here for backward compat reasons
*/
protected Iterable<URL> getBeanArchiveUrls()
{
return beanArchiveLocations;
}
/**
* @return URLs of all classpath entries which
*/
public Map<String, URL> getBeanDeploymentUrls()
{
return beanDeploymentUrls;
}
/**
* Configure the Web Beans Container with deployment information and fills
* annotation database and beans.xml stream database.
*
* @throws org.apache.webbeans.exception.WebBeansConfigurationException if any run time exception occurs
*/
@Override
public void scan() throws WebBeansDeploymentException
{
try
{
configure();
initFinder();
}
catch (Exception e)
{
throw new WebBeansDeploymentException(e);
}
}
protected abstract void configure();
/**
* Since CDI-1.1 this is actually more a 'findBdaBases' as it also
* picks up jars without marker file.
* This will register all 'explicit' Bean Archives, aka all
* META-INF/beans.xml resources on the classpath. Those will
* be added including the META-INF/beans.xml in the URL.
*
* We will also add all other classpath locations which do not
* have the beans.xml marker file, the 'implicit bean archives'.
* In this case the URL will point to the root of the classpath entry.
*
* @param loader the ClassLoader which should be used
*
* @see #getBeanArchiveUrls()
* @see #getBeanDeploymentUrls()
*/
protected void registerBeanArchives(ClassLoader loader)
{
this.loader = loader;
try
{
final Set<URL> classPathUrls = ClassLoaders.findUrls(loader);
Map<File, URL> classpathFiles = toFiles(classPathUrls);
// first step: get all META-INF/beans.xml marker files
Enumeration<URL> beansXmlUrls = loader.getResources(META_INF_BEANS_XML);
while (beansXmlUrls.hasMoreElements())
{
URL beansXmlUrl = beansXmlUrls.nextElement();
addWebBeansXmlLocation(beansXmlUrl);
if (classpathFiles == null) // handle protocols out if [jar,file] set
{
// second step: remove the corresponding classpath entry if we found an explicit beans.xml
String beansXml = beansXmlUrl.toExternalForm();
beansXml = stripProtocol(beansXml);
Iterator<URL> cpIt = classPathUrls.iterator(); // do not use Set<URL> remove as this would trigger hashCode -> DNS
while (cpIt.hasNext())
{
URL cpUrl = cpIt.next();
if (beansXml.startsWith(stripProtocol(cpUrl.toExternalForm())))
{
cpIt.remove();
addDeploymentUrl(beansXml, cpUrl);
break;
}
}
}
else
{
File key = Files.toFile(beansXmlUrl);
URL url = classpathFiles.remove(key);
if (url == null &&
"beans.xml".equals(key.getName()) &&
key.getParentFile() != null &&
"META-INF".equals(key.getParentFile().getName()))
{
key = key.getParentFile().getParentFile();
url = classpathFiles.remove(key);
}
if (url != null)
{
addDeploymentUrl(beansXmlUrl.toExternalForm(), url);
}
}
}
boolean onlyBeansXmlJars = webBeansContext().getOpenWebBeansConfiguration().scanOnlyBeansXmlJars();
if (!onlyBeansXmlJars)
{
// third step: remove all jars we know they do not contain any CDI beans
filterExcludedJars(classPathUrls);
if (classpathFiles != null)
{
classpathFiles = classpathFiles.entrySet().stream()
.filter(e -> classPathUrls.contains(e.getValue()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
}
// forth step: add all 'implicit bean archives'
for (URL url : (classpathFiles == null ? classPathUrls : classpathFiles.values()))
{
if (isBdaUrlEnabled(url))
{
addWebBeansXmlLocation(url);
addDeploymentUrl(url.toExternalForm(), url);
}
}
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
protected Map<File, URL> toFiles(final Set<URL> classPathUrls)
{
try
{
final Map<File, URL> collected = classPathUrls.stream()
.collect(toMap(Files::toFile, identity(), (a, b) -> a));
if (collected.containsKey(null)) // not a known protocol
{
return null;
}
return collected;
}
catch (final RuntimeException re)
{
return null;
}
}
/**
* Get rid of any protocol header from the url externalForm
* @param urlPath
*/
protected String stripProtocol(String urlPath)
{
int pos = urlPath.lastIndexOf(":/");
if (pos > 0)
{
return urlPath.substring(pos+1);
}
return urlPath;
}
protected void filterExcludedJars(Set<URL> classPathUrls)
{
classPathUrls.removeIf(i -> isExcludedJar(i));
}
protected boolean isExcludedJar(URL url)
{
String path = url.toExternalForm();
// TODO: should extract file path and test file.getName(), not the whole path
// + should be configurable
int knownJarIdx = isExcludedJar(path);
// -Prun-its openwebbeans-tomcat7 in path but WEB-INF/classes
if (knownJarIdx > 0 && knownJarIdx < path.indexOf(".jar"))
{
//X TODO this should be much more actually
//X TODO we might need to configure it via files
return true;
}
else
{
if (path.contains("geronimo-"))
{
// we could check for META-INF/maven/org.apache.geronimo.specs presence there but this is faster
final File file = Files.toFile(url);
if (file != null)
{
final String filename = file.getName();
if (filename.startsWith("geronimo-") && filename.contains("_spec"))
{
return true;
}
}
}
}
return false;
}
protected int isExcludedJar(String path)
{
// lazy init - required when using DS CdiTestRunner
initScanningExcludes();
for (String p : scanningExcludes)
{
int i = path.indexOf(p);
if (i > 0)
{
return i;
}
}
return -1;
}
@Override
public void release()
{
finder = null;
archive = null;
loader = null;
annotationCache.clear();
}
/**
* Add an URL for a deployment later on
* @param beansXml
* @param cpUrl
*/
protected void addDeploymentUrl(String beansXml, URL cpUrl)
{
beanDeploymentUrls.put(beansXml, cpUrl);
}
/**
* This method could filter out known JARs or even JVM classpaths which
* shall not be considered bean archives.
*
* @return whether the URL is a bean archive or not
*/
protected boolean isBdaUrlEnabled(URL bdaUrl)
{
return true;
}
@Override
public void init(Object object)
{
// set per BDA beans.xml flag here because setting it in constructor
// occurs before
// properties are loaded.
String usage = WebBeansContext.currentInstance().getOpenWebBeansConfiguration().getProperty(OpenWebBeansConfiguration.USE_BDA_BEANSXML_SCANNER);
isBDAScannerEnabled = Boolean.parseBoolean(usage);
initScanningExcludes();
}
public void initScanningExcludes()
{
if (scanningExcludes == null)
{
OpenWebBeansConfiguration owbConfiguration = WebBeansContext.currentInstance().getOpenWebBeansConfiguration();
String scanningExcludesProperty = owbConfiguration.getProperty(OpenWebBeansConfiguration.SCAN_EXCLUSION_PATHS);
List<String> excludes = owbConfiguration.splitValues(scanningExcludesProperty);
scanningExcludes = excludes.toArray(new String[excludes.size()]);
}
}
/**
* add the given beans.xml path to the locations list
* @param beanArchiveUrl location path
*/
protected void addWebBeansXmlLocation(URL beanArchiveUrl)
{
// just the logging there to let children customize the way it is printed out,
// no logic there but in doAddWebBeansXmlLocation(URL) please
if(logger.isLoggable(Level.INFO))
{
logger.info("added beans archive URL: " + beanArchiveUrl.toExternalForm());
}
doAddWebBeansXmlLocation(beanArchiveUrl);
}
protected void doAddWebBeansXmlLocation(URL beanArchiveUrl)
{
beanArchiveLocations.add(beanArchiveUrl);
// and also scan the bean archive!
if (beanArchiveService == null)
{
beanArchiveService = webBeansContext().getBeanArchiveService();
}
// just to trigger the creation
beanArchiveService.getBeanArchiveInformation(beanArchiveUrl);
}
/**
* This method only gets called if the initialisation is done already.
* It will collect all the classes from all the BDAs it can find.
*/
public Map<BeanArchiveService.BeanArchiveInformation, Set<Class<?>>> getBeanClassesPerBda()
{
if (beanClassesPerBda == null)
{
beanClassesPerBda = new HashMap<>();
ClassLoader loader = WebBeansUtil.getCurrentClassLoader();
boolean dontSkipNCDFT = !(webBeansContext != null &&
webBeansContext.getOpenWebBeansConfiguration().isSkipNoClassDefFoundErrorTriggers());
for (CdiArchive.FoundClasses foundClasses : archive.classesByUrl().values())
{
Set<Class<?>> classSet = new HashSet<>();
boolean scanModeAnnotated = BeanDiscoveryMode.ANNOTATED == foundClasses.getBeanArchiveInfo().getBeanDiscoveryMode();
for (String className : foundClasses.getClassNames())
{
try
{
if (scanModeAnnotated)
{
// in this case we need to find out whether we should keep this class in the Archive
AnnotationFinder.ClassInfo classInfo = finder.getClassInfo(className);
if (classInfo == null || !isBeanAnnotatedClass(classInfo))
{
continue;
}
}
Class<?> clazz = ClassUtil.getClassFromName(className, loader, dontSkipNCDFT);
if (clazz != null)
{
if (dontSkipNCDFT)
{
// try to provoke a NoClassDefFoundError exception which is thrown
// if some dependencies of the class are missing
clazz.getDeclaredFields();
}
// we can add this class cause it has been loaded completely
classSet.add(clazz);
}
}
catch (NoClassDefFoundError e)
{
if (isAnonymous(className))
{
if (logger.isLoggable(Level.FINE))
{
logger.log(Level.FINE, OWBLogConst.WARN_0018, new Object[]{className, e.toString()});
}
}
else if (logger.isLoggable(Level.WARNING))
{
logger.log(Level.WARNING, OWBLogConst.WARN_0018, new Object[]{className, e.toString()});
}
}
}
beanClassesPerBda.put(foundClasses.getBeanArchiveInfo(), classSet);
}
}
return beanClassesPerBda;
}
private boolean isAnonymous(final String className)
{
final int start = className.lastIndexOf('$');
if (start <= 0)
{
return false;
}
try
{
Integer.parseInt(className.substring(start + 1));
return true;
}
catch (final NumberFormatException nfe)
{
return false;
}
}
/* (non-Javadoc)
* @see org.apache.webbeans.corespi.ScannerService#getBeanClasses()
*/
@Override
public Set<Class<?>> getBeanClasses()
{
// do nothing, getBeanClasses() should not get invoked anymore
return Collections.EMPTY_SET;
}
/**
* This method is called for classes from bean archives with
* bean-discovery-mode 'annotated'.
*
* This method is intended to be overwritten in integration scenarios and e.g.
* allows to add other criterias for keeping the class.
*
* @param classInfo
* @return true if this class should be kept and further get picked up as CDI Bean
*/
protected boolean isBeanAnnotatedClass(AnnotationFinder.ClassInfo classInfo)
{
// check whether this class has 'scope' annotations or a stereotype
for (AnnotationFinder.AnnotationInfo annotationInfo : classInfo.getAnnotations())
{
if (Interceptor.class.getName().equals(annotationInfo.getName()) ||
Decorator.class.getName().equals(annotationInfo.getName()) ||
isBeanAnnotation(annotationInfo))
{
return true;
}
}
return false;
}
protected boolean isBeanAnnotation(AnnotationFinder.AnnotationInfo annotationInfo)
{
String annotationName = annotationInfo.getName();
Boolean isBeanAnnotation = annotationCache.get(annotationName);
if (isBeanAnnotation != null)
{
return isBeanAnnotation;
}
try
{
Class<? extends Annotation> annotationType = (Class<? extends Annotation>) WebBeansUtil.getCurrentClassLoader().loadClass(annotationName);
isBeanAnnotation = DEPENDENT_CLASS.equals(annotationName) || webBeansContext().getBeanManagerImpl().isNormalScope(annotationType);
if (!isBeanAnnotation)
{
isBeanAnnotation = webBeansContext().getBeanManagerImpl().isStereotype(annotationType);
}
annotationCache.put(annotationName, isBeanAnnotation);
return isBeanAnnotation;
}
catch (ClassNotFoundException e)
{
return false;
}
}
@Override
public Set<URL> getBeanXmls()
{
return Collections.unmodifiableSet(beanArchiveLocations);
}
@Override
public BDABeansXmlScanner getBDABeansXmlScanner()
{
return bdaBeansXmlScanner;
}
@Override
public boolean isBDABeansXmlScanningEnabled()
{
return isBDAScannerEnabled;
}
protected WebBeansContext webBeansContext()
{
if (webBeansContext == null)
{
webBeansContext = WebBeansContext.getInstance();
}
return WebBeansContext.getInstance();
}
}
|
package com.wipe.zc.journey.lib.calendar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import com.wipe.zc.journey.R;
public class MonkeyCalendarHorizontal extends LinearLayout {
private LinearLayout ll_monkeycalendar_horizontal;
private MonkeyDateHorizontal mPreviousSelectedDate;
private Calendar date_now = Calendar.getInstance();
private Calendar date_selected = Calendar.getInstance();
private Context context;
private ArrayList<Calendar> list_record;
private int windowWidth;
private int startX;
private int offsetLeft = 0;
private int dateWidth;
private boolean firstFill = true;
public interface OnMonthChangeListener {
public void OnMonthChange(Calendar date);
}
private OnMonthChangeListener mMonthChangeListener;
public void setOnMonthChangeListener(OnMonthChangeListener mMonthChangeListener) {
this.mMonthChangeListener = mMonthChangeListener;
}
public interface OnDateSelectedListener {
public void onDateSelected(Calendar date);
}
private OnDateSelectedListener mDateSelectedListener;
public void setOnDateSelectedListener(OnDateSelectedListener mDateSelectedListener) {
this.mDateSelectedListener = mDateSelectedListener;
}
public MonkeyCalendarHorizontal(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public MonkeyCalendarHorizontal(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
setWindowWidth();
init(context);
}
public MonkeyCalendarHorizontal(Context context) {
super(context);
this.context = context;
setWindowWidth();
init(context);
}
private void init(Context context) {
View.inflate(context, R.layout.layout_monkeycalendar_horizontal, this);
ll_monkeycalendar_horizontal = (LinearLayout) findViewById(R.id.ll_monkeycalendar_horizontal);
fillDateView();
}
/**
* 添加
*/
private void fillDateView() {
// 清除所有子控件
ll_monkeycalendar_horizontal.removeAllViews();
// TODO 填充日历内容
dateWidth = getWindowWidth() / 7;
MonkeyDateHorizontal date;
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// lp.weight = 1;
lp.width = dateWidth;
int mostdate = date_now.getActualMaximum(Calendar.DAY_OF_MONTH);
int day = 1;
for (int i = 0; i < mostdate; i++) {
date = new MonkeyDateHorizontal(context);
date.setLayoutParams(lp);
date.setBackgroundColor(Color.parseColor("#F9F9F9"));
date.setGravity(Gravity.CENTER);
// 星期字体
date.setWeekTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
date.setWeekTextColor(Color.parseColor("#BDBDBD"));
// 日期字体
date.setDateTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
date.setDateTextColor(Color.parseColor("#11111C"));
date.setPointVisiable(true);
// 设置年月日
date.setYear(date_now.get(Calendar.YEAR));
date.setMonth(date_now.get(Calendar.MONTH));
date.setDay(day);
// 设置触摸监听
date.setOnTouchListener(dateClickedListener);
date_now.set(Calendar.DAY_OF_MONTH, day);
// 当前日期是否存在记录
if (isRecord(date_now)) {
date.setPointVisiable(true);
} else {
date.setPointVisiable(false);
}
// 今天
if (isToday(date_now)) {
mPreviousSelectedDate = date;
date.setWeekTextColor(Color.parseColor("#BDBDBD"));
date.setDateTextColor(Color.parseColor("#D73C10"));
if (date_selected.get(Calendar.MONTH) == date_now.get(Calendar.MONTH)
&& date_selected.get(Calendar.DAY_OF_MONTH) == day) { // 本日且被选中
date.setWeekTextColor(Color.WHITE);
date.setBackgroundColor(Color.parseColor("#52d2c4"));
date.setPointBackground(R.drawable.icon_point_white);
}
if (firstFill) {
// 在中间移动范围内
if (date_now.get(Calendar.DAY_OF_MONTH) > 4 && date_now.get(Calendar.DAY_OF_MONTH) <= mostdate - 3) {
int day_of_month = date_now.get(Calendar.DAY_OF_MONTH);
ll_monkeycalendar_horizontal.scrollTo(dateWidth * (day_of_month - 4), 0);
offsetLeft += dateWidth * (day_of_month - 4);
}
// 在后段范围内
if (date_now.get(Calendar.DAY_OF_MONTH) > (mostdate - 3)
&& date_now.get(Calendar.DAY_OF_MONTH) <= mostdate) {
ll_monkeycalendar_horizontal.scrollTo(dateWidth * (mostdate - 7), 0);
offsetLeft += dateWidth * (mostdate - 7);
}
}
}
// 选中
else if (date_selected.get(Calendar.MONTH) == date_now.get(Calendar.MONTH)
&& date_selected.get(Calendar.DAY_OF_MONTH) == day) {
mPreviousSelectedDate = date;
date.setWeekTextColor(Color.WHITE);
date.setDateTextColor(Color.WHITE);
date.setPointBackground(R.drawable.icon_point_blue);
date.setBackgroundColor(Color.parseColor("#52d2c4"));
}
date.setDateText(String.valueOf(day++));
date.setWeekText(date_now.get(Calendar.DAY_OF_WEEK));
ll_monkeycalendar_horizontal.addView(date);
}
}
// 获取选中的日期
public Calendar getSelectedDate() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, date_selected.get(Calendar.YEAR));
calendar.set(Calendar.MONTH, date_selected.get(Calendar.MONTH));
calendar.set(Calendar.DAY_OF_MONTH, date_selected.get(Calendar.DAY_OF_MONTH));
return calendar;
}
/**
* 是否存在记录
*
* @param date
* @return
*/
private boolean isRecord(Calendar date) {
if (list_record != null) {
for (Calendar record_date : list_record) {
// 当前日期存在记录
if (date.get(Calendar.YEAR) == record_date.get(Calendar.YEAR)
&& date.get(Calendar.MONTH) == record_date.get(Calendar.MONTH)
&& date.get(Calendar.DAY_OF_MONTH) == record_date.get(Calendar.DAY_OF_MONTH)) {
return true;
}
}
}
return false;
}
/**
* 判断是否是今天
*
* @param date
* @return
*/
private boolean isToday(Calendar date) {
Calendar today = Calendar.getInstance();
return date.get(Calendar.YEAR) == today.get(Calendar.YEAR)
&& date.get(Calendar.MONTH) == today.get(Calendar.MONTH)
&& date.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH);
}
/**
* 方法重载
*
* @param yaer
* @param month
* @param day
* @return
*/
private boolean isToday(int yaer, int month, int day) {
Calendar today = Calendar.getInstance();
return yaer == today.get(Calendar.YEAR) && month == today.get(Calendar.MONTH)
&& day == today.get(Calendar.DAY_OF_MONTH);
}
/**
* 设置设备的宽度
*/
public void setWindowWidth() {
Activity activity = (Activity) context;
Display d = activity.getWindowManager().getDefaultDisplay();
windowWidth = d.getWidth();
}
private int getWindowWidth() {
return windowWidth;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获取日期控件宽度
int width = MeasureSpec.getSize(widthMeasureSpec);
dateWidth = width / 7;
}
/**
* 本月日期点击事件
*/
private OnTouchListener dateClickedListener = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
MonkeyDateHorizontal tv = (MonkeyDateHorizontal) v;
Calendar selected = Calendar.getInstance();
// TODO DEBUG日期
selected.set(Calendar.YEAR, tv.getYear());
selected.set(Calendar.MONTH, tv.getMonth());
selected.set(Calendar.DAY_OF_MONTH, tv.getDay());
if (!isToday(selected)) { // 选中的不是当天
tv.setDateTextColor(Color.WHITE);
} else {
tv.setDateTextColor(Color.parseColor("#D73C10"));
}
tv.setWeekTextColor(Color.WHITE);
tv.setPointBackground(R.drawable.icon_point_white);
// tv.setPadding(0, 8, 0, 8);
tv.setBackgroundColor(Color.parseColor("#52d2c4"));
if (mPreviousSelectedDate != null) {
if (mPreviousSelectedDate != tv) {
try {
if (isToday(mPreviousSelectedDate.getYear(), mPreviousSelectedDate.getMonth(),
mPreviousSelectedDate.getDay())) {
mPreviousSelectedDate.setWeekTextColor(Color.parseColor("#BDBDBD"));
mPreviousSelectedDate.setDateTextColor(Color.parseColor("#D73C10"));
mPreviousSelectedDate.setPointBackground(R.drawable.icon_point_blue);
mPreviousSelectedDate.setBackgroundColor(Color.parseColor("#F9F9F9"));
} else {
mPreviousSelectedDate.setWeekTextColor(Color.parseColor("#BDBDBD"));
mPreviousSelectedDate.setDateTextColor(Color.parseColor("#11111C"));
mPreviousSelectedDate.setPointBackground(R.drawable.icon_point_blue);
mPreviousSelectedDate.setBackgroundColor(Color.parseColor("#F9F9F9"));
}
} catch (Exception ex) {
mPreviousSelectedDate.setWeekTextColor(Color.parseColor("#BDBDBD"));
mPreviousSelectedDate.setDateTextColor(Color.parseColor("#11111C"));
mPreviousSelectedDate.setPointBackground(R.drawable.icon_point_blue);
mPreviousSelectedDate.setBackgroundColor(Color.parseColor("#F9F9F9"));
}
}
}
// 设置选中的日期
int selectedDay = Integer.parseInt(((MonkeyDateHorizontal) v).getDateText().toString());
date_selected.set(Calendar.YEAR, date_now.get(Calendar.YEAR));
date_selected.set(Calendar.MONTH, date_now.get(Calendar.MONTH));
date_selected.set(Calendar.DAY_OF_MONTH, selectedDay);
mPreviousSelectedDate = (MonkeyDateHorizontal) v;
if (mDateSelectedListener != null)
mDateSelectedListener.onDateSelected(date_selected);
break;
default:
break;
}
return true;
}
};
private int start;
private int overLeft;
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: // 按下记录
start = (int) ev.getX();
startX = (int) ev.getX();
// System.out.println(startX);
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) ev.getX();
int offset = moveX - startX;
// System.out.println(offset);
if (offset > 0) {// 认定为右移 上月
// 月内移动
ll_monkeycalendar_horizontal.scrollBy(-offset, 0);
if (offsetLeft > 0) { // 超出左端
offsetLeft += -offset;
if (overLeft > 0) { // 回转操作
overLeft += -offset;
}
} else { // 月初部分
overLeft += -offset;
}
// System.out.println("右移" + offsetLeft);
} else { // 认定为左移 下月
int width = dateWidth * date_now.getActualMaximum(Calendar.DAY_OF_MONTH);
ll_monkeycalendar_horizontal.scrollBy(-offset, 0);
if (offsetLeft < width - windowWidth) { // 超出右端
offsetLeft += -offset;
if (overLeft < 0) { // 回转操作
overLeft += -offset;
}
} else { // 月末部分
overLeft += -offset; // 超出
}
}
System.out.println("左移" + offsetLeft);
System.out.println(overLeft);
startX = (int) ev.getX();
break;
case MotionEvent.ACTION_UP:
int endX = (int) ev.getX();
if (endX > start) { // 右滑动处理
if (overLeft <= -windowWidth / 2) { // 距离大,换至上月
date_now.add(Calendar.MONTH, -1);
date_now.set(Calendar.DAY_OF_MONTH, 1);
int mostday = date_now.getActualMaximum(Calendar.DAY_OF_MONTH);
fillDateView();
// 动画效果
ll_monkeycalendar_horizontal.scrollTo(0, 0);
TranslateAnimation ta = new TranslateAnimation(-windowWidth, 0, 0, 0);
ta.setDuration(500);
ta.setRepeatMode(Animation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
// 归零数据
offsetLeft = 0;
overLeft = 0;
// 移动位置
ll_monkeycalendar_horizontal.scrollTo(dateWidth * (mostday - 7), 0);
offsetLeft += dateWidth * (mostday - 7);
if (mMonthChangeListener != null) {
mMonthChangeListener.OnMonthChange(date_now);
}
} else if (overLeft != 0) { // 距离小,还原本月
ll_monkeycalendar_horizontal.scrollBy(-overLeft, 0);
offsetLeft = 0;
overLeft = 0;
}
return true;
} else if (endX < start) { // 左滑动处理
if (overLeft >= windowWidth / 2) { // 距离大,换至下月
date_now.add(Calendar.MONTH, 1);
date_now.set(Calendar.DAY_OF_MONTH, 1);
fillDateView();
// 动画效果
ll_monkeycalendar_horizontal.scrollTo(0, 0);
TranslateAnimation ta = new TranslateAnimation(0, -windowWidth, 0, 0);
ta.setDuration(500);
ta.setRepeatMode(Animation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
// 归零数据
offsetLeft = 0;
overLeft = 0;
if (mMonthChangeListener != null) {
mMonthChangeListener.OnMonthChange(date_now);
}
} else if (overLeft != 0) { // 距离小,还原本月
ll_monkeycalendar_horizontal.scrollBy(-overLeft, 0);
int width = date_now.getActualMaximum(Calendar.DAY_OF_MONTH) * dateWidth;
offsetLeft = width - windowWidth;
overLeft = 0;
}
return true;
} else {
return false;
}
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
/**
* 设置记录集合
*
* @param list
*/
public void setRecordList(List<Calendar> list) {
list_record = (ArrayList<Calendar>) list;
fillDateView();
}
/**
* 返回当天
*/
public void backToToday() {
Calendar calendar = Calendar.getInstance();
date_now = calendar;
fillDateView();
if (mMonthChangeListener != null) {
mMonthChangeListener.OnMonthChange(date_now);
}
}
/**
* 改变日期为
*
* @param calendar
*/
public void changeDateTo(Calendar calendar) {
// 同年变化
if (calendar.get(Calendar.YEAR) == date_now.get(Calendar.YEAR)) {
if (calendar.get(Calendar.MONTH) != date_now.get(Calendar.MONTH)) { // 不同月变化
date_now = calendar;
fillDateView();
ll_monkeycalendar_horizontal.scrollTo(0, 0);
if (calendar.get(Calendar.MONTH) > date_now.get(Calendar.MONTH)) { // 下月
TranslateAnimation ta = new TranslateAnimation(0.0F, -windowWidth, 0.0F, 0.0F);
ta.setDuration(500);
ta.setRepeatMode(TranslateAnimation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
}
if (calendar.get(Calendar.MONTH) < date_now.get(Calendar.MONTH)) { // 上月
TranslateAnimation ta = new TranslateAnimation(0.0F, -windowWidth, 0.0F, 0.0F);
ta.setDuration(500);
ta.setRepeatMode(TranslateAnimation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
}
offsetLeft = 0;
overLeft = 0;
if (this.mMonthChangeListener != null) {
this.mMonthChangeListener.OnMonthChange(date_now);
}
}
}else{ //不同年
date_now = calendar;
fillDateView();
ll_monkeycalendar_horizontal.scrollTo(0, 0);
if(calendar.get(Calendar.YEAR) > date_now.get(Calendar.YEAR)){
TranslateAnimation ta = new TranslateAnimation(0.0F, -windowWidth, 0.0F, 0.0F);
ta.setDuration(500);
ta.setRepeatMode(TranslateAnimation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
}
if(calendar.get(Calendar.YEAR) < date_now.get(Calendar.YEAR)){
TranslateAnimation ta = new TranslateAnimation(0.0F, -windowWidth, 0.0F, 0.0F);
ta.setDuration(500);
ta.setRepeatMode(TranslateAnimation.RESTART);
ll_monkeycalendar_horizontal.startAnimation(ta);
}
offsetLeft = 0;
overLeft = 0;
if (this.mMonthChangeListener != null) {
this.mMonthChangeListener.OnMonthChange(date_now);
}
}
}
}
|
package com.smxknife.mq.rocketmq;
import com.smxknife.mq.api.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* @author smxknife
* 2020/5/18
*/
@Slf4j
public class RocketMqConsumer extends MqConsumer<RocketMqBroker> {
private DefaultMQPushConsumer consumer;
public RocketMqConsumer(String name, RocketMqBroker broker, WorkerExecutor workerExecutor) {
super(name, broker, workerExecutor);
}
@Override
public void subscribe(String destination, List<String> tags, Map<String, Object> arguments, MessageHandler handler) {
try {
Object messageModel = Objects.nonNull(arguments) ? arguments.get("MessageModel") : null;
if (Objects.nonNull(messageModel)) {
if (MessageModel.BROADCASTING.getModeCN().equalsIgnoreCase(String.valueOf(messageModel))) {
consumer.setMessageModel(MessageModel.BROADCASTING);
}
}
consumer.subscribe(destination, tags.get(0));
consumer.setConsumeFromWhere(
ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
IdempotenceToken token = new IdempotenceToken();
consumer.registerMessageListener(
new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(
List<MessageExt> list,
ConsumeConcurrentlyContext Context) {
Message msg = list.get(0);
String topic = msg.getTopic();
String tags = msg.getTags();
byte[] body = msg.getBody();
String data = new String(body);
String tokenKey = msg.getProperties().get(Constant.MESSAGE_HEADER_TOKEN_KEY);
getIdempotenceHandler().ifPresent(handler -> token.copy(handler.checkToken(tokenKey)));
if (!token.checkSuccess()) {
log.warn("Skipped!!! {} receive duplicate message from exchange = {}, routingKey = {}, msg = {}", name, topic, tags, data);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
log.info("{} receive message from topic = {}, tags = {}, msg = {} ", name, topic, tags, data);
handler.handle(topic, tags, data);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
);
consumer.start();
} catch (MQClientException e) {
log.error(e.getErrorMessage(), e);
}
}
@Override
protected void init() throws Exception {
consumer = new DefaultMQPushConsumer(name);
consumer.setNamesrvAddr(broker.getNamesrvAddr());
}
}
|
package tema8;
import java.io.*;
import java.util.*;
public class Clientela implements Comparator<Usuario> {
private ArrayList<Usuario> clientela;
public Clientela() {
clientela = new ArrayList<Usuario>();
}
public ArrayList<Usuario> retornaClientela() {
return clientela;
}
public void zeraClientela() {
clientela.clear();
}
public int getSize() {
return clientela.size();
}
public void atualizaCont() {
int proximoId=0;
for (Usuario usuario : clientela) {
if (usuario.getId() > proximoId) {
proximoId = usuario.getId();
}
}
Usuario.setCont(proximoId);
}
public void addUsuario(Usuario usuario) {
clientela.add(usuario);
}
public void removerUsuario(Usuario usuario) {
clientela.remove(usuario);
}
public Optional<Usuario> buscaUsuarioPorID(int id) {
for (Usuario usuario : clientela) {
if ( usuario.getId() == id ) {
return Optional.of(usuario);
}
}
return Optional.empty();
}
public void pagouQtSaldo(Usuario usuario, int saldoDevedor) {
usuario.pagouQtSaldo(saldoDevedor);
if (usuario.getSaldoDevedor() <= 0) {
usuario.quitouAtraso();
}
}
@Override
public int compare(Usuario o1, Usuario o2) {
return o1.compareTo(o2);
}
public ArrayList<Usuario> topUsuarios() {
ArrayList<Usuario> usuariosDescQtLocacoes = clientela;
Collections.sort(usuariosDescQtLocacoes);
return usuariosDescQtLocacoes;
}
}
|
package com.mvc.upgrade.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.mvc.upgrade.model.biz.MYBoardBiz;
import com.mvc.upgrade.model.dto.MYBoardDto;
@Controller
public class MYBoardController {
@Autowired
private MYBoardBiz biz;
@RequestMapping("/list.do")
public String selectList(Model model) {
model.addAttribute("list", biz.selectList());
return "boardlist";
}
@RequestMapping("/insertform.do")
public String insertForm() {
return "insertform";
}
@RequestMapping("/insertres.do")
public String insertRes(MYBoardDto dto) {
if(biz.insert(dto) > 0) {
return "redirect:list.do";
}
return "redirect:insertform.do";
}
}
|
package com.ibm.jikesbt;
/*
* Licensed Material - Property of IBM
* (C) Copyright IBM Corp. 1998, 2003
* All rights reserved
*/
import java.io.DataOutputStream;
import java.io.IOException;
/**
Represents an opc_newarray instruction that allocates an array of primitives.
Also see {@link BT_ANewArrayIns}, {@link BT_MultiANewArrayIns}, and {@link
BT_NewIns}.
Typically created by one of the {@link BT_Ins#make} methods.
* @author IBM
**/
public final class BT_NewArrayIns extends BT_NewIns {
/**
Types as represented in newarray instruction operands.
See {@link BT_Class#getBoolean()}, ..., {@link BT_Class#getLong()} for
types represented as classes.
**/
public static final short T_BOOLEAN = 4;
public static final short T_CHAR = 5;
public static final short T_FLOAT = 6;
public static final short T_DOUBLE = 7;
public static final short T_BYTE = 8;
public static final short T_SHORT = 9;
public static final short T_INT = 10;
public static final short T_LONG = 11;
/**
* The bytecode for a 'newarray' instruction actually refers to the element class
* and not the array class itself. This is in contrast to the 'multianewarray'
* instruction and the 'new' instruction, but similar to 'anewarray'.
*
* The target field of a new instruction always refers to the created class.
* So both constructors here translate from the element class referred to in the
* bytecode and initialize target as the array class that is actually created.
*/
/**
For application use via {@link BT_Ins#make}.
**/
BT_NewArrayIns(BT_Class primitive) {
super(opc_newarray);
if (primitive == null)
assertFailure(Messages.getString("JikesBT.The_class_must_be_a_primitive____not_null_1"));
if(!primitive.isBasicTypeClass) {
assertFailure(Messages.getString("JikesBT.The_class_must_be_a_primitive____not_{0}_2", primitive));
}
target = primitive.getArrayClass();
}
/**
One of {@link BT_Misc#T_BOOLEAN} thru {@link BT_Misc#T_LONG}.
**/
int getTypeNumber() {
BT_Class primitive = target.arrayType;
BT_Repository repository = primitive.getRepository();
if (primitive == repository.getBoolean())
return T_BOOLEAN;
else if (primitive == repository.getByte())
return T_BYTE;
else if (primitive == repository.getChar())
return T_CHAR;
else if (primitive == repository.getDouble())
return T_DOUBLE;
else if (primitive == repository.getFloat())
return T_FLOAT;
else if (primitive == repository.getInt())
return T_INT;
else if (primitive == repository.getLong())
return T_LONG;
else if (primitive == repository.getShort())
return T_SHORT;
else
throw new IllegalStateException(Messages.getString("JikesBT.The_class_must_be_a_primitive____not_{0}_2", primitive));
}
/**
For use when reading a class-file.
@param index The byte offset of the instruction.
-1 mean unknown?
**/
BT_NewArrayIns(int opcode, int index, short typeNumber, BT_Repository repository)
throws BT_ClassFileException {
super(opcode, index);
if (CHECK_USER && opcode != opc_newarray)
expect(Messages.getString("JikesBT.Invalid_opcode_for_this_constructor___4") + opcode);
BT_Class primitive;
switch (typeNumber) {
case T_BOOLEAN :
primitive = repository.getBoolean();
break;
case T_BYTE :
primitive = repository.getByte();
break;
case T_CHAR :
primitive = repository.getChar();
break;
case T_DOUBLE :
primitive = repository.getDouble();
break;
case T_FLOAT :
primitive = repository.getFloat();
break;
case T_INT :
primitive = repository.getInt();
break;
case T_LONG :
primitive = repository.getLong();
break;
case T_SHORT :
primitive = repository.getShort();
break; // Ok
default :
throw new BT_ClassFileException(Messages.getString("JikesBT.invalid_primitive_type_in_newarray_instruction_4"));
}
target = primitive.getArrayClass();
}
public void link(BT_CodeAttribute code) {
BT_CreationSite site = target.addCreationSite(this, code);
if(site != null) {
code.addCreatedClass(site);
super.linkClassReference(site, target);
}
}
public void unlink(BT_CodeAttribute code) {
super.unlinkReference(code);
target.removeCreationSite(this);
code.removeCreatedClass(this);
}
public boolean isNewArrayIns() {
return true;
}
public boolean optimize(BT_CodeAttribute code, int n, boolean strict) {
return false;
}
public void resolve(BT_CodeAttribute code, BT_ConstantPool pool) {}
public void write(DataOutputStream dos, BT_CodeAttribute code, BT_ConstantPool pool)
throws IOException {
dos.writeByte(opcode);
dos.writeByte(getTypeNumber());
if (CHECK_JIKESBT && size() != 2)
assertFailure(
Messages.getString("JikesBT.Write/size_error_{0}_3", this)
+ Messages.getString("JikesBT._expected_{0}_got_{1}_7",
new Object[] {Integer.toString(2), Integer.toString(size())}));
}
public Object clone() {
return new BT_NewArrayIns(target.arrayType);
}
public String toString() {
return getPrefix() + BT_Misc.opcodeName[opcode] + " " + target.arrayType.name;
}
public String toAssemblerString(BT_CodeAttribute code) {
return BT_Misc.opcodeName[opcode] + " " + target.arrayType.name;
}
}
|
package com.ibeiliao.trade.test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:trade-spring/applicationContext.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public abstract class BaseTestCase {
}
|
package present;
import java.util.List;
import bean.Duanzibean;
import bean.TuijianBean;
import fragment.Tuijian;
import m.Getdatamodle;
import mInterface.Duanziview;
import mInterface.Tuijianview;
import mybase.Basepresent;
/**
* Created by 地地 on 2017/11/28.
* 邮箱:461211527@qq.com.
*/
public class Gettuiianp extends Basepresent {
private Getdatamodle getdatamodle;
private Tuijianview tujianview;
public Gettuiianp(Object viewmodel) {
super(viewmodel);
this.tujianview= (Tuijianview) viewmodel;
if(getdatamodle==null){
getdatamodle=new Getdatamodle();
}
}
public void getduanzidata(String uid, int type, int page){
getdatamodle.gettuijian(uid, type, page, new Getdatamodle.requesttuijianBack() {
@Override
public void success(List<TuijianBean> list) {
tujianview.getdatasuess(list);
}
@Override
public void fail(Throwable e) {
tujianview.getdatafail(e.toString());
}
});
}
}
|
package com.handsome.qhb.ui.activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
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.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handsome.qhb.adapter.ShopCarAdapter;
import com.handsome.qhb.application.MyApplication;
import com.handsome.qhb.bean.Address;
import com.handsome.qhb.bean.IdNum;
import com.handsome.qhb.bean.OrderJson;
import com.handsome.qhb.bean.Product;
import com.handsome.qhb.config.Config;
import com.handsome.qhb.db.UserDAO;
import com.handsome.qhb.db.UserDBOpenHelper;
import com.handsome.qhb.listener.MyListener;
import com.handsome.qhb.utils.HttpUtils;
import com.handsome.qhb.utils.LogUtils;
import com.handsome.qhb.utils.UserInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import tab.com.handsome.handsome.R;
/**
* Created by zhang on 2016/3/13.
*/
public class GwcActivity extends BaseActivity implements MyListener {
private SQLiteDatabase db;
private List<Product> shopCarList;
private ListView listView;
private LinearLayout ll_back;
private LinearLayout ll_address;
private List<Address> addressList = new ArrayList<Address>();
private Gson gson = new Gson();
private TextView tv_receName;
private TextView tv_recePhone;
private TextView tv_receAddr;
private TextView tv_totalPrice;
private Button btn_sub;
private EditText et_liuyan;
private float totalPrice = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gwc);
//初始化数据表
db = UserDBOpenHelper.getInstance(this).getWritableDatabase();
listView = (ListView) findViewById(R.id.ll_gwc);
ll_back = (LinearLayout) findViewById(R.id.ll_back);
ll_address = (LinearLayout) findViewById(R.id.ll_address);
tv_receName = (TextView)findViewById(R.id.tv_receName);
tv_recePhone = (TextView) findViewById(R.id.tv_recePhone);
tv_receAddr = (TextView) findViewById(R.id.tv_receAddr);
tv_totalPrice = (TextView)findViewById(R.id.tv_totalPrice);
btn_sub = (Button)findViewById(R.id.btn_sub);
et_liuyan = (EditText) findViewById(R.id.et_liuyan);
shopCarList = (List<Product>)getIntent().getSerializableExtra("shopCarList");
if(shopCarList!=null) {
for (int i = 0; i < shopCarList.size(); i++) {
totalPrice = totalPrice+shopCarList.get(i).getPrice()*shopCarList.get(i).getNum();
}
tv_totalPrice.setText("¥"+String.valueOf(totalPrice));
ShopCarAdapter shopCarAdapter = new ShopCarAdapter(this,shopCarList,R.layout.gwc_list_items, MyApplication.getmQueue());
listView.setAdapter(shopCarAdapter);
}else{
shopCarList = gson.fromJson(UserDAO.find(db,UserInfo.getInstance().getUid()),new TypeToken<List<Product>>() {
}.getType());
if(shopCarList!=null){
for (int i = 0; i < shopCarList.size(); i++) {
totalPrice = totalPrice+shopCarList.get(i).getPrice()*shopCarList.get(i).getNum();
}
tv_totalPrice.setText("¥"+String.valueOf(totalPrice));
ShopCarAdapter shopCarAdapter = new ShopCarAdapter(this,shopCarList,R.layout.gwc_list_items, MyApplication.getmQueue());
listView.setAdapter(shopCarAdapter);
}
}
ll_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
ll_address.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(GwcActivity.this,AddressActivity.class);
i.putExtra("TAG","GWC");
startActivity(i);
finish();
}
});
btn_sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(UserInfo.getInstance()==null){
return;
}
else if(shopCarList.size()<=0){
LogUtils.e("shopCarList", "null");
Toast toast = Toast.makeText(GwcActivity.this, "你的购物车为空,请添加商品", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
return ;
}else if(tv_receAddr.getText().toString().equals("")
||tv_recePhone.getText().toString().equals("")
||tv_receName.getText().toString().equals("")){
Toast toast = Toast.makeText(GwcActivity.this,"请填写收货信息",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
return ;
}
btn_sub.setClickable(false);
final ProgressDialog progressDialog = new ProgressDialog(GwcActivity.this);
progressDialog.setMessage("提交中");
progressDialog.setCancelable(true);
progressDialog.show();
Map<String, String> map = new HashMap<String, String>();
List<IdNum> idNumList = new ArrayList<IdNum>();
for(Product p:shopCarList){
IdNum idNum = new IdNum();
idNum.setId(p.getPid());
idNum.setNum(p.getNum());
idNumList.add(idNum);
}
OrderJson orderJson = new OrderJson(UserInfo.getInstance().getUid(),tv_receName.getText().toString()+";"
+tv_recePhone.getText().toString()+";"
+tv_receAddr.getText().toString(),et_liuyan.getText().toString(),idNumList);
LogUtils.e("orderJson", gson.toJson(orderJson));
map.put("order", gson.toJson(orderJson));
map.put("uid", String.valueOf(UserInfo.getInstance().getUid()));
map.put("token", UserInfo.getInstance().getToken());
HttpUtils.request(GwcActivity.this, Config.INSERTORDER_URL, GwcActivity.this, map, Config.INSERTORDER_TAG);
progressDialog.dismiss();
}
});
}
@Override
protected void onStart() {
super.onStart();
if (getIntent().getSerializableExtra("address") != null) {
Address address = (Address) getIntent().getSerializableExtra("address");
tv_receAddr.setText(address.getReceAddr());
tv_recePhone.setText(address.getRecePhone());
tv_receName.setText(address.getReceName());
} else {
addressList = gson.fromJson(UserDAO.findAddress(db, UserInfo.getInstance().getUid()),
new TypeToken<List<Address>>() {
}.getType());
if (addressList != null&&addressList.size()!=0) {
tv_receAddr.setText(addressList.get(0).getReceAddr());
tv_recePhone.setText(addressList.get(0).getRecePhone());
tv_receName.setText(addressList.get(0).getReceName());
}
}
}
@Override
protected void onStop() {
super.onStop();
MyApplication.getmQueue().cancelAll(Config.INSERTORDER_TAG);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void dataController(String response, int tag) {
switch (tag){
case Config.INSERTORDER_TAG:
LogUtils.e("data", response);
UserDAO.update(db, UserInfo.getInstance().getUid(), "");
Toast toast = Toast.makeText(GwcActivity.this,"提交成功",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
Intent i = new Intent(GwcActivity.this,MainActivity.class);
i.putExtra("TAG", "ClearGWC");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
break;
}
}
@Override
public void requestError(String error) {
btn_sub.setClickable(true);
}
}
|
package jc.sugar.JiaHui.exception;
/**
* @Code 谢良基 2021/7/1
*/
public class SugarJMXException extends Exception{
public SugarJMXException(String message){
super(message);
}
public SugarJMXException(Throwable throwable){
super(throwable);
}
public SugarJMXException(){
}
public SugarJMXException(String message, Throwable throwable){
super(message, throwable);
}
public SugarJMXException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace){
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package com.lambton;
public class Arithmetic
{
int add(int a, int b)
{
return a + b;
}
float add(float a, float b)
{
return a + b;
}
String add(String a, String b)
{
return a + b;
}
String add(String a, int b)
{
return a + b;
}
String add(int a, String b)
{
return a + b;
}
int add(int a, int b , int c)
{
return a + add(b, c);
}
float add(int a, int b, float c)
{
return (float)add(a, b) + c;
}
float add(float a, int b)
{
return a + b;
}
float add(float a, int b, int c)
{
return a + (float)add(b,c);
}
String add(String a, int b, float c)
{
return a + add(b, c);
}
double add(int a, double b)
{
return a + b;
}
float add(int a, float b)
{
return a + b;
}
}
|
package exercise_chapter4;
public class FormatDemo {
public static void main(String[] args) {
System.out.printf("%-10s%-10s%-10s%-10s%-10s\n", "degrees","radians",
"sine" , "cosine" , "tangent");
int degree = 30;
double radians = Math.toRadians(degree);
System.out.printf("%-10d%-10.4f%-10.4f%-10.4f%-10.4f", degree,
radians , Math.sin(radians) , Math.cos(radians) , Math.tan(radians));
}
}
|
import java.awt.event.KeyEvent;
import java.io.*;
// Die Steuerung für alle Spieler
public abstract class steuerung {
//
public static int[][] keys = null;
// Aufzählung der Spieler
public static final int P1 = 0;
public static final int P2 = 1;
public static final int P3 = 2;
public static final int P4 = 3;
// Aufzählung der Stuerungselemente
public static final int UP = 0;
public static final int DOWN = 1;
public static final int LEFT = 2;
public static final int RIGHT = 3;
public static final int BOMB = 4;
// Steuerung öffnen
public static void InitConrols(){
// erstelle ein Objekt:
File file = new File("BomberKeyConfig.dat");
// wenn file nicht exestiert
if (!file.exists())
{
// DefaultFile erstellen
createDefaultFile();
// erneut versuchen es zu öffnen
openFile();
}
}
// öffne konfiguration
public static boolean openFile() {
//
boolean result = true;
// versuche File zu öffnen
try {
// Fileinput um Datei zu lesen
FileInputStream fis = new FileInputStream("Bombermansteuerung.dat");
// durchläuft array keys
for(int i = 0; i < keys.length; i++){
for(int j = 0; j < keys[i].length; j++){
// lesen von gespeicherten tasten
keys[i][j] = fis.read();
}
}
// file schließen
fis.close();
}
// wenn etwas falsch läuft, setze result auf falsch
catch (Exception e) {
result = false;
}
// return result
return result;
}
// damit Tastenbelegung geändert werden kann
public static void writeFile() {
// versuche File zu erstellen
try {
// erstelle file objekt
FileOutputStream fos = new FileOutputStream("Bombermansteuerung.dat");
// schreibe file
for(int i = 0; i < keys.length; i++){
for(int j = 0; j < keys[i].length; j++){
// hier werden die tasten in die datei geschrieben die oben gelesen werden
fos.write(keys[i][j]);
}
}
// schließe file
fos.close();
}
catch (Exception e) { new ErrorDialog(e); }
}
// erstelle default file
public static void createDefaultFile() {
//
if (keys == null) keys = new int[4][5];
// Steuerng Spieler 1
keys[P1][UP] = KeyEvent.VK_W;
keys[P1][DOWN] = KeyEvent.VK_S;
keys[P1][LEFT] = KeyEvent.VK_A;
keys[P1][RIGHT] = KeyEvent.VK_D;
keys[P1][BOMB] = KeyEvent.VK_SPACE;
// Steuerung Spieler 2
keys[P2][UP] = KeyEvent.VK_UP;
keys[P2][DOWN] = KeyEvent.VK_DOWN;
keys[P2][LEFT] = KeyEvent.VK_LEFT;
keys[P2][RIGHT] = KeyEvent.VK_RIGHT;
keys[P2][BOMB] = KeyEvent.VK_NUMPAD0;
// Steuerung Spieler 3
keys[P3][UP] = KeyEvent.VK_I;
keys[P3][DOWN] = KeyEvent.VK_K;
keys[P3][LEFT] = KeyEvent.VK_J;
keys[P3][RIGHT] = KeyEvent.VK_L;
keys[P3][BOMB] = KeyEvent.VK_O;
// Steuerung Spieler 4
keys[P4][UP] = KeyEvent.VK_NUMPAD8;
keys[P4][DOWN] = KeyEvent.VK_NUMPAD5;
keys[P4][LEFT] = KeyEvent.VK_NUMPAD4;
keys[P4][RIGHT] = KeyEvent.VK_NUMPAD6;
keys[P4][BOMB] = KeyEvent.VK_NUMPAD9;
// schreibe file
writeFile();
}
}
|
package com.zero.votes.web;
import com.zero.votes.beans.UrlsPy;
import com.zero.votes.persistence.entities.Item;
import com.zero.votes.persistence.entities.ItemOption;
import com.zero.votes.persistence.entities.ItemType;
import com.zero.votes.persistence.entities.Poll;
import com.zero.votes.persistence.entities.PollState;
import com.zero.votes.persistence.entities.Token;
import com.zero.votes.persistence.entities.Vote;
import com.zero.votes.web.util.ZVotesUtils;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
@Named("votingController")
@SessionScoped
public class VotingController implements Serializable {
private Poll current;
private Token token;
@ManagedProperty(value = "#{param.results}")
private Map<String, Object> results;
@ManagedProperty(value = "#{param.abstentions}")
private Map<String, Object> abstentions;
@ManagedProperty(value = "#{param.freeTexts}")
private Map<String, Object> freeTexts;
@ManagedProperty(value = "#{param.freeTextDescriptions}")
private Map<String, Object> freeTextDescriptions;
@EJB
private com.zero.votes.persistence.PollFacade pollFacade;
@EJB
private com.zero.votes.persistence.VoteFacade voteFacade;
@EJB
private com.zero.votes.persistence.TokenFacade tokenFacade;
@EJB
private com.zero.votes.persistence.ItemOptionFacade itemOptionFacade;
@EJB
private com.zero.votes.persistence.ParticipantFacade participantFacade;
@Inject
private com.zero.votes.web.TokenController tokenController;
public VotingController() {
}
public String prepareVoting(Poll poll, Token token) {
this.current = poll;
this.token = token;
results = new HashMap<>();
abstentions = new HashMap<>();
freeTexts = new HashMap<>();
freeTextDescriptions = new HashMap<>();
for (Item item : current.getItems()) {
abstentions.put(item.getId().toString(), Boolean.TRUE);
for (ItemOption itemOption : item.getOptions()) {
results.put(itemOption.getId().toString(), Boolean.FALSE);
}
}
return getCurrentPollUrl();
}
private String getCurrentPollUrl() {
String tokenId;
String currentId;
if (token != null) {
tokenId = token.getId().toString();
} else {
tokenId = "";
}
if (current != null) {
currentId = current.getId().toString();
} else {
currentId = "";
}
return UrlsPy.POLL.getUrl(false)+"?token="+tokenId+"&poll="+currentId;
}
public Poll getCurrent() {
return current;
}
public void setCurrent(Poll current) {
this.current = current;
}
public String abstainAll() {
for (Item item : current.getItems()) {
abstentions.remove(item.getId().toString());
abstentions.put(item.getId().toString(), Boolean.TRUE);
for (ItemOption itemOption : item.getOptions()) {
results.remove(itemOption.getId().toString());
results.put(itemOption.getId().toString(), Boolean.FALSE);
}
}
return this.submit();
}
public String submit() {
if (this.token == null) {
ZVotesUtils.addInternationalizedWarnMessage("NoValidTokenActive");
return getCurrentPollUrl();
}
if (this.token.isUsed()) {
ZVotesUtils.addInternationalizedWarnMessage("TokenAlreadyUsed");
return getCurrentPollUrl();
}
for (Item item : current.getItems()) {
int votes = 0;
for (ItemOption itemOption : item.getOptions()) {
if (results.get(itemOption.getId().toString()) == Boolean.TRUE) {
votes++;
}
}
if (item.isOwnOptions()) {
for (int i = 1; i <= this.getMaxOptions(item); i++) {
String freeTextId = item.getId().toString()+"_"+Integer.toString(i);
if (results.get(freeTextId) == Boolean.TRUE) {
votes++;
}
String[] fieldNames = {"shortName", "item"};
Object[] values = {freeTexts.get(freeTextId), item};
if (itemOptionFacade.countBy(fieldNames, values) > 0) {
ZVotesUtils.addInternationalizedErrorMessage("ShortNameAlreadyUsed");
return getCurrentPollUrl();
}
}
}
if (votes > item.getM() && item.getType().equals(ItemType.M_OF_N)) {
return getCurrentPollUrl();
} else if (votes > 1 && !item.getType().equals(ItemType.M_OF_N)) {
return getCurrentPollUrl();
}
}
for (Item item : current.getItems()) {
if (abstentions.get(item.getId().toString()) == Boolean.TRUE) {
Vote vote = new Vote();
vote.setItem(item);
vote.setAbstention(true);
voteFacade.create(vote);
} else {
if (item.isOwnOptions()) {
for (int i = 1; i <= this.getMaxOptions(item); i++) {
String freeTextId = item.getId().toString()+"_"+Integer.toString(i);
if (results.get(freeTextId) == Boolean.TRUE) {
ItemOption itemOption = new ItemOption();
itemOption.setShortName((String) freeTexts.get(freeTextId));
itemOption.setDescription((String) freeTextDescriptions.get(freeTextId));
itemOption.setItem(item);
itemOptionFacade.create(itemOption);
Vote vote = new Vote();
vote.setItem(item);
vote.setItemOption(itemOption);
vote.setAbstention(false);
voteFacade.create(vote);
}
}
}
for (ItemOption itemOption : item.getOptions()) {
if (results.get(itemOption.getId().toString()) == Boolean.TRUE) {
Vote vote = new Vote();
vote.setItem(item);
vote.setItemOption(itemOption);
vote.setAbstention(false);
voteFacade.create(vote);
}
}
}
for (ItemOption itemOption : item.getOptions()) {
results.remove(itemOption.getId().toString());
results.put(itemOption.getId().toString(), Boolean.FALSE);
}
abstentions.remove(item.getId().toString());
abstentions.put(item.getId().toString(), Boolean.TRUE);
}
tokenController.markUsed(token);
if (current.isParticipationTracking()) {
token.getParticipant().setHasVoted(true);
participantFacade.edit(token.getParticipant());
}
updatePollState();
this.token = null;
this.current = null;
freeTexts = new HashMap<>();
freeTextDescriptions = new HashMap<>();
ZVotesUtils.addInternationalizedInfoMessage("Voted");
return UrlsPy.HOME.getUrl(true);
}
public String cancel() {
for (Item item : current.getItems()) {
for (ItemOption itemOption : item.getOptions()) {
results.remove(itemOption.getId().toString());
results.put(itemOption.getId().toString(), Boolean.FALSE);
}
abstentions.remove(item.getId().toString());
abstentions.put(item.getId().toString(), Boolean.TRUE);
}
freeTexts = new HashMap<>();
freeTextDescriptions = new HashMap<>();
this.token = null;
this.current = null;
return UrlsPy.TOKEN.getUrl(true);
}
public void updatePollState() {
if (!current.isPollFinished()) {
boolean finished;
PollState state_before = current.getPollState();
if (current.getEndDate().before(new Date())) {
finished = true;
} else {
finished = true;
for (Token token : current.getTokens()) {
if (!token.isUsed()) {
finished = false;
}
}
}
if (finished) {
current.setPollState(PollState.FINISHED);
pollFacade.edit(current);
} else if (!finished && !state_before.equals(PollState.VOTING)) {
current.setPollState(PollState.VOTING);
pollFacade.edit(current);
}
}
}
public int getMaxOptions(Item item) {
if (item.getType().equals(ItemType.M_OF_N)) {
return item.getM();
} else {
return 1;
}
}
public Map<String, Object> getResults() {
return results;
}
public void setResults(Map<String, Object> results) {
this.results = results;
}
public Map<String, Object> getAbstentions() {
return abstentions;
}
public void setAbstentions(Map<String, Object> abstentions) {
this.abstentions = abstentions;
}
public Map<String, Object> getFreeTexts() {
return freeTexts;
}
public void setFreeTexts(Map<String, Object> freeTexts) {
this.freeTexts = freeTexts;
}
public Map<String, Object> getFreeTextDescriptions() {
return freeTextDescriptions;
}
public void setFreeTextDescriptions(Map<String, Object> freeTextDescriptions) {
this.freeTextDescriptions = freeTextDescriptions;
}
public void checkForInstance() throws IOException {
HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
if (req.getParameter("token") != null && !req.getParameter("token").isEmpty()) {
token = tokenFacade.find(Long.valueOf(req.getParameter("token")));
} else {
token = null;
}
if (req.getParameter("poll") != null && !req.getParameter("poll").isEmpty()) {
current = pollFacade.find(Long.valueOf(req.getParameter("poll")));
} else {
current = null;
}
if (current == null) {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect("/token/");
}
}
}
|
package tictactoe;
public class GameState {
private final Status status;
private final Player nextUp;
public GameState(Status status, Player nextUp) {
this.status = status;
this.nextUp = nextUp;
}
@Override
public String toString() {
return "Status: " + status + ", nextUp: "+ nextUp ;
}
@Override
public boolean equals(Object obj) {
return obj instanceof GameState && ((GameState) obj).status == this.status && ((GameState) obj).nextUp == this.nextUp;
}
}
|
package com.yusun.eurekaclientuserservice.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author SunYu
* @date 2019/8/31 21:17
*/
@RestController
public class UserController {
@GetMapping("/user/hello")
public String hello(){
return "hello";
}
}
|
package com.service;
import com.domain.CurrentUser;
import com.domain.Customer;
import com.domain.Reservation;
import com.repository.ReservationRepository;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
/**
* Created by Michał on 2016-12-18.
*/
@Named
public class ReservationServiceImpl implements ReservationService {
@Inject
private ReservationRepository reservationRepository;
@Inject
private CustomerService customerService;
public Set<Reservation> findReservationsByCustomerId(Long customerId) {
return reservationRepository.findReservationsByCustomerId(customerId);
}
@Override
public void delete(Long id) {
reservationRepository.delete(id);
}
@Override
public Reservation findReservationByReservationCode(String reservationCode) {
return reservationRepository.findReservationByReservationCode(reservationCode);
}
@Override
public boolean canDeletedReservation(CurrentUser currentUser, Long reservationId) {
if (areNotNull(currentUser, reservationId)) {
Customer customer = customerService.findCustomerByUserId(currentUser.getId());
Set<Reservation> reservations = findReservationsByCustomerId(customer.getId());
if (containsReservationWithId(reservationId, reservations)) {
return true;
}
}
return false;
}
private boolean areNotNull(CurrentUser currentUser, Long reservationId) {
return Objects.nonNull(currentUser) && Objects.nonNull(reservationId);
}
private boolean containsReservationWithId(Long reservationId, Set<Reservation> reservations) {
return reservations.stream()
.anyMatch(hasEqualId(reservationId));
}
private Predicate<Reservation> hasEqualId(Long reservationId) {
return reservation -> reservation.getId().equals(reservationId);
}
}
|
package sqlServer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import model.Genero;
import services.Logica;
public class GeneroQuery {
public static void loadGenero(){
String genero = "SELECT genero_id, genero_nome FROM Genero WHERE genero_estado = 1";
try {
Connection conn = Coneccao.getConnection();
Statement st = conn.createStatement();
ResultSet rs;
rs = st.executeQuery(genero);
while ( rs.next() ) {
Logica.arGeneros.add(new Genero(rs.getInt("genero_id"), rs.getString("genero_nome")));
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
public static int addGenero(String genero_nome) {
try {
Connection conn = Coneccao.getConnection();
Statement st = conn.createStatement();
st.executeUpdate(
"INSERT INTO Genero(genero_nome)"
+ " VALUES ('" + Coneccao.cleanQuery(genero_nome) + "')");
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
//-----------------------//-----------------------//
String user = "SELECT MAX(genero_id) AS max_id FROM Genero"; //Query para ir buscar o ID maximo da tabela Genero
try {
Connection conn = Coneccao.getConnection();
Statement st = conn.createStatement();
ResultSet rs;
rs = st.executeQuery(user);
while(rs.next()) {
if(rs.getInt("max_id") >= 1) { //Se o ID retornado pela query for maior ou igual a 1, este metodo ira retornar esse valor mais um
return rs.getInt("max_id")+1;
}else { //Caso contrario ira retornar 1
return 1;
}
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! TemaQuerys.load()");
System.err.println(e.getMessage());
}
return 0;
}
public static void editGenero(int genero_id, String genero_nome){
try {
Connection conn = Coneccao.getConnection();
Statement st = conn.createStatement();
st.executeUpdate(
"UPDATE Genero"
+ " SET genero_nome = '" + Coneccao.cleanQuery(genero_nome) + "'"
+ " WHERE genero_id = " + Integer.parseInt(Coneccao.cleanQuery(Integer.toString(genero_id))) + "");
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
public static void delGenero(int genero_id){
try {
Connection conn = Coneccao.getConnection();
Statement st = conn.createStatement();
st.executeUpdate(
"UPDATE Genero"
+ " SET genero_estado = 0"
+ " WHERE genero_id = " + Integer.parseInt(Coneccao.cleanQuery(Integer.toString(genero_id))) + "");
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_15591_MoonTube{
private static int N,Q;
private static List<Edge>[] adlist;
private static boolean[] visited;
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
Q = Integer.parseInt(st.nextToken());
adlist = new ArrayList[N];
for (int i = 0; i < N; i++) {
adlist[i] = new ArrayList<>();
}
for (int i = 0; i < N-1; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
int u = Integer.parseInt(st.nextToken());
adlist[a].add(new Edge(b, u));
adlist[b].add(new Edge(a, u));
}
for (int i = 0; i < Q; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int s= Integer.parseInt(st.nextToken())-1;
visited = new boolean[N];
Queue<Integer> queue = new LinkedList<>();
queue.offer(s);
visited[s] = true;
int ans = 0;
while(!queue.isEmpty()) {
int q = queue.poll();
for (int j = 0; j < adlist[q].size(); j++) {
Edge next = adlist[q].get(j);
if(!visited[next.x] && next.v >= u) {
visited[next.x] = true;
queue.offer(next.x);
ans++;
}
}
}
sb.append(ans + "\n");
}
System.out.println(sb);
}
public static class Edge{
int x,v;
public Edge(int x, int v) {
super();
this.x = x;
this.v = v;
}
}
}
|
package com.framework.model;
import java.util.*;
import com.baomidou.mybatisplus.annotations.TableName;
@TableName("act_re_model")
public class ActReModel {
/**
*主键ID
*/
private String id;
/**
*
*/
private Integer rev;
/**
*名称
*/
private String name;
/**
*编码
*/
private String key;
/**
*类型
*/
private String category;
/**
*创建时间
*/
private Date createTime;
/**
*修改时间
*/
private Date lastUpdateTime;
/**
*版本
*/
private Integer version;
/**
*
*/
private String metaInfo;
/**
*部署ID
*/
private String deploymentId;
/**
*
*/
private String editorSourceValueId;
/**
*
*/
private String editorSourceExtraValueId;
/**
*
*/
private String tenantId;
public ActReModel() {
}
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
public Integer getRev(){
return this.rev;
}
public void setRev(Integer rev){
this.rev = rev;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public String getKey(){
return this.key;
}
public void setKey(String key){
this.key = key;
}
public String getCategory(){
return this.category;
}
public void setCategory(String category){
this.category = category;
}
public Date getCreateTime(){
return this.createTime;
}
public void setCreateTime(Date createTime){
this.createTime = createTime;
}
public Date getLastUpdateTime(){
return this.lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime){
this.lastUpdateTime = lastUpdateTime;
}
public Integer getVersion(){
return this.version;
}
public void setVersion(Integer version){
this.version = version;
}
public String getMetaInfo(){
return this.metaInfo;
}
public void setMetaInfo(String metaInfo){
this.metaInfo = metaInfo;
}
public String getDeploymentId(){
return this.deploymentId;
}
public void setDeploymentId(String deploymentId){
this.deploymentId = deploymentId;
}
public String getEditorSourceValueId(){
return this.editorSourceValueId;
}
public void setEditorSourceValueId(String editorSourceValueId){
this.editorSourceValueId = editorSourceValueId;
}
public String getEditorSourceExtraValueId(){
return this.editorSourceExtraValueId;
}
public void setEditorSourceExtraValueId(String editorSourceExtraValueId){
this.editorSourceExtraValueId = editorSourceExtraValueId;
}
public String getTenantId(){
return this.tenantId;
}
public void setTenantId(String tenantId){
this.tenantId = tenantId;
}
}
|
package com.nfc;
import android.widget.Toast;
/**
* Created by acer on 14-6-4.
*/
public class NfcLunce {
public static String name,company,phone,email,profession;
public NfcLunce() {
}
public static void lunceSet(String str) {
int nameIndex = str.indexOf("name");
int phoneIndex = str.indexOf("phone");
int companyIndex = str.indexOf("company");
int emailIndex = str.indexOf("email");
int professionIndex = str.indexOf("profession");
NfcLunce.name = find(nameIndex, "name", str);
NfcLunce.phone = find(phoneIndex, "phone", str);
NfcLunce.company = find(companyIndex, "company", str);
NfcLunce.email = find(emailIndex, "email", str);
NfcLunce.profession = find(professionIndex, "profession", str);
// 还一个冒号
}
public static String find(int index, String tmp, String str) {
index += tmp.length()+1;
String ans = "";
for (int i = index; i < str.length(); i++) {
if (str.charAt(i) == ';')
break;
ans += str.charAt(i);
}
System.out.println(ans);
return ans;
}
// public static void main(String args[]) {
// NfcLunce text = new NfcLunce();
// text.lunceSet("name:1;phone:2;company:3;email:4;profession:5");
// }
}
|
package dino.command;
import dino.exception.*;
import dino.task.TaskList;
import dino.util.Storage;
/**
* Contains a set of instructions that can be understood and executed by the ChatBot
*/
public abstract class Command {
abstract public String execute(Storage storage, TaskList taskList) throws InvalidFormatException, TimeNotSpecifiedException, EmptyTaskDescriptionException, InvalidIndexException, TaskAlreadyDoneException, InvalidInputException, IndexNotSpecifiedException, EmptyListException, TaskNotFoundException;
}
|
//package com.github.quark.mongo.component;
//
//import com.github.quark.mongo.model.Person;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
//import org.springframework.stereotype.Component;
//
//import javax.annotation.PostConstruct;
//import java.util.concurrent.CountDownLatch;
//
//import static org.springframework.data.mongodb.core.query.Criteria.where;
//import static org.springframework.data.mongodb.core.query.Query.query;
//import static org.springframework.data.mongodb.core.query.Update.update;
//
///**
// * @author shihuaguo
// * @email huaguoshi@gmail.com
// * @date 2019-05-14
// **/
//@Component
//@Slf4j
//public class MongoOps {
// @Autowired
// private ReactiveMongoTemplate mongoTemplate;
//
// @PostConstruct
// public void init(){
// new Thread(() -> {
// try {
// init0();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }).start();
// }
//
// private void init0() throws InterruptedException {
// CountDownLatch latch = new CountDownLatch(1);
// mongoTemplate.insert(new Person("monday", 30))
// .doOnNext(person -> log.info("insert:{}", person))
// .flatMap(person -> mongoTemplate.findById(person.getId(), Person.class))
// .doOnNext(person -> log.info("found: " + person))
// .zipWith(mongoTemplate.updateFirst(query(where("name").is("monday")), update("age", 40), Person.class))
// .flatMap(tuple -> mongoTemplate.remove(tuple.getT1()))
// .flatMapMany(dr -> mongoTemplate.findAll(Person.class))
// .count().doOnSuccess(count -> {
// log.info("Number of people: " + count);
// latch.countDown();
// }).subscribe(t -> latch.countDown());
// log.info("Count Down latch await...");
// latch.await();
// log.info("Count Down latch await finish");
// }
//}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class alq extends a {
public String bWP;
public int huV;
public String hwg;
public String hyz;
public alp rIy;
public boolean rOf;
protected final int a(int i, Object... objArr) {
int h;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.hwg != null) {
aVar.g(1, this.hwg);
}
if (this.hyz != null) {
aVar.g(2, this.hyz);
}
if (this.bWP != null) {
aVar.g(3, this.bWP);
}
aVar.av(4, this.rOf);
aVar.fT(5, this.huV);
if (this.rIy == null) {
return 0;
}
aVar.fV(6, this.rIy.boi());
this.rIy.a(aVar);
return 0;
} else if (i == 1) {
if (this.hwg != null) {
h = f.a.a.b.b.a.h(1, this.hwg) + 0;
} else {
h = 0;
}
if (this.hyz != null) {
h += f.a.a.b.b.a.h(2, this.hyz);
}
if (this.bWP != null) {
h += f.a.a.b.b.a.h(3, this.bWP);
}
h = (h + (f.a.a.b.b.a.ec(4) + 1)) + f.a.a.a.fQ(5, this.huV);
if (this.rIy != null) {
h += f.a.a.a.fS(6, this.rIy.boi());
}
return h;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
alq alq = (alq) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
switch (intValue) {
case 1:
alq.hwg = aVar3.vHC.readString();
return 0;
case 2:
alq.hyz = aVar3.vHC.readString();
return 0;
case 3:
alq.bWP = aVar3.vHC.readString();
return 0;
case 4:
alq.rOf = aVar3.cJQ();
return 0;
case 5:
alq.huV = aVar3.vHC.rY();
return 0;
case 6:
LinkedList IC = aVar3.IC(intValue);
int size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
byte[] bArr = (byte[]) IC.get(intValue);
alp alp = new alp();
f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (boolean z = true; z; z = alp.a(aVar4, alp, a.a(aVar4))) {
}
alq.rIy = alp;
}
return 0;
default:
return -1;
}
}
}
}
|
package com.techelevator.bank;
import java.math.BigDecimal;
public class BankTeller {
public static void main (String[] args) {
BankAccount checkingAccount = new CheckingAccount();
BankAccount savingsAccount = new SavingsAccount();
BankCustomer jayGatsby = new BankCustomer();
jayGatsby.addAccount(checkingAccount);
jayGatsby.addAccount(savingsAccount);
BigDecimal amountToDeposit = new BigDecimal("24000");
savingsAccount.deposit(amountToDeposit);
//BigDecimal amountToWithdraw = new BigDecimal("4");
System.out.println(String.format("Jay Gatsby has %s accounts.", jayGatsby.getAccounts().length));
System.out.println("Checking before: " + savingsAccount.getBalance() +" "+jayGatsby.isVip() );
//savingsAccount.withdraw(amountToWithdraw);
//System.out.println("Checking after: " + savingsAccount.getBalance());
}
}
|
package com.baixiaowen.javaconcurrencyprogramming.singleton单例模式8种写法;
/**
* 描述: 懒汉式(线程不安全) [不可用]
*/
public class Singleton懒汉式同步代码块线程不安全5 {
private static Singleton懒汉式同步代码块线程不安全5 instance;
private Singleton懒汉式同步代码块线程不安全5(){}
public static Singleton懒汉式同步代码块线程不安全5 getInstance(){
// 俩个线程同时走过这条if语句, 还是会创建俩个实例,所以它是线程不安全的
if (instance == null){
synchronized (Singleton懒汉式同步代码块线程不安全5.class){
instance = new Singleton懒汉式同步代码块线程不安全5();
}
}
return instance;
}
}
|
package agent2;
/**
* @author bipin khatiwada
* github.com/bipinkh
*/
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.InetAddress;
import utils.UdpMessageService;
import org.ice4j.ice.Agent;
import org.ice4j.ice.CandidatePair;
import org.ice4j.ice.Component;
import org.ice4j.ice.IceMediaStream;
import org.ice4j.ice.IceProcessingState;
public class StateListener2 implements PropertyChangeListener {
private InetAddress hostname;
int port;
@Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getSource() instanceof Agent){
Agent agent = (Agent) evt.getSource();
System.out.println("Agent state changed to " + agent.getState());
if(agent.getState().equals(IceProcessingState.TERMINATED)) {
System.out.println("Agent Connected");
for (IceMediaStream stream: agent.getStreams()) {
if (stream.getName().contains("audio")) {
Component rtpComponent = stream.getComponent(org.ice4j.ice.Component.RTP);
CandidatePair rtpPair = rtpComponent.getSelectedPair();
/*** lets listen for the packet now ***/
byte[] msg = UdpMessageService.receiveMessage(rtpPair);
System.out.println("agent1 says :: "+ new String(msg));
/*** lets send the reply ***/
UdpMessageService.sendMessage(rtpPair, "yes, i am listening".getBytes());
}
}
}
}
}
}
|
package a2lend.app.com.a2lend;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pub.devrel.easypermissions.EasyPermissions;
import static android.app.Activity.RESULT_OK;
import static android.content.Context.LOCATION_SERVICE;
/**
* Created by Igbar on 1/27/2018.
*/
public class MySupport {
private static final int RC_TAKE_PICTURE = 101;
private static final int RC_STORAGE_PERMS = 102;
//--|
public static ProgressDialog showProgressDialog(Context context , String title , String Message ,int Style) {
ProgressDialog mProgressDialog = new ProgressDialog(context);
mProgressDialog.setTitle(title);
mProgressDialog.setMessage(Message);
mProgressDialog.setIndeterminate(true);
return mProgressDialog;
}
//--|
public static boolean hideProgressDialog(ProgressDialog mProgressDialog) {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
return true;
}
return false;
}
public static void showMessageDialog(Context context ,String title, String message) {
AlertDialog ad = new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.create();
ad.show();
}
//--|
public static File createFileAboutExternalStorage(String dirName,String fileName){
File dir = new File(Environment.getExternalStorageDirectory() + "/"+ fileName);
File file = new File(dir, fileName + "__" +UUID.randomUUID().toString() + ".jpg");
try {
// Create directory if it does not exist.
if (!dir.exists()) {
dir.mkdir();
}
boolean created = file.createNewFile();
if(created ==false)
return null;
Log.d("MySupport-Storage", "file.createNewFile:" + file.getAbsolutePath() + ":" + created);
} catch (IOException e) {
Log.e("MySupport-Storage", "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
}
return file;
}
// //--| firebase Package
public static Uri getFileUri(Context context,File file){
// Create content:// URI for file, required since Android N
// See: https://developer.android.com/reference/android/support/v4/content/FileProvider.html
String firebasePackage = "com.firebase.abo3le.firebasehelloworld.fileprovider";
return FileProvider.getUriForFile(context, firebasePackage , file);
}
public static void RotitColor(final ImageButton but){
but.setBackgroundColor(Color.RED);
}
//--|
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public static boolean goToFragment(Fragment fragment, FragmentActivity activity){
try {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace((R.id.fragment),fragment);
fragmentTransaction.commit();
if(fragment != new HomeFragment()) {
HomePageActivity.frameLayout.setVisibility(View.GONE);
HomePageActivity.layoutButtons.setVisibility(View.GONE);
}else {
HomePageActivity.frameLayout.setVisibility(View.VISIBLE);
HomePageActivity.layoutButtons.setVisibility(View.VISIBLE);
}
return true;
}catch (Exception e ){
return false;
}
}
public static Location getlocation(FragmentActivity fragmentActivity) {
Location myLocation = null;
try {
LocationManager locationManager = (LocationManager) fragmentActivity.getSystemService(LOCATION_SERVICE);
if (locationManager != null) {
if (ActivityCompat.checkSelfPermission(fragmentActivity, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(fragmentActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(fragmentActivity, "Location Permission Denied", Toast.LENGTH_SHORT).show();
return null;
}
myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
}
}
catch (Exception ex){
}
return myLocation;
}
//--|
public static void launchCamera(FragmentActivity fragmentActivity) {
final String TAG = "launchCamera";
Log.d(TAG, "Start");
//@AfterPermissionGranted(RC_STORAGE_PERMS)
final String AUTHORITY = "com.firebase.abo3le.firebasehelloworld.fileprovider";
final String permissionWrite = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
final String rationale_storage_message = "This sample reads images from your camera to demonstrate uploading.";
final int RC_STORAGE_PERMS =102;
//region Permissions - Check that we have permission to read images from external storage.
if (!EasyPermissions.hasPermissions(fragmentActivity, permissionWrite)) {
EasyPermissions.requestPermissions(fragmentActivity, rationale_storage_message,RC_STORAGE_PERMS, permissionWrite );
return;
}
//endregion
//region Choose file storage location, must be listed in res/xml/file_paths.xml
String ImageName = UUID.randomUUID().toString();
File dir = new File(Environment.getExternalStorageDirectory() + "/photos");
File file = new File(dir, ImageName + ".jpg");
try {
boolean created = file.createNewFile();
Log.d(TAG, "file.createNewFile:"+ Environment.getExternalStorageDirectory() + file.getAbsolutePath() + ":" + created);
// Create directory if it does not exist.
if (!dir.exists()) {
dir.mkdir();
}
} catch (IOException e) {
Log.e(TAG, "file.createNewFile" + file.getAbsolutePath() + ":FAILED", e);
}
//endregion
//region Create content:// URI for file
Uri mFileUri = FileProvider.getUriForFile(fragmentActivity, AUTHORITY, file);
//endregion
// Create and launch the intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
fragmentActivity.startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}
//--|
public static void hideKeyBoard(View view,FragmentActivity activity){
if (view != null) {
InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
|
/*
* 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 teg.model;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* @author HTC
*/
public class Paragraph {
public String text="";
public ObservableList<HyperLink> hyperlinks;
public Font font;
public Paragraph(String initText){
text = initText;
this.hyperlinks = FXCollections.observableArrayList();
this.font = new Font();
}
public void addHyperLink(String initStartIndex, String initEndIndex, String initLink, String initText){
HyperLink hy = new HyperLink(initStartIndex, initEndIndex, initLink,initText);
hyperlinks.add(hy);
}
@Override
public Object clone() throws CloneNotSupportedException{
Paragraph h = new Paragraph("");
h.text = this.text;
for(HyperLink hy : this.hyperlinks){
h.hyperlinks.add(hy);
}
h.font = (Font) this.font.clone();
return h;
}
}
|
package com.stark;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Stark on 2017/10/30.
* 方法区和运行常量池溢出
* -XX:PermSize=10M -XX:MaxPermSize=10M
* 这个在1.7开始逐步去永久代之后就没有再出现过了
*/
public class RuntimeConstantPoolOOM {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
int i=0;
while (true){
list.add(String.valueOf(i++).intern());// intern native方法 将字符串添加到常量池
}
}
}
|
package com.example.root.curriculum;
/**
* 保存软件的一些常量值
*/
public class Constants {
public static final String EX_URL = "http://www.wanandroid.com/article/list/0/json";
public static final String EX_URL_TEO = "http://gank.io/api/data/福利/10/1";
public static final String GIT_ADDRESS = "https://github.com/jiwenjie/CurriculumForAndroid";
public static boolean IS_LOGIN = false; //默认为未登录状态
}
|
package com.an.an_be.service;
import com.an.an_be.entity.User;
public interface UserService {
User findUser(User user);
}
|
package template.controller;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
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 org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import template.model.ReportDto;
import template.model.ReportResultDto;
import template.service.ReportService;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
class ReportControllerTest {
@Mock
private ReportService reportService;
@InjectMocks
private final ReportController reportController = new ReportController(reportService);
private static ReportDto reportDto;
private static QueryCriteria queryCriteria;
@BeforeAll
static void setData() {
reportDto = ReportDto.builder()
.id(1L)
.queryCriteriaCharacterPhrase("testCharacterPhrase")
.queryCriteriaPlanetName("testPlanetName")
.resultEntityList(
Arrays.asList(ReportResultDto.builder()
.filmId("1")
.filmName("testFilmName")
.characterId("2")
.characterName("testCharacterName")
.planetId("3")
.planetName("testPlanetName")
.build()
))
.build();
queryCriteria = new QueryCriteria("testCharacterPhrase", "testPlanetName");
}
@BeforeEach
void setMockOutput() {
lenient().when(reportService.getReportById(1L)).thenReturn(reportDto);
lenient().when(reportService.getAllReports()).thenReturn(Arrays.asList(reportDto));
}
@DisplayName("Test putReport + helloRepository")
@Test
void putReport() {
ResponseEntity report = reportController.putReport(1L, queryCriteria);
assertEquals(HttpStatus.NO_CONTENT, report.getStatusCode());
assertEquals(null, report.getBody());
}
@Test
void getReport() {
ResponseEntity report = reportController.getReport(1L);
assertEquals(HttpStatus.OK, report.getStatusCode());
assertEquals(reportDto, report.getBody());
}
@Test
void getAllReports() {
ResponseEntity report = reportController.getAllReports();
assertEquals(HttpStatus.OK, report.getStatusCode());
assertEquals(Arrays.asList(reportDto), report.getBody());
}
@Test
void deleteReport() {
ResponseEntity report = reportController.deleteReport(1L);
assertEquals(HttpStatus.OK, report.getStatusCode());
assertEquals(null, report.getBody());
}
@Test
void deleteAllReports() {
ResponseEntity report = reportController.deleteAllReports();
assertEquals(HttpStatus.OK, report.getStatusCode());
assertEquals(null, report.getBody());
}
}
|
package com.usnoozeulose.app.alarm.activities;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TabHost;
import com.usnoozeulose.app.alarm.R;
public class MainActivity extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
SharedPreferences sharedPrefs = getLocalActivityManager().getCurrentActivity().
getSharedPreferences("SHARED_PREFS", Context.MODE_PRIVATE);
String userId = sharedPrefs.getString("userId", null);
// userid does not exist
if (userId == null) {
// need to get login page
SharedPreferences.Editor sharedPrefsEditor = sharedPrefs.edit();
sharedPrefsEditor.putString("userId", "");
sharedPrefsEditor.apply();
}
*/
/* Alarm */
TabHost tabHost = getTabHost();
TabHost.TabSpec alarm = tabHost.newTabSpec("b");
alarm.setIndicator("Alarm List");
Intent alarmIntent = new Intent(this, AlarmActivity.class);
alarm.setContent(alarmIntent);
tabHost.addTab(alarm);
}
//Alarm-Clock/app/build/intermediates/transforms/instantRunSlicer/debug/folders/1/5/slice_0/com/usnoozeulose/app/alarm/AlarmListAdapter.class
}
|
package com.suhid.practice.controller;
import com.suhid.practice.dto.request.AddCourseRequest;
import com.suhid.practice.services.CourseService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/admin")
public class AdminController {
private final CourseService courseService;
public AdminController(CourseService courseService) {
this.courseService = courseService;
}
@PostMapping("/addcourse/")
public void AddCources(@RequestBody AddCourseRequest addCourseRequest){
courseService.AddCourse(addCourseRequest);
}
}
|
package com.wuyan.masteryi.admin.service;
/*
*project:master-yi
*file:Statistic
*@author:wsn
*date:2021/7/11 16:24
*/
import com.wuyan.masteryi.admin.entity.MonthlyData;
import com.wuyan.masteryi.admin.entity.OrderCount;
import com.wuyan.masteryi.admin.entity.Statistic;
import com.wuyan.masteryi.admin.entity.UserCateCount;
import com.wuyan.masteryi.admin.mapper.StatisticMapper;
import com.wuyan.masteryi.admin.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
@Service
public class StatisticServiceImpl implements StatisticService{
@Autowired
StatisticMapper statisticMapper;
@Override
public Map<String, Object> getBasicData() {
return ResponseMsg.sendMsg(200,"查询成功",
new Statistic(statisticMapper.getSalesNum(),statisticMapper.getEraningNum(),
statisticMapper.getVisitorNum(),statisticMapper.getUserNum(),statisticMapper.getOrderNum()));
}
@Override
public Map<String,Object> getOrderCount(){
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
List<OrderCount> orderCount = statisticMapper.getOrderCount();
for(OrderCount orderCount1:orderCount){
orderCount1.setF_date(sdf.format(orderCount1.getDate()));
orderCount1.setDate(null);
}
return ResponseMsg.sendMsg(200,"ok",orderCount);
}
@Override
public Map<String, Object> getMonthData() {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
List<MonthlyData> monthData = statisticMapper.getMonthData();
// for(MonthlyData monthlyData:monthData){
// monthlyData.setF_month(sdf.format(monthlyData.getCreateMonth()));
// }
return ResponseMsg.sendMsg(200,"ok",monthData);
}
@Override
public Map<String, Object> getTopGoods() {
return ResponseMsg.sendMsg(200,"ok",statisticMapper.getTopGoods());
}
@Override
public Map<String, Object> getUserCount() {
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
List<UserCateCount> userCateCount = statisticMapper.getUserCount();
for(UserCateCount userCateCount1 : userCateCount){
userCateCount1.setF_time(sdf.format(userCateCount1.getTime()));
userCateCount1.setTime(null);
}
return ResponseMsg.sendMsg(200,"ok", userCateCount);
}
@Override
public Map<String, Object> getCateCount() {
return ResponseMsg.sendMsg(200,"OK",statisticMapper.getCateCount());
}
}
|
package com.yixiu.advance.cloud.config.client;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
public class MyHealthIndicator extends AbstractHealthIndicator {
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
builder.up().withDetail("MyHealthIndicator","MyHealthIndicator Message Show Up!");
}
}
|
/*
* MIT License
*
* Copyright (c) 2018 Guillermo Facundo Colunga
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.weso.security.defender.client.connectors;
import java.util.Map;
import com.mashape.unirest.http.JsonNode;
/**
* The Interface MetadataEntryConnector.
*
* @author Guillermo Facundo Colunga
* @version 201806081225
*/
public interface MetadataEntryConnector {
/**
* Request toquen.
*
* @return the string
*/
public String requestToken();
/**
* Gets the metadata for token.
*
* @param token the token
* @return the metadata for token
*/
public JsonNode getMetadataForToken(String token);
/**
* Save metadata for token.
*
* @param token the token
* @param metadata the metadata
* @return the map
*/
public JsonNode saveMetadataForToken(String token, Map<String, Object> metadata);
}
|
package com.vladan.mymovies.ui;
import android.content.Context;
import com.vladan.mymovies.BuildConfig;
import com.vladan.mymovies.data.model.Movie;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.vladan.mymovies.R;
import java.util.List;
/**
* Created by Vladan on 10/16/2017.
*/
public class MoviesRecyclerAdapter extends RecyclerView.Adapter<MoviesRecyclerAdapter.ViewHolder> {
private List<Movie> listOfMovies;
private Context context;
private OnItemClicked mListener;
public MoviesRecyclerAdapter(List<Movie> listOfMovies, Context context, OnItemClicked listener) {
this.listOfMovies = listOfMovies;
this.context = context;
this.mListener = listener;
}
public interface OnItemClicked{
void onItemClicked(int position);
}
public void updateList(List<Movie> list){
listOfMovies = list;
notifyDataSetChanged();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.movies_adapter_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Movie movie = listOfMovies.get(position);
//binding data
holder.bind(movie.getPosterPath(), movie.getTitle(), movie.getOverview(), String.valueOf(movie.getVoteAverage()), movie.getGenreIds());
}
@Override
public int getItemCount() {
return listOfMovies.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView movieImg;
TextView movieName;
TextView movieOverview;
TextView movieRating;
TextView movieGenres;
View mView;
private ViewHolder(View itemView) {
super(itemView);
mView = itemView;
movieImg = itemView.findViewById(R.id.iv_recycler_item);
movieName = itemView.findViewById(R.id.tv_recycler_item_name);
movieOverview = itemView.findViewById(R.id.tv_recycler_item_overview);
movieGenres = itemView.findViewById(R.id.tv_recycler_item_genres);
movieRating = itemView.findViewById(R.id.tv_recycler_item_rating);
itemView.setOnClickListener(this);
}
void bind(String img, String name, String overview, String rating, List<Integer> list){
Picasso.with(context).load(BuildConfig.IMAGES_BASE_URL+img).into(movieImg);
movieName.setText(name);
movieOverview.setText(overview);
movieRating.setText(rating);
String genres = "";
for(int i=0; i<list.size(); i++){
int numb = list.get(i);
String genreName = "";
switch (numb){
case 28: genreName = "Action";
break;
case 12: genreName = "Adventure";
break;
case 16: genreName = "Animation";
break;
case 35: genreName = "Comedy";
break;
case 80: genreName = "Crime";
break;
case 99: genreName = "Documentary";
break;
case 18: genreName = "Drama";
break;
case 10751: genreName = "Family";
break;
case 14: genreName = "Fantasy";
break;
case 36: genreName = "History";
break;
case 27: genreName = "Horror";
break;
case 10402: genreName = "Music";
break;
case 9648: genreName = "Mystery";
break;
case 10749: genreName = "Romance";
break;
case 878: genreName = "Science Fiction";
break;
case 10770: genreName = "TV Movie";
break;
case 53: genreName = "Thriller";
break;
case 10752: genreName = "War";
break;
case 37: genreName = "Western";
break;
}
if(i==0){
genres += genreName;
} else {
genres += ", "+genreName;
}
}
movieGenres.setText(genres);
}
@Override
public void onClick(View view) {
int index = getAdapterPosition();
mListener.onItemClicked(index);
}
}
}
|
package com.example.myapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class FriendAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
ArrayList<String> names = null, emails = null, types = null;
public FriendAdapter(Context c, ArrayList<String> n, ArrayList<String> e, ArrayList<String> t) {
names = n;
emails = e;
types = t;
layoutInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return names == null? 0: names.size();
}
@Override
public Object getItem(int i) {
return names == null? null: names.size() > i? names.get(i): null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = layoutInflater.inflate(R.layout.friend_item_list, null);
TextView userNameTVFli = (TextView)v.findViewById(R.id.userNameTVFli);
userNameTVFli.setText(names.get(i));
TextView emailTVFli = (TextView)v.findViewById(R.id.emailTVFli);
emailTVFli.setText(emails.get(i));
TextView relationTVFli = (TextView)v.findViewById(R.id.relationTVFli);
relationTVFli.setText(types.get(i));
return v;
}
}
|
package com.claycorp.nexstore.api.model;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.data.mongodb.core.mapping.Document;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
@Document
public class OrderVo {
private String id;
private RefOrderStatusCodesVo statusCode;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime dateOfOrderPlaced;
private List<OrderItemVo> orderDetails;
public OrderVo() {
}
public String getId() {
return id;
}
public OrderVo setId(String id) {
this.id = id;
return this;
}
public RefOrderStatusCodesVo getStatusCode() {
return statusCode;
}
public OrderVo setStatusCode(RefOrderStatusCodesVo statusCode) {
this.statusCode = statusCode;
return this;
}
public LocalDateTime getDateOfOrderPlaced() {
return dateOfOrderPlaced;
}
public OrderVo setDateOfOrderPlaced(LocalDateTime dateOfOrderPlaced) {
this.dateOfOrderPlaced = dateOfOrderPlaced;
return this;
}
public List<OrderItemVo> getOrderDetails() {
return orderDetails;
}
public OrderVo setOrderDetails(List<OrderItemVo> orderDetails) {
this.orderDetails = orderDetails;
return this;
}
@Override
public String toString() {
return "Order [id=" + id + ", statusCode=" + statusCode + ", dateOfOrderPlaced=" + dateOfOrderPlaced
+ ", orderDetails=" + orderDetails + "]";
}
}
|
package techokami.computronics.block;
import net.minecraft.block.material.Material;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import techokami.computronics.Computronics;
import techokami.computronics.tile.TileIronNote;
import techokami.lib.block.BlockBase;
public class BlockIronNote extends BlockBase {
public BlockIronNote() {
super(Material.iron, Computronics.instance);
this.setCreativeTab(Computronics.tab);
this.setIconName("computronics:noteblock");
this.setBlockName("computronics.ironNoteBlock");
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileIronNote();
}
}
|
package ssh.eum;
public enum MRLock {
LOCKED, NOTLOCKED;
}
|
package plp.orientadaObjetos3.declaracao.constante;
import plp.orientadaObjetos1.expressao.leftExpression.Id;
import plp.orientadaObjetos1.expressao.valor.Valor;
import plp.orientadaObjetos1.memoria.AmbienteCompilacaoOO1;
import plp.orientadaObjetos1.util.Tipo;
import plp.orientadaObjetos3.memoria.AmbienteCompilacaoOO3;
import plp.orientadaObjetos3.memoria.AmbienteExecucaoOO3;
public class Constante {
private Id id;
private Tipo tipo;
private Valor valor;
public Constante(Id id, Tipo tipo, Valor valor) {
this.id = id;
this.tipo = tipo;
this.valor = valor;
}
public boolean checaTipo(AmbienteCompilacaoOO1 ambiente) {
boolean ret = false;
ret = valor.getTipo(ambiente).equals(tipo);
if (ret) {
((AmbienteCompilacaoOO3) ambiente).mapConstantes(id, tipo);
}
return ret;
}
public AmbienteExecucaoOO3 elabora(AmbienteExecucaoOO3 ambiente) {
ambiente.mapConstantes(id, valor);
return ambiente;
}
public Id getId() {
return id;
}
public Tipo getTipo() {
return tipo;
}
public Valor getValor() {
return valor;
}
}
|
package com.korea.seoul;
public class Tommy {
public int age = 25;
public void hello() {
System.out.println("Hello world!");
}
}
|
package ru.kstu.aec.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import ru.kstu.aec.models.User;
import static ru.kstu.aec.configs.SecurityConfig.getAuthentication;
import static ru.kstu.aec.configs.SecurityConfig.isTeacher;
@Controller
public class CourseTestController {
@GetMapping("/course-test")
public String courseTest(Model model) {
isTeacher(model);
model.addAttribute("name", ((User) getAuthentication().getPrincipal()).getFirstname());
model.addAttribute("surname", ((User) getAuthentication().getPrincipal()).getSurname());
return "test";
}
}
|
package com.unknown.game;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;
import com.unknown.game.helper.Const;
import com.unknown.game.helper.SetFullScreen;
public class MainActivity extends AppCompatActivity {
private boolean music;
private TextView tvNotificationStt;
private ImageView imgDowsie;
private CountDownTimer timerNotification;
private CountDownTimer timerDecrease;
private MediaPlayer mediaPlayer;
private MediaPlayer clickSound;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetFullScreen.hideSystemUI(getWindow()); //Set Fullscreen_Hide System UI
sharedPreferences = getSharedPreferences(Const.PET_INFORMATION, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
GetPetData();
SetIndexDecrease();
tvNotificationStt = findViewById(R.id.tvNotificationStt);
music = true;
SetSound();
mediaPlayer.start();
SetPetIndexChange();
imgDowsie = findViewById(R.id.imgDowsie);
AnimationDrawable animationDrawable = (AnimationDrawable) imgDowsie.getDrawable();
animationDrawable.start();
}
@Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
@Override
protected void onResume() {
super.onResume();
mediaPlayer.start();
SetFullScreen.hideSystemUI(getWindow());
}
@Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.pause();
}
public void btnIn4OnClick(View view) {
clickSound.start();
Intent intent = new Intent(MainActivity.this, PetIn4Activity.class);
intent.putExtra(Const.PET_NAME, sharedPreferences.getString(Const.PET_NAME, ""));
intent.putExtra(Const.PET_LEVEL, sharedPreferences.getFloat(Const.PET_LEVEL, 1f));
intent.putExtra(Const.PET_MONEY, sharedPreferences.getInt(Const.PET_MONEY, 0));
intent.putExtra(Const.PET_HUNGRY, sharedPreferences.getInt(Const.PET_HUNGRY, 0));
intent.putExtra(Const.PET_HEALTH, sharedPreferences.getInt(Const.PET_HEALTH, 0));
startActivity(intent);
}
public void btnSetVolumeOnClick(View view) {
clickSound.start();
if (music) {
view.setBackground(getDrawable(R.drawable.ic_mute));
music = !music;
Log.e("music", String.valueOf(music));
mediaPlayer.setVolume(0, 0);
clickSound.setVolume(0, 0);
}
else if (!music) {
view.setBackground(getDrawable(R.drawable.ic_volume));
music = !music;
Log.e("music", String.valueOf(music));
mediaPlayer.setVolume(1, 1);
clickSound.setVolume(1, 1);
}
}
public void btnStudyOnClick(View view) {
clickSound.start();
if (sharedPreferences.getInt(Const.PET_HUNGRY, 0) <= 10) {
SetTimeTextViewNotification("Đói lắm! Không học đâu!");
}
if (sharedPreferences.getInt(Const.PET_HEALTH, 0) <= 15) {
SetTimeTextViewNotification("Mệt lắm! Không học đâu!");
}
if (sharedPreferences.getInt(Const.PET_HUNGRY, 0) > 10 && sharedPreferences.getInt(Const.PET_HEALTH, 0) > 15) {
mediaPlayer.pause();
startActivity(new Intent(MainActivity.this, StudyActivity.class));
finish();
}
}
public void btnPlayOnClick(View view) {
clickSound.start();
if (sharedPreferences.getInt(Const.PET_HUNGRY, 0) <= 10) {
SetTimeTextViewNotification("Đói lắm! Không học đâu!");
}
if (sharedPreferences.getInt(Const.PET_HEALTH, 0) <= 15) {
SetTimeTextViewNotification("Mệt lắm! Không học đâu!");
}
if (sharedPreferences.getInt(Const.PET_HUNGRY, 0) > 10 && sharedPreferences.getInt(Const.PET_HEALTH, 0) > 15) {
mediaPlayer.pause();
startActivity(new Intent(MainActivity.this, GameActivity.class));
finish();
}
}
public void btnEatingOnClick(View view) {
clickSound.start();
if (sharedPreferences.getInt(Const.PET_MONEY, 0) >= 500) {
if (sharedPreferences.getInt(Const.PET_HUNGRY, 0) < 70) {
if (sharedPreferences.getInt(Const.PET_HUNGRY, 100) + 50 > 100) {
SetTimeTextViewNotification("Tiền: -500, " + "Độ no của " + sharedPreferences.getString(Const.PET_NAME, "") + " đã đầy");
editor.putInt(Const.PET_HUNGRY, 100);
editor.putInt(Const.PET_MONEY, sharedPreferences.getInt(Const.PET_MONEY, 100) - 500);
} else {
SetTimeTextViewNotification("Tiền: -500, Độ no + 50");
editor.putInt(Const.PET_HUNGRY, sharedPreferences.getInt(Const.PET_HUNGRY, 100) + 50);
editor.putInt(Const.PET_MONEY, sharedPreferences.getInt(Const.PET_MONEY, 100) - 500);
}
} else {
SetTimeTextViewNotification(sharedPreferences.getString(Const.PET_NAME, "") + " đã no bụng");
}
} else {
SetTimeTextViewNotification("Bạn không đủ tiền để mua thức ăn");
}
editor.apply();
}
public void btnHealingOnClick(View view) {
clickSound.start();
if (sharedPreferences.getInt(Const.PET_MONEY, 0) >= 1000) {
if (sharedPreferences.getInt(Const.PET_HEALTH, 0) < 70) {
if (sharedPreferences.getInt(Const.PET_HEALTH, 100) + 50 > 100) {
SetTimeTextViewNotification("Tiền: -1000, " + "Sức khỏe của " + sharedPreferences.getString(Const.PET_NAME, "") + " đã hồi phục");
editor.putInt(Const.PET_HEALTH, 100);
editor.putInt(Const.PET_MONEY, sharedPreferences.getInt(Const.PET_MONEY, 100) - 1000);
} else {
SetTimeTextViewNotification("Tiền: -1000, Độ no + 50");
editor.putInt(Const.PET_HEALTH, sharedPreferences.getInt(Const.PET_HEALTH, 100) + 50);
editor.putInt(Const.PET_MONEY, sharedPreferences.getInt(Const.PET_MONEY, 100) - 1000);
}
} else {
SetTimeTextViewNotification(sharedPreferences.getString(Const.PET_NAME, "") + " đang rất khỏe!");
}
} else {
SetTimeTextViewNotification("Bạn không đủ tiền để mua thuốc");
}
editor.apply();
}
private void GetPetData() {
if (sharedPreferences.getString(Const.PET_NAME, "") == "") {
editor.putString(Const.PET_NAME, getIntent().getStringExtra(Const.PET_NAME));
}
if (sharedPreferences.getFloat(Const.PET_LEVEL, -1) == -1) {
editor.putFloat(Const.PET_LEVEL, 1f);
}
if (sharedPreferences.getInt(Const.PET_MONEY, -1) == -1) {
editor.putInt(Const.PET_MONEY, 20000);
}
if (sharedPreferences.getInt(Const.PET_HUNGRY, -1) == -1) {
editor.putInt(Const.PET_HUNGRY, 100);
}
if (sharedPreferences.getInt(Const.PET_HEALTH, -1) == -1) {
editor.putInt(Const.PET_HEALTH, 100);
}
editor.apply();
}
private void SetTimeTextViewNotification(String str) {
if (timerNotification != null) {
timerNotification.onFinish();
}
timerNotification = new CountDownTimer(10000,1000) {
@Override
public void onTick(long millisUntilFinished) {
tvNotificationStt.setText(str);
tvNotificationStt.setVisibility(View.VISIBLE);
}
@Override
public void onFinish() {
timerNotification.cancel();
tvNotificationStt.setVisibility(View.INVISIBLE);
}
}.start();
}
private void SetIndexDecrease() {
timerDecrease = new CountDownTimer(90000, 90000) {
@Override
public void onTick(long millisUntilFinished) {
if (sharedPreferences.getInt(Const.PET_HUNGRY, -1) <= 0) {
editor.putInt(Const.PET_HUNGRY, 0);
} else {
editor.putInt(Const.PET_HUNGRY, sharedPreferences.getInt(Const.PET_HUNGRY, 0) - 1);
}
if (sharedPreferences.getInt(Const.PET_HEALTH, -1) <= 0) {
editor.putInt(Const.PET_HEALTH, 0);
} else {
editor.putInt(Const.PET_HEALTH, sharedPreferences.getInt(Const.PET_HEALTH, 0) - 1);
}
editor.apply();
}
@Override
public void onFinish() {
timerDecrease.start();
Log.e("index", String.valueOf(sharedPreferences.getInt(Const.PET_HUNGRY, 100)));
Log.e("index1", String.valueOf(sharedPreferences.getInt(Const.PET_HEALTH, 100)));
}
}.start();
}
private void SetPetIndexChange() {
int intExp = getIntent().getIntExtra(Const.EXP, 0);
float exp = (float) intExp / 250;
int coin = getIntent().getIntExtra(Const.COIN, 0);
int hungryIndex = Math.round(getIntent().getIntExtra(Const.EXP, 0) / 20) + Math.round(getIntent().getIntExtra(Const.COIN, 0) / 10);
int healthIndex = Math.round(getIntent().getIntExtra(Const.EXP, 0) / 20) + Math.round(getIntent().getIntExtra(Const.COIN, 0) / 20);
float currentLevel = sharedPreferences.getFloat(Const.PET_LEVEL, 1f) + (exp * 1.5f);
int currentMoney = sharedPreferences.getInt(Const.PET_MONEY, 0) + (coin * 2);
int currentHungry = sharedPreferences.getInt(Const.PET_HUNGRY, 0) - hungryIndex;
int currentHealth = sharedPreferences.getInt(Const.PET_HEALTH, 0) - healthIndex;
currentHungry = currentHungry <= 0 ? 0 : currentHungry;
currentHealth = currentHealth <= 0 ? 0 : currentHealth;
editor.putFloat(Const.PET_LEVEL, currentLevel);
editor.putInt(Const.PET_MONEY, currentMoney);
editor.putInt(Const.PET_HUNGRY, currentHungry);
editor.putInt(Const.PET_HEALTH, currentHealth);
editor.apply();
}
private void SetSound() {
mediaPlayer = MediaPlayer.create(this, R.raw.background_music);
clickSound = MediaPlayer.create(this, R.raw.sound_click);
mediaPlayer.setLooping(true);
clickSound.setLooping(false);
mediaPlayer.setVolume(1, 1);
clickSound.setVolume(1, 1);
}
private void CaiNayDeTest() {
editor.putFloat(Const.PET_LEVEL, 1.75f);
editor.putInt(Const.PET_MONEY, 1000000);
editor.putInt(Const.PET_HUNGRY, 100);
editor.putInt(Const.PET_HEALTH, 100);
editor.apply();
}
}
|
package programmers.lv2;
import java.util.Stack;
public class Land_Test {
public static void main(String[] args) {
//땅따먹기
//처음에 dfs로 모든 경우의 수를 구하는 어림도 없는 방법으로 생각하고 구현했다.
//그 결과, 처음 테스트는 통과해도 나머지는 전부 시간초과 떴다.
//검색 후 내가 너무 복잡하게 생각했다는 것을 깨닫고 반성했다..
int[][] land = {{1,2,3,5},{5,6,7,8},{4,3,2,1}};
int answer = 0;
for(int i=1; i< land.length; i++) {
land[i][0] += Math.max(land[i-1][1], Math.max(land[i-1][2], land[i-1][3]));
land[i][1] += Math.max(land[i-1][0], Math.max(land[i-1][2], land[i-1][3]));
land[i][2] += Math.max(land[i-1][0], Math.max(land[i-1][1], land[i-1][3]));
land[i][3] += Math.max(land[i-1][0], Math.max(land[i-1][2], land[i-1][1]));
}
for(int i=0; i< 4; i++) {
int value = land[land.length-1][i];
answer = value > answer ? value : answer;
}
System.out.println(answer);
// boolean[][] check = new boolean[land.length][land[0].length];
// Stack<Point> stack = new Stack<>();
// int max = 0;
// for(int i=0; i<4; i++) {
// int answer = 0;
// answer += land[0][i];
// stack.add(new Point(answer,0, i));
// System.out.println(answer);
//
// while (!stack.isEmpty()) {
// Point tmpPoint = stack.peek();
// System.out.println(tmpPoint.num+"/"+ tmpPoint.row+"/"+ tmpPoint.col);
// if(!check[tmpPoint.row][tmpPoint.col]) {
// check[tmpPoint.row][tmpPoint.col] = true;
// }
// boolean flag = false;
// for(int j=0; j<4; j++) {
// int tmpRow = tmpPoint.row;
// int tmpCol = tmpPoint.col;
// if(tmpRow+1< land.length) {
// if(tmpCol != j && !check[tmpRow+1][j]) {
// answer += land[tmpRow+1][j];
// stack.add(new Point(answer,tmpRow+1,j));
//
// flag = true;
// break;
// }
// }else {
// max = tmpPoint.num > max ? tmpPoint.num : max;
// break;
// }
// }
// if(!flag) {
// if(tmpPoint.row != land.length -1) {
// for(int k=0; k<4; k++) {
// check[tmpPoint.row+1][k] = false;
// }
// }
// stack.pop();
// answer = tmpPoint.num-land[tmpPoint.row][tmpPoint.col];
// }
// }
//
// }
// System.out.println(max);
}
static class Point {
int num;
int row;
int col;
Point(int num, int row, int col) {
this.num = num;
this.row = row;
this.col = col;
}
}
}
|
/*
Document : SME_Lending
Created on : August 21, 2015, 11:56:42 AM
Author : Anuj Verma
*/
package com.spring.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.domain.DealerDemographic;
import com.spring.domain.DealerPaymentCollected;
import com.spring.service.PrincipalUpdateService;
import com.spring.util.ConstantUtils;
@Controller
@RequestMapping("/principal_demographic_service")
public class CrontabDealerDemographicServiceController {
@Autowired
PrincipalUpdateService principalUpdateService;
private static Logger logger = Logger.getLogger(CrontabDealerDemographicServiceController.class);
@Value("${generateSMECPrintKey}")
private String generateSMECPrintKey;
@Value("${sellerDemographicDataFilePath}")
private String sellerDemographicDataFilePath;
@Value("${sellerPaymentCollectedFilePath}")
private String sellerPaymentCollectedFilePath;
@RequestMapping(value = "/demographic_generated_file/{seller_id}/{file_date}", method = RequestMethod.GET)
public void updateInvoiceData(@PathVariable("seller_id") int seller_id,@PathVariable("file_date") String file_date,ModelMap model) {
logger.info("inside :updateInvoiceData ");
try {
updateDemographicdata(seller_id,file_date);
} catch (Exception e) {
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
}
@RequestMapping(value = "/demographic_invoice_file/{seller_id}/{file_date}", method = RequestMethod.GET)
public void updatePaymentClearedData(@PathVariable("seller_id") int seller_id,@PathVariable("file_date") String file_date,ModelMap model) {
logger.info("inside :updatePaymentClearedData ");
try {
updatePaymentdata(seller_id,file_date);
} catch (Exception e) {
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
}
}
public String updateDemographicdata(int sellerId, String date) throws Exception,FileNotFoundException {
logger.info("Entering updateDemographicdata() API method");
String message = null;
DealerDemographic dealerDemographicData = null;
String modifiedDate = date;
String newDate = modifiedDate.replaceAll("-", "");
ArrayList<DealerDemographic> invoiceGenerateList = new ArrayList<DealerDemographic>();
try{
String filepath = sellerDemographicDataFilePath+sellerId+"_"+newDate+".xls";
logger.info(filepath);
File fileToDownload = new File(filepath);
try{
InputStream input = new FileInputStream(fileToDownload);
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheet("demographic_dealer_file");
Iterator<Row> rowIterator = null;
if (sheet != null) {
if(!validateDemographicExcelFile(sheet)){
message = "Invalid file format. Check your header names";
return message;
}
logger.info("total no:of rows:" + sheet.getLastRowNum());
rowIterator = sheet.iterator();
} else {
logger.error("Excel sheet name is wrong, sheet name should be demographic_dealer_file");
message = "Excel sheet name is wrong, sheet name should be demographic_dealer_file. Please change name and try again";
return message;
}
if (rowIterator.hasNext()) {
rowIterator.next();
}
/*Integer totalRows = sheet.getLastRowNum();
if(totalRows > 101){
message = "Total number of rows should be less than 100";
return message;
}
*/
for(int rowNumber = 1; rowNumber <=sheet.getLastRowNum(); rowNumber++) {
dealerDemographicData = null;
Row row = sheet.getRow(rowNumber);
for (int i = 0; i <= 10; i++) {
Cell cell = row.getCell(i);
int columnIndex = i;
String cellData = null;
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
// Do nothing
} else {
cellData = converting(cell);
if (dealerDemographicData == null)
dealerDemographicData = new DealerDemographic();
}
switch (columnIndex) {
case 1:
if (cellData != null) {
dealerDemographicData.setDealerName(cellData);
}
break;
case 2:
if (cellData != null) {
dealerDemographicData.setPrincipalERPCode(cellData);
}
break;
case 3:
if (cellData != null) {
dealerDemographicData.setDealerMobileNumber(cellData);
}
break;
case 4:
if (cellData != null) {
dealerDemographicData.setVatNumber(cellData);
}
break;
case 5:
if (cellData != null) {
dealerDemographicData.setDealerAddress(cellData);
}
break;
case 6:
if (cellData != null) {
dealerDemographicData.setDealerCity(cellData);
}
break;
case 7:
if (cellData != null) {
dealerDemographicData.setDateofAsccoiationwithPrinciapal(cellData);
}
break;
case 8:
if (cellData != null) {
dealerDemographicData.setAssignedSalesPerson(cellData);
}
break;
case 9:
if (cellData != null) {
dealerDemographicData.setSalesPersonMobileNumber(cellData);
}
break;
}
}
if(dealerDemographicData!=null){
dealerDemographicData.setSellerId(Long.valueOf(sellerId));
message = principalUpdateService.updateDemographicData(dealerDemographicData);
invoiceGenerateList.add(dealerDemographicData);
logger.info(message);
}
}
}catch(FileNotFoundException e){
logger.info("File Location is wrong ::"+e);
}
}catch (Exception e){
logger.info(e);
}
logger.info("Output message from smelending API ::" + message);
return message;
}
public String updatePaymentdata(int sellerId, String date) throws Exception,FileNotFoundException{
logger.info("Entering updatePaymentdata() API method");
String message = null;
DealerPaymentCollected paymentCleared = null;
String modifiedDate = date;
String newDate = modifiedDate.replaceAll("-", "");
ArrayList<DealerPaymentCollected> paymentList = new ArrayList<DealerPaymentCollected>();
try{
String filepath = sellerPaymentCollectedFilePath+sellerId+"_"+newDate+".xls";
logger.info(filepath);
File fileToDownload = new File(filepath);
try{
InputStream input = new FileInputStream(fileToDownload);
Workbook wb = new HSSFWorkbook(input);
Sheet sheet = wb.getSheet("Daily Payment Collected File");
Iterator<Row> rowIterator = null;
if (sheet != null) {
if(!validatePaymentExcelFile(sheet)){
message = "Invalid file format. Check your header names";
return message;
}
logger.info("total no:of rows:" + sheet.getLastRowNum());
rowIterator = sheet.iterator();
} else {
logger.error("Excel sheet name is wrong, sheet name should be Daily Payment Collected File");
message = "Excel sheet name is wrong, sheet name should be Daily Payment Collected File. Please change name and try again";
return message;
}
if (rowIterator.hasNext()) {
rowIterator.next();
}
/*Integer totalRows = sheet.getLastRowNum();
if(totalRows > 101){
message = "Total number of rows should be less than 100";
return message;
}
*/
for(int rowNumber = 1; rowNumber <=sheet.getLastRowNum(); rowNumber++) {
paymentCleared = null;
Row row = sheet.getRow(rowNumber);
for (int i = 0; i <= 10; i++) {
Cell cell = row.getCell(i);
int columnIndex = i;
String cellData = null;
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
// Do nothing
} else {
cellData = converting(cell);
if (paymentCleared == null)
paymentCleared = new DealerPaymentCollected();
}
switch (columnIndex) {
case 1:
if (cellData != null) {
paymentCleared.setPaymentClearanceDate(cellData);;
}
break;
case 2:
if (cellData != null) {
paymentCleared.setSapDealerCode(cellData);
}
break;
case 3:
if (cellData != null) {
paymentCleared.setFirmName(cellData);
}
break;
case 4:
if (cellData != null) {
paymentCleared.setCity(cellData);
}
break;
case 5:
if (cellData != null) {
paymentCleared.setInvoiceNo(cellData);
}
break;
case 6:
if (cellData != null) {
paymentCleared.setInvoiceDate(cellData);
}
break;
case 7:
if (cellData != null) {
paymentCleared.setInvoiceValue(Double.valueOf(cellData));
}
break;
case 8:
if (cellData != null) {
paymentCleared.setInvoiceDueDate(cellData);
}
break;
case 9:
if (cellData != null) {
paymentCleared.setPaymentMode(cellData);
}
break;
case 10:
if (cellData != null) {
paymentCleared.setPaymentAmount(Double.valueOf(cellData));
}
break;
}
}
if(paymentCleared!=null){
paymentCleared.setSellerId(sellerId);
message = principalUpdateService.updatePaymentCollectedData(paymentCleared);
paymentList.add(paymentCleared);
logger.info(message);
}
}
}catch(FileNotFoundException e){
logger.info("File Location is wrong ::"+e);
}
}catch (Exception e){
logger.info(e);
}
logger.info("Output message from smelending API ::" + message);
return message;
}
private Boolean validateDemographicExcelFile(Sheet sheet){
String headerCellData = null;
Boolean isValid = Boolean.FALSE;
Row firstRow = sheet.getRow(0);
Cell firstCell = firstRow.getCell(0);
headerCellData = converting(firstCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_FIRST_CELL.equals(headerCellData)){
return isValid;
}
Cell secondCell = firstRow.getCell(1);
headerCellData = converting(secondCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_SECOND_CELL.equals(headerCellData)){
return isValid;
}
Cell thirdCell = firstRow.getCell(2);
headerCellData = converting(thirdCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_THIRD_CELL.equals(headerCellData)){
return isValid;
}
Cell fourthCell = firstRow.getCell(3);
headerCellData = converting(fourthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_FOURTH_CELL.equals(headerCellData)){
return isValid;
}
Cell fifthCell = firstRow.getCell(4);
headerCellData = converting(fifthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_FIFTH_CELL.equals(headerCellData)){
return isValid;
}
Cell sixthCell = firstRow.getCell(5);
headerCellData = converting(sixthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_SIXTH_CELL.equals(headerCellData)){
return isValid;
}
Cell seventhCell = firstRow.getCell(6);
headerCellData = converting(seventhCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_SEVENTH_CELL.equals(headerCellData)){
return isValid;
}
Cell eighthCell = firstRow.getCell(7);
headerCellData = converting(eighthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_EIGHTH_CELL.equals(headerCellData)){
return isValid;
}
Cell ninthCell = firstRow.getCell(8);
headerCellData = converting(ninthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_NINETH_CELL.equals(headerCellData)){
return isValid;
}
Cell tenthCell = firstRow.getCell(9);
headerCellData = converting(tenthCell);
if(!ConstantUtils.SELLER_DEMOGRAPHIC_INVOICE_TENTH_CELL.equals(headerCellData)){
return isValid;
}
isValid = Boolean.TRUE;
return isValid;
}
private Boolean validatePaymentExcelFile(Sheet sheet){
String headerCellData = null;
Boolean isValid = Boolean.FALSE;
Row firstRow = sheet.getRow(0);
Cell firstCell = firstRow.getCell(0);
headerCellData = converting(firstCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_FIRST_CELL.equals(headerCellData)){
return isValid;
}
Cell secondCell = firstRow.getCell(1);
headerCellData = converting(secondCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_SECOND_CELL.equals(headerCellData)){
return isValid;
}
Cell thirdCell = firstRow.getCell(2);
headerCellData = converting(thirdCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_THIRD_CELL.equals(headerCellData)){
return isValid;
}
Cell fourthCell = firstRow.getCell(3);
headerCellData = converting(fourthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_FOURTH_CELL.equals(headerCellData)){
return isValid;
}
Cell fifthCell = firstRow.getCell(4);
headerCellData = converting(fifthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_FIFTH_CELL.equals(headerCellData)){
return isValid;
}
Cell sixthCell = firstRow.getCell(5);
headerCellData = converting(sixthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_SIXTH_CELL.equals(headerCellData)){
return isValid;
}
Cell seventhCell = firstRow.getCell(6);
headerCellData = converting(seventhCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_SEVENTH_CELL.equals(headerCellData)){
return isValid;
}
Cell eighthCell = firstRow.getCell(7);
headerCellData = converting(eighthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_EIGHTH_CELL.equals(headerCellData)){
return isValid;
}
Cell ninthCell = firstRow.getCell(8);
headerCellData = converting(ninthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_NINETH_CELL.equals(headerCellData)){
return isValid;
}
Cell tenthCell = firstRow.getCell(9);
headerCellData = converting(tenthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_TENTH_CELL.equals(headerCellData)){
return isValid;
}
Cell eleveenthCell = firstRow.getCell(10);
headerCellData = converting(eleveenthCell);
if(!ConstantUtils.SELLER_DAILY_PAYMENT_ELEVEENTH_CELL.equals(headerCellData)){
return isValid;
}
isValid = Boolean.TRUE;
return isValid;
}
public String converting(Cell cell) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().getString().trim();
case Cell.CELL_TYPE_NUMERIC:
if (cell.getCellStyle().getDataFormatString().contains("%")) {
Double value = cell.getNumericCellValue() * 100;
return value.toString().substring(0, 5);
}else{
if (DateUtil.isCellInternalDateFormatted(cell)) {
return ConstantUtils.dateConverter(cell.getDateCellValue(),"dd-MMM-yyyy").trim();
} else {
return String.valueOf(Math.round(cell.getNumericCellValue())).trim();
}
}
case Cell.CELL_TYPE_BOOLEAN:
return String.valueOf(cell.getBooleanCellValue()).trim();
default:
return "not matching";
}
}
}
|
package team1699.subsystems;
import org.junit.Before;
import org.junit.Test;
import team1699.utils.MotorConstants;
import team1699.utils.controllers.SpeedControllerGroup;
import team1699.utils.controllers.TestSpeedController;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ShooterTest {
final static double goal = 2 * Math.PI; //TODO Figure out units (prob rad/sec)
private ShooterSim simShooter;
@Before
public void setupTest() {
simShooter = new ShooterSim();
}
@Test
public void testShooterModel() {
SpeedControllerGroup testGroup = new SpeedControllerGroup(new TestSpeedController(1));
Shooter shooter = new Shooter(testGroup, null, null); //TODO Add speed controller group
shooter.setGoal(goal);
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("dump.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return; //Return if something breaks
}
pw.write("# time, velocity, voltage, acceleration, goal, lastError\n");
double currentTime = 0.0;
while (currentTime < 30.0) {
shooter.update(simShooter.getVelocity());
final double voltage = testGroup.get();
pw.write(String.format("%f, %f, %f, %f, %f, %f\n", currentTime, simShooter.velocity, voltage, simShooter.getAcceleration(voltage), shooter.filteredGoal, shooter.lastError));
simulateTime(voltage, ShooterSim.kDt);
currentTime += ShooterSim.kDt;
pw.flush();
}
pw.close();
assertEquals(goal, simShooter.velocity, 0.01);
}
void simulateTime(final double voltage, final double time) {
assertTrue(String.format("System asked for: %f volts which is greater than 12.0", voltage), voltage <= 12.0 && voltage >= -12.0);
final double kSimTime = 0.0001;
double currentTime = 0.0;
while (currentTime < time) {
final double acceleration = simShooter.getAcceleration(voltage);
//simShooter.velocity += simShooter.velocity * kSimTime;
simShooter.velocity += acceleration * kSimTime;
currentTime += kSimTime;
//Jakob: I don't this we need this because there is no positional limit on a shooter
// if(simShooter.limitTriggered()){
// assertTrue(simShooter.velocity > -0.05, String.format("System running at %f m/s which is less than -0.051", simShooter.velocity));
// }
//TODO Check units
//assertTrue(String.format("System is at %f rad/sec which is less than minimum velocity of %f", simShooter.velocity, Shooter.kMinVelocity), simShooter.velocity >= Shooter.kMinVelocity - 0.01);
//assertTrue(String.format("System is at %f rad/sec which is greater than the maximum velocity of %f", simShooter.velocity, Shooter.kMaxVelocity), simShooter.velocity <= Shooter.kMaxVelocity + 0.01);
}
}
private static class ShooterSim {
//Sample time
public static final double kDt = 0.010;
//TODO Change constants
//Gear Ratio
static final double kG = 1;
//Rotational Inertial of Flywheel
static final double kI = 0.05;
// V = I * R + ω / Kv
// torque = Kt * I
private double velocity = 0.0;
ShooterSim() {
}
private double getAcceleration(final double voltage) {
// System.out.println(String.format("Velocity: %f, Voltage: %f", velocity, voltage));
// System.out.println("Accel: " + (voltage - ((velocity * kG)/(MotorConstants.MotorCIM.Kv))) * (MotorConstants.MotorCIM.Kt/(kI * MotorConstants.MotorCIM.kResistance)));
return (voltage - ((velocity * kG) / (MotorConstants.MotorCIM.Kv))) * (MotorConstants.MotorCIM.Kt / (kI * MotorConstants.MotorCIM.kResistance));
}
private double getVelocity() {
return velocity;
}
}
}
|
package com.example.duckdemo.data.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
// Duck is our Business Domain
@Entity // JPA + Hibernate will auto-create table for this class
public class Duck {
// Validation Rules specify what can and can't be processed in our DB
@Id // Auto-incrementing
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name", unique = true)
@NotNull
private String name;
@NotNull
private String colour;
@NotNull
private String habitat;
@Min(0)
@Max(36)
private int age;
public Duck() {
}
public Duck(String name, String colour, String habitat, int age) {
super();
this.name = name;
this.colour = colour;
this.habitat = habitat;
this.age = age;
}
public Duck(int id, String name, String colour, String habitat, int age) {
super();
this.id = id;
this.name = name;
this.colour = colour;
this.habitat = habitat;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public String getHabitat() {
return habitat;
}
public void setHabitat(String habitat) {
this.habitat = habitat;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((colour == null) ? 0 : colour.hashCode());
result = prime * result + ((habitat == null) ? 0 : habitat.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
// Equals method is VERY IMPORTANT for testing
// - this override compares the content rather than the object reference
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Duck other = (Duck) obj;
if (age != other.age)
return false;
if (colour == null) {
if (other.colour != null)
return false;
} else if (!colour.equals(other.colour))
return false;
if (habitat == null) {
if (other.habitat != null)
return false;
} else if (!habitat.equals(other.habitat))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
package com.space.smarthive.f_feed;
import android.util.Log;
import com.space.smarthive.data.Feed;
import java.util.List;
/**
* @Author: Space
* @Date: 2020/10/31 11:09
*/
public class InfoPresenter implements InfoContract.Presenter, InfoContract.LoadDataCallback{
private static final String TAG = "InfoPresenter";
private final InfoContract.View mInfoView;
private InfoModel model;
public InfoPresenter(InfoContract.View infoView) {
this.mInfoView = infoView;
//this.mInfoView.setPresenter(this);
model = new InfoModel();
}
@Override
public void onSuccess(List<Feed> feeds) {
mInfoView.updateRecyclerView(feeds);
}
@Override
public void onFailed() {
}
@Override
public void loadFeeds() {
model.getFeeds(this);
Log.i(TAG, "loadFeeds: ");
}
@Override
public void start() {
loadFeeds();
}
}
|
package chatroom.model.message;
public class RoomNameEditMessage extends Message {
private String newName;
public RoomNameEditMessage(String newName){
this.newName = newName;
type = 13;
}
public String getNewName() {
return newName;
}
}
|
package nbody_pap1314.simulator;
/**
* The statistician is used to compute statistics and show them to the user.
*
* @author Michele Braccini
* @author Alessandro Fantini
*/
public class Statistician {
protected final long printWaitTimeMs; /* the minimum amount of time between two logs */
protected long lastPrintTime; /* the last instant of time a log was printed */
protected long averageExecutionTimeMs; /* the average execution time */
protected long numCycles; /* the number of cycles done */
public Statistician(long printWaitTimeMs) {
this.printWaitTimeMs = printWaitTimeMs;
resetStatistics();
}
/**
* Updates statics.
*/
public void updateStatistics(long executionTime) {
averageExecutionTimeMs = ((averageExecutionTimeMs * numCycles) + executionTime) / (numCycles + 1);
numCycles++;
if (numCycles == 0) {
averageExecutionTimeMs = 0;
}
long currentTime = System.currentTimeMillis();
if (currentTime - lastPrintTime > printWaitTimeMs) {
lastPrintTime = currentTime;
log("average execution time: " + averageExecutionTimeMs + " ms");
}
}
/**
* Resets statics.
*/
public void resetStatistics() {
this.lastPrintTime = System.currentTimeMillis();
this.averageExecutionTimeMs = 0;
this.numCycles = 0;
}
private void log(String msg) {
System.out.println("[" + this.getClass().getSimpleName() + "] " + msg);
}
}
|
package com.mybatis.interceptor.abstracts;
import com.mybatis.interceptor.filterinterceptor.SQLLanguage;
import com.mybatis.interceptor.enums.SQLEnums;
import org.aspectj.lang.JoinPoint;
import java.util.Map;
import java.util.TreeMap;
/**
* @author yi
* @ClassName BaseAspectAbstract
* @Description 基础切面处理类,每一个Spring的切面都需要去继承此抽象类
* @Date
**/
public abstract class BaseAspectAbstract {
private static TreeMap<Integer,SQLLanguage> CONTAINERS = new TreeMap<>();
public void putSQL(JoinPoint point,SQLEnums sqlEnums,SQLLanguage sqlLanguage) {
CONTAINERS.put(sqlEnums.getId(),sqlLanguage);
//获取方法里的参数
Object parmas = point.getArgs()[0];
Map map = (Map) parmas;
map.put("SQL",getSQL());
}
public TreeMap<Integer,SQLLanguage> getSQL() {
return CONTAINERS;
}
}
|
/**
* Title: DLSim<p>
* Description: <p>
* Copyright: Copyright (c) Matthew Leslie<p>
* Company: Keble College, Oxford<p>
* @author Matthew Leslie
* @version 1.0
*/
package dlsim.DLSim.Util;
import dlsim.DLSim.*;
import java.awt.Point;
import javax.swing.*;
import javax.swing.filechooser.FileView;
import java.awt.Color;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
import java.io.*;
import java.net.*;
public class staticUtils {
public static boolean snapToGrid()
{
return Preferences.getValue("SNAPTOGRID","TRUE").equals("TRUE");
}
public static void errorMessage(String s)
{
System.err.println(s);
JOptionPane.showMessageDialog(UIMainFrame.currentinstance,s);
}
public static Rectangle boundingRect(Point p1, Point p2)
{
int x1,x2,y1,y2;
x1 = java.lang.Math.min(p1.x,p2.x);
x2 = java.lang.Math.max(p1.x,p2.x);
y1 = java.lang.Math.min(p1.y,p2.y);
y2 = java.lang.Math.max(p1.y,p2.y);
return new Rectangle(x1,y1,(x2-x1),(y2-y1));
}
public static Rectangle bigBoundingRect(Point p1, Point p2)
{
int x1,x2,y1,y2;
x1 = java.lang.Math.min(p1.x,p2.x);
x2 = java.lang.Math.max(p1.x,p2.x);
y1 = java.lang.Math.min(p1.y,p2.y);
y2 = java.lang.Math.max(p1.y,p2.y);
return new Rectangle(x1-5,y1-5,(x2-x1)+10,(y2-y1)+10);
}
public static FileFilter xmlFilter = new FileFilter()
{
public boolean accept(File f)
{
if (f.getName().endsWith(".xml")) return true;
return false;
}
public String getDescription()
{
return "XML filter";
}
};
public static FileFilter componentFilter = new FileFilter()
{
public boolean accept(File f)
{
if (f.getName().endsWith(".component.xml")) return true;
return false;
}
public String getDescription()
{
return "Component Filter";
}
};
public static String getLastNameFromURL(URL u)
{
if (u==null) return "";
String url = u.toString();
// strip ending '/'
if (url.endsWith("/")) url=url.substring(0,url.length()-1);
int i = url.lastIndexOf("/");
if (i==-1) return u.toString();
// strip all upto and including last '/'
String s = url.substring(i+1);
return s;
}
public static File FileFromURL(URL u)
{
if (u==null) return null;
if (u.getProtocol().equals("file"))
{
// convert into file
try{
URI uri = new URI(u.toString());
File f = new File(uri);
return f;
}
catch (Exception e) {e.printStackTrace();return null;}
}
else
{
return null;
}
}
public static URL URLFromFile(File f)
{
try{
return f.toURL();
}
catch (Exception e)
{
e.printStackTrace();
errorMessage(e.getMessage());
return null;
}
}
public static FileView CircuitFileView()
{
return new CircuitFileView();
}
public static boolean[] decimalToBinary(int i)
{
boolean[] bools = new boolean[8];
int p=7;
if (i>511) throw new Error("Overflow in binary to dec conversion");
while (i>1 && p>0)
{
int j = i % 2;
double a = (i/2.0);
if (j==1) a=a-0.5;
i=(int)Math.round(a);
bools[p]=((j==1));
p--;
}
bools[p]=(i==1);
return bools;
}
}
class CircuitFileView extends FileView
{
public String getName(File f)
{
if (f.getName().endsWith(".circuit.xml"))
return f.getName().substring(0,f.getName().length()-12);
if (f.getName().endsWith(".component.xml"))
return f.getName().substring(0,f.getName().length()-14);
return f.getName();
}
public String getDescription(File f)
{
if (f.getName().endsWith(".circuit.xml")) return "A circuit";
if (f.getName().endsWith(".component.xml")) return "A sub-component";
return "";
}
public String getTypeDescription(File f)
{
if (f.getName().endsWith(".circuit.xml")) return "A circuit";
if (f.getName().endsWith(".component.xml")) return "A sub-component";
return "";
}
public Icon getIcon(File f)
{
if (f.getName().endsWith(".circuit.xml")) return new ImageIcon(dlsim.DLSim.UIImages.circuit);
if (f.getName().endsWith(".component.xml")) return new ImageIcon(dlsim.DLSim.UIImages.icon);
return null;
}
public Boolean isTraversable(File f)
{
return new Boolean(f.isDirectory());
}
}
abstract class FileFilter extends javax.swing.filechooser.FileFilter implements java.io.FileFilter
{
}
|
package com.sharjeelhussain.smd_project;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Chat_Box extends AppCompatActivity {
AutoCompleteTextView Doctor, Patient;
EditText Message;
Button Back,Send;
Boolean Pchat = true;
Boolean Dchat = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat__box);
Doctor=findViewById(R.id.doctor);
Patient=findViewById(R.id.patient);
Back=findViewById(R.id.back);
Send=findViewById(R.id.send);
Message=findViewById(R.id.message);
Back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
Send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String message=Message.getText().toString();
if (message.length()==0)
{
Toast.makeText(Chat_Box.this, "Kindly enter message.", Toast.LENGTH_LONG).show();
}
else
{
//firebase code
if (getIntent().getExtras().getString("Type").equals("Doctor"))
{ if (Dchat){ message = Doctor.getText().toString()+"\n"+message; } }
else { if (Pchat){ message = Patient.getText().toString()+"\n"+message; } }
FirebaseDatabase.getInstance().getReference(getIntent().getExtras().getString("Fkey")+"_Chat")
.child(getIntent().getExtras().getString("Type")).setValue(message);
Intent reload = new Intent(Chat_Box.this,Chat_Box.class);
reload.putExtra("Fkey",getIntent().getExtras().getString("Fkey"));
reload.putExtra("Type",getIntent().getExtras().getString("Type"));
startActivity(reload);
finish();
}
}
});
FirebaseDatabase.getInstance().getReference(getIntent().getExtras().getString("Fkey")+"_Chat").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("Patient"))
{
Patient.setText(dataSnapshot.child("Patient").getValue(String.class));
}
else
{
Pchat = false;
Patient.setText("N/A");
}
if (dataSnapshot.hasChild("Doctor"))
{
Patient.setText(dataSnapshot.child("Doctor").getValue(String.class));
}
else
{
Dchat = false;
Patient.setText("N/A");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
|
package com.theIronYard.entity;
import java.util.ArrayList;
/**
* Created by chris on 8/12/16.
*/
public class Animal {
private int id;
private String name;
private AnimalType type;
private AnimalBreed breed;
private String description;
private String color;
private ArrayList<Note> notes;
/**
* entity constructor which creates a new animal with the specified properties.
*
* @param name String
* @param type String
* @param breed String
* @param color String
* @param description String
*/
public Animal(int id, String name, AnimalType type, AnimalBreed breed, String color, String description) {
this.id = id;
this.name = name;
this.type = new AnimalType(type.getTypeId(), type.getTypeName());
this.breed = new AnimalBreed(breed.getBreedId(), breed.getName(), breed.getTypeId());
this.color = color;
this.description = description;
this.notes = new ArrayList<>();
}
public Animal(String name, AnimalType type, AnimalBreed breed, String color, String description) {
this.name = name;
this.type = new AnimalType(type.getTypeId(), type.getTypeName());
this.breed = new AnimalBreed(breed.getBreedId(), breed.getName(), breed.getTypeId());
this.color = color;
this.description = description;
this.notes = new ArrayList<>();
}
/**
* entity no arguments constructor creates a blank animal.
*/
public Animal() {
this.name = "";
this.type = new AnimalType();
this.breed = new AnimalBreed();
this.color = "";
this.description = "";
this.notes = new ArrayList<>();
}
// getter methods
public String getName(){ return this.name; }
public AnimalType getType(){ return this.type; }
public AnimalBreed getBreed(){ return this.breed; }
public String getDescription(){ return this.description; }
public String getColor(){ return this.color; }
public int getId() {return id;}
public ArrayList<Note> getNotes() {return notes;}
public int getNoteCount() {return notes.size();}
/*
The setter methods are package private because AnimalRepository exposes methods
for creating and editing animals.
*/
public void setName(String name){ this.name = name; }
public void setType(AnimalType type){ this.type = type; }// void setSpeciesID(int speciesID) {this.speciesID = speciesID;}
public void setBreed(AnimalBreed breed){ this.breed = breed; }
public void setDescription(String description){ this.description = description; }
public void setColor(String color){ this.color = color; }
public void setId(int id) {this.id = id;}
public void setNotes(ArrayList<Note> notes) {
// create blank list
this.notes = new ArrayList<Note>();
// addAnimal notes to list instead of creating a link
this.notes.addAll(notes);
}
public void addNote(Note note) {this.notes.add(note);}
public void addNote(String note) {
Note newNote = new Note(note);
this.notes.add(newNote);
}
@Override
public String toString() {
return this.id + "\t" + this.name + "\t" + this.type.getTypeName() + "\t" + this.breed.getName() + "\t" + this.color;
}
/**
* toString(verbose) Overloads the toString method with an option to
* display the full details of the entity. Including the description.
*
* @param verbose String, ignored, but it's presence triggers this
* version of the toString method.
* @return String
*/
public String toString(String verbose){
return "Name:\t\t\t" + this.name + "\nType:\t\t\t" + this.type.getTypeName() +
"\nBreed:\t\t\t" + this.breed.getName() + "\nColor:\t\t\t" + this.color + "\nDescription:\t" + this.description;
}
@Override
// auto generated by IntelliJ
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Animal animal = (Animal) o;
if (!getName().equals(animal.getName())) return false;
if (!getType().equals(animal.getType())) return false;
if (!getBreed().equals(animal.getBreed())) return false;
if (!getDescription().equals(animal.getDescription())) return false;
return getColor().equals(animal.getColor());
}
@Override
// auto generated by IntelliJ
public int hashCode() {
int result = getName().hashCode();
result = 31 * result + getType().hashCode();
result = 31 * result + getBreed().hashCode();
result = 31 * result + getDescription().hashCode();
result = 31 * result + getColor().hashCode();
return result;
}
}
|
package com.ifisolution.cmsmanagerment.services.impl;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ifisolution.cmsmanagerment.entities.NewsStatus;
import com.ifisolution.cmsmanagerment.repository.NewsStatusRepository;
import com.ifisolution.cmsmanagerment.services.NewsStatusService;
@Service
public class NewsStatusServiceImpl implements NewsStatusService {
@Autowired
private NewsStatusRepository newsstatusrepository;
@Override
public List<NewsStatus> findAll() {
return newsstatusrepository.findAll();
}
@Override
public NewsStatus findById(Integer Id) {
Optional<NewsStatus> newsStatus = newsstatusrepository.findById(Id);
if (!newsStatus.isPresent()) {
throw new EntityNotFoundException("Not Found Status with id " + Id);
}
NewsStatus newsStatus2 = newsStatus.get();
return newsStatus2;
}
@Override
public NewsStatus save(NewsStatus newsStatus) {
Integer id = newsStatus.getId();
Optional<NewsStatus> newsStatus2 = newsstatusrepository.findById(id);
if (newsStatus2.isPresent()) {
throw new EntityExistsException("Status id " + id + " has exist");
}
return newsstatusrepository.save(newsStatus);
}
@Override
public NewsStatus update(NewsStatus newsStatus, Integer Id) {
Optional<NewsStatus> stockStatus = newsstatusrepository.findById(Id);
Integer idUpdate = newsStatus.getId();
if (!stockStatus.isPresent()) {
throw new EntityNotFoundException("Status id " + Id + " not found");
}
if (idUpdate != Id) {
throw new EntityExistsException("not change id");
}
return newsstatusrepository.save(newsStatus);
}
@Override
public ResponseEntity<Object> deleteById(Integer Id) {
Optional<NewsStatus> newsStatus = newsstatusrepository.findById(Id);
if (!newsStatus.isPresent()) {
throw new EntityNotFoundException("Not Found Status with id " + Id);
}
newsstatusrepository.deleteById(Id);
return new ResponseEntity<Object>("Status id " + Id + " has been deleted", HttpStatus.OK);
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$fx extends g {
public c$fx() {
super("operateVideoPlayer", "", 10000, false);
}
}
|
package fbos;
import java.util.Map;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
/**
* Represents an Frame Buffer Object. Holds the ID of the object, and the
* width/height of the FBO.
*
* @author Karl
*
*/
public class Fbo {
private final int fboId;
private final int width;
private final int height;
private final Map<Integer, Attachment> colourAttachments;
private final Attachment depthAttachment;
protected Fbo(int fboId, int width, int height, Map<Integer, Attachment> attachments, Attachment depthAttachment) {
this.fboId = fboId;
this.width = width;
this.height = height;
this.colourAttachments = attachments;
this.depthAttachment = depthAttachment;
}
/**
* Copy the contents of a colour attachment of this FBO to the screen.
*
* @param colourIndex
* - The index of the colour buffer that should be blitted.
*/
public void blitToScreen(int colourIndex) {
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0);
GL11.glDrawBuffer(GL11.GL_BACK);
GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fboId);
GL11.glReadBuffer(GL30.GL_COLOR_ATTACHMENT0 + colourIndex);
GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, Display.getWidth(), Display.getHeight(),
GL11.GL_COLOR_BUFFER_BIT, GL11.GL_NEAREST);
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
}
/**
* Copy the contents of this FBO to another FBO. This can be used to resolve
* multisampled FBOs.
*
* @param srcColourIndex
* - Index of the colour buffer in this (the source) FBO.
* @param target
* - The target FBO.
* @param targetColourIndex
* - The index of the target colour buffer in the target FBO.
*/
public void blitToFbo(int srcColourIndex, Fbo target, int targetColourIndex) {
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, target.fboId);
GL11.glDrawBuffer(GL30.GL_COLOR_ATTACHMENT0 + targetColourIndex);
GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, fboId);
GL11.glReadBuffer(GL30.GL_COLOR_ATTACHMENT0 + srcColourIndex);
int bufferBit = depthAttachment != null && target.depthAttachment != null
? GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT : GL11.GL_COLOR_BUFFER_BIT;
GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, target.width, target.height, bufferBit, GL11.GL_NEAREST);
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
}
/**
* Gets the ID of the buffer being used as the colour buffer (either a
* render buffer or a texture).
*
* @param colourIndex
* - The index of the colour attachment.
* @return The ID of the buffer.
*/
public int getColourBuffer(int colourIndex) {
return colourAttachments.get(colourIndex).getBufferId();
}
/**
* @return The ID of the buffer containing the depth buffer (either a render
* buffer or a texture).
*/
public int getDepthBuffer() {
return depthAttachment.getBufferId();
}
/**
* @return True if this framebuffer has been correctly set up and is
* complete.
*/
public boolean isComplete() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fboId);
boolean complete = GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) == GL30.GL_FRAMEBUFFER_COMPLETE;
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
return complete;
}
/**
* Bind the FBO so that it can be rendered to. Anything rendered while the
* FBO is bound will be rendered to the FBO.
*
* @param colourIndex
* - The index of the colour buffer that should be drawn to.
*/
public void bindForRender(int colourIndex) {
// should add support for binding multiple colour attachments
GL11.glDrawBuffer(GL30.GL_COLOR_ATTACHMENT0 + colourIndex);
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, fboId);
GL11.glViewport(0, 0, width, height);
}
/**
* Switch back to the default frame buffer.
*/
public void unbindAfterRender() {
GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0);
GL11.glDrawBuffer(GL11.GL_BACK);
GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());
}
/**
* Delete the FBO and attachments.
*/
public void delete() {
for (Attachment attachment : colourAttachments.values()) {
attachment.delete();
}
if (depthAttachment != null) {
depthAttachment.delete();
}
}
/**
* Starts the creation of a new FBO (without multisampling)
*
* @param width
* - The width in pixels of the FBO.
* @param height
* - The height in pixels.
* @return The builder object for the FBO.
*/
public static FboBuilder newFbo(int width, int height) {
return new FboBuilder(width, height, 0);
}
/**
* Starts the creation of a new multisampled FBO.
*
* @param width
* - Width in pixels.
* @param height
* - Height in pixels.
* @param samples
* - Number of samples being used for multisampling.
* @return The builder object.
*/
public static FboMsBuilder newMultisampledFbo(int width, int height, int samples) {
return new FboMsBuilder(new FboBuilder(width, height, samples));
}
}
|
package MovieScriptProgram;
public class Mekan extends Yer {
String isim;
private Kişi[] şahıslar = new Kişi[20];
public Mekan() {
}
public Mekan(String isim) {
this.isim = isim;
}
public Mekan(String isim, String adres) {
super(adres);
this.isim = isim;
}
public String getİsim() {
return isim;
}
public Kişi[] getŞahıslar() {
return şahıslar;
}
public String getAdres() {
return super.getAdres();
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setİsim(String isim) {
this.isim = isim;
}
public void setKişiler(Kişi[] şahıslar) {
this.şahıslar = şahıslar;
}
public void kişiEkle(Kişi k) {
if (getKişiSayısı() < şahıslar.length) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == null) {
şahıslar[i] = k;
break;
}
}
} else {
System.out.println("Eklenebilecek maksimum kişi zaten eklendi!");
}
}
public void kişiÇıkar(Kişi k) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == k) {
şahıslar[i] = null;
}
}
}
public void karakterEkle(Karakter ka) {
boolean isVar = false;
if (getKişiSayısı() < şahıslar.length) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] != null && şahıslar[i] instanceof Karakter && ((Karakter) şahıslar[i]).ad == ka.ad && ((Karakter) şahıslar[i]).tip == ka.tip) {
isVar = true;
}
}
if (isVar == false) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == null) {
şahıslar[i] = ka;
break;
}
}
} else {
System.out.println("Bu ad ve tipe sahip bir karakter bu mekana eklenemez!");
}
} else {
System.out.println("Eklenebilecek kişi sayısı zaten eklendi!");
}
}
public void karakterÇıkar(Karakter ka) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == ka) {
şahıslar[i] = null;
}
}
}
public int getKişiSayısı() {
int toplamKişi = 0;
for (Kişi k : şahıslar) {
if (k != null) {
toplamKişi++;
}
}
return toplamKişi;
}
public int getKarakterSayısı() {
int toplamKarakter = 0;
for (Kişi k : şahıslar) {
if (k instanceof Karakter) {
toplamKarakter++;
}
}
return toplamKarakter;
}
public int getKişilerinToplamYaşı() {
int toplamYaş = 0;
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] != null) {
toplamYaş += şahıslar[i].yaş;
}
}
return toplamYaş;
}
public int getKarakterlerinToplamYaşı() {
int toplamYaş = 0;
for (Kişi k : şahıslar) {
if (k != null) {
if (k instanceof Karakter) {
toplamYaş += ((Karakter) k).yaş;
}
}
}
return toplamYaş;
}
public double getKişilerinYaşlarıOrtalaması() {
double ortalamaYaş = 0;
int toplamYaş = 0;
int sayaç = 0;
for (Kişi k : şahıslar) {
if (k != null) {
toplamYaş += k.yaş;
sayaç++;
}
}
ortalamaYaş = (double) toplamYaş / sayaç;
return ortalamaYaş;
}
public double getKarakterlerinYaşlarıOrtalaması() {
double ortalamaYaş = 0;
int toplamYaş = 0;
int sayaç = 0;
for (Kişi k : şahıslar) {
if (k != null) {
if (k instanceof Karakter) {
toplamYaş += ((Karakter) k).yaş;
sayaç++;
}
}
}
ortalamaYaş = (double) toplamYaş / sayaç;
return ortalamaYaş;
}
public int getKişilerinToplamKilosu() {
int toplamKilo = 0;
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] != null) {
toplamKilo += şahıslar[i].kilo;
}
}
return toplamKilo;
}
public int getKarakterlerinToplamKilosu() {
int toplamKilosu = 0;
for (Kişi k : şahıslar) {
if (k != null) {
if (k instanceof Karakter) {
toplamKilosu += ((Karakter) k).kilo;
}
}
}
return toplamKilosu;
}
public double getKişilerinKilolarıOrtalaması() {
return (double) getKişilerinToplamKilosu() / getKişiSayısı();
}
public double getKarakterlerinKilolarıOrtalaması() {
return (double) getKarakterlerinToplamKilosu() / getKarakterSayısı();
}
public int getKişilerinToplamBoyu() {
int toplamBoy = 0;
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] != null) {
toplamBoy += şahıslar[i].boy;
}
}
return toplamBoy;
}
public int getKarakterlerinToplamBoyu() {
int toplamBoy = 0;
for (Kişi k : şahıslar) {
if (k != null) {
if (k instanceof Karakter) {
toplamBoy += ((Karakter) k).boy;
}
}
}
return toplamBoy;
}
public double getKişilerinBoylarıOrtalaması() {
return (double) getKişilerinToplamBoyu() / getKişiSayısı();
}
public double getKarakterlerinBoylarıOrtalaması() {
return (double) getKarakterlerinToplamBoyu() / getKarakterSayısı();
}
public void kişiOluşturupEkle() {
if (getKişiSayısı() < şahıslar.length) {
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == null) {
Kişi k = new Kişi();
şahıslar[i] = k;
break;
}
}
} else {
System.out.println("Kişi oluşturulup eklenemedi!");
}
}
public void kişiOluşturupEkle(int oluşturulacakKişiSayısı) {
int boşAlan = 0;
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] == null) {
boşAlan++;
}
}
if (boşAlan < oluşturulacakKişiSayısı) {
System.out.println("Mekanda bu sayıda yer yoktur!");
} else {
for (int i = 0; i < oluşturulacakKişiSayısı; i++) {
for (int j = 0; j < şahıslar.length; j++) {
if (şahıslar[j] == null) {
Kişi k = new Kişi();
şahıslar[j] = k;
break;
}
}
}
}
}
public boolean isKişiBurda(Kişi k) {
boolean burda = false;
for (int i = 0; i < şahıslar.length; i++) {
if (şahıslar[i] != null && şahıslar[i] == k) {
burda = true;
}
}
return burda;
}
}
|
import java.util.ArrayList;
import java.io.IOException;
import java.io.Serializable;
@SuppressWarnings("serial")
public class VipassanaSystem implements Serializable
{
// Defining and preparing array lists
private ArrayList<Member> memberList;
private ArrayList<Event> eventList;
private ArrayList<Lecturer> lecturerList;
public VipassanaSystem()
{
memberList = new ArrayList<Member>();
eventList = new ArrayList<Event>();
lecturerList = new ArrayList<Lecturer>();
readAllData();
}
// Managing member stuff
public void addMember(Member member)
{
memberList.add(member);
}
public void removeMember(Member member)
{
memberList.remove(member);
}
public Member getMemberByName(String name)
{
Member memberToGet = null;
for (Member d : memberList)
{
if (d.getName().equals(name))
{
memberToGet = d;
}
}
return memberToGet;
}
public Member getMemberByEmail(String email)
{
Member memberToGet = null;
for (Member d : memberList)
{
if (d.getEmail().equals(email))
{
memberToGet = d;
}
}
return memberToGet;
}
public Member getMemberByNameAndEmail(String name, String email)
{
Member memberToGet = null;
for (Member d : memberList)
{
if (d.getName().equals(name) && d.getEmail().equals(email))
{
memberToGet = d;
}
}
return memberToGet;
}
public void removeMember(String name, String email)
{
Member memberToGet = null;
for (Member d : memberList)
{
if (d.getName().equals(name) && d.getEmail().equals(email))
{
memberToGet = d;
}
memberList.remove(memberList.indexOf(memberToGet));
break;
}
}
public ArrayList<Member> getMemberList()
{
return memberList;
}
// Done with member
/******************************************************************************/
// Event list
public void addEvent(Event event)
{
eventList.add(event);
}
public void removeEvent(Event event)
{
eventList.remove(event);
}
public void removeEventByTitle(String title)
{
Event eventToGet = null;
for (Event d : eventList)
{
if (d.getTitle().equals(title))
{
eventToGet = d;
}
eventList.remove(eventList.indexOf(eventToGet));
break;
}
}
public ArrayList<Event> getEventByType(String type)
{
ArrayList<Event> eventsNameList = new ArrayList<Event>();
for (Event d : eventList)
{
if (d.getType() != null && d.getType().contains(type))
{
eventsNameList.add(d);
}
}
return eventsNameList;
}
public Event getEventByTitle(String title)
{
Event eventToGet = null;
for (Event d : eventList)
{
if (d.getTitle().equals(title))
{
eventToGet = d;
break;
}
}
return eventToGet;
}
@SuppressWarnings("unlikely-arg-type")
public ArrayList<Event> getEventByLecturer(Lecturer lecturer)
{
ArrayList<Event> eventsLecturerList = new ArrayList<Event>();
for (Event d : eventList)
{
if (d.getLecturer() != null && lecturer.equals(d.getLecturer()))
{
eventsLecturerList.add(d);
}
}
return eventsLecturerList;
}
public ArrayList<Event> getEventByCategory(String category)
{
ArrayList<Event> eventsCategoryList = new ArrayList<Event>();
for (Event d : eventList)
{
if (d.getCategory() != null && d.getCategory().contains(category))
{
eventsCategoryList.add(d);
}
}
return eventsCategoryList;
}
public ArrayList<Event> getUnfinalizedEvents()
{
ArrayList<Event> unDoneEvents = new ArrayList<Event>();
for (Event d : eventList)
{
if (d.isFinalized() == false)
{
unDoneEvents.add(d);
}
}
return unDoneEvents;
}
public ArrayList<Event> getFinalizedEvents()
{
ArrayList<Event> doneEvents = new ArrayList<Event>();
for (Event d : eventList)
{
if (d.isFinalized() == true)
{
doneEvents.add(d);
}
}
return doneEvents;
}
public ArrayList<Event> getEventList()
{
return eventList;
}
// End of Event section
/********************************************************************************************/
// Lecturer list
public void addLecturer(Lecturer lecturer)
{
lecturerList.add(lecturer);
}
public void removeLecturer(Lecturer lecturer)
{
lecturerList.remove(lecturer);
}
public void removeLecturer(String name, String email)
{
Lecturer lecturerToGet = null;
for (Lecturer d : lecturerList)
{
if (d.getName().equals(name) && d.getEmail().equals(email))
{
lecturerToGet = d;
}
lecturerList.remove(lecturerList.indexOf(lecturerToGet));
break;
}
}
public Lecturer getLecturerByName(String name)
{
Lecturer lecturerToGet = null;
for (Lecturer d : lecturerList)
{
if (d.getName().equals(name))
{
lecturerToGet = d;
}
}
return lecturerToGet;
}
public Lecturer getLecturerByNameAndCategory(String name, String category)
{
Lecturer lecturerToGet = null;
for (Lecturer d : lecturerList)
{
if (d.getName().equals(name) && d.getCategory().equals(category))
{
lecturerToGet = d;
}
}
return lecturerToGet;
}
public ArrayList<Lecturer> getLecturerByCategory(String category)
{
ArrayList<Lecturer> lecturersCategoryList = new ArrayList<Lecturer>();
for (Lecturer d : lecturerList)
{
if (d.getCategory().contains(category))
{
lecturersCategoryList.add(d);
}
}
return lecturersCategoryList;
}
public ArrayList<Lecturer> getLecturerList()
{
return lecturerList;
}
// File handler calls
public void saveEventsData()
{
try {
FileHandler.writeEventFile(eventList);
}
catch(IOException e)
{
}
}
public void saveMembersData()
{
try {
FileHandler.writeMemberFile(memberList);
}
catch(IOException e)
{
}
}
public void saveLecturersData()
{
try {
FileHandler.writeLecturerFile(lecturerList);
}
catch(IOException e)
{
}
}
public void readAllData()
{
try {
eventList = FileHandler.readEventFile();
lecturerList = FileHandler.readLecturerFile();
memberList = FileHandler.readMemberFile();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
package org.collections;
public class Node<E> {
E elem;
Node<E> next;
Node(E elem) {
this.elem = elem;
}
Node(E elem, Node<E> next) {
this.elem = elem;
this.next = next;
}
}
|
package br.usp.memoriavirtual.controle;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import br.usp.memoriavirtual.modelo.entidades.Aprovacao;
import br.usp.memoriavirtual.modelo.entidades.Instituicao;
import br.usp.memoriavirtual.modelo.entidades.Usuario;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarInstituicaoRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.ExcluirInstituicaoRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.MemoriaVirtualRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.UtilMultimidiaRemote;
import br.usp.memoriavirtual.utils.MVModeloAcao;
import br.usp.memoriavirtual.utils.MVModeloEmailParser;
import br.usp.memoriavirtual.utils.MVModeloEmailTemplates;
import br.usp.memoriavirtual.utils.MVModeloMapeamentoUrl;
import br.usp.memoriavirtual.utils.MVModeloParametrosEmail;
import br.usp.memoriavirtual.utils.MensagensDeErro;
@ManagedBean(name = "excluirInstituicaoMB")
@SessionScoped
public class ExcluirInstituicaoMB extends EditarInstituicaoMB implements
Serializable {
private static final long serialVersionUID = 1147425267036231710L;
@EJB
private ExcluirInstituicaoRemote excluirInstituicaoEJB;
@EJB
private MemoriaVirtualRemote memoriaVirtualEJB;
@EJB
private EditarInstituicaoRemote editarInstituicaoEJB;
@EJB
private UtilMultimidiaRemote utilMultimidiaEJB;
private Instituicao instituicao = new Instituicao();
private String validade = "1";
private String justificativa = "";
private Aprovacao aprovacao = null;
private String analista;
private MensagensMB mensagens;
private Usuario solicitante = new Usuario();
public ExcluirInstituicaoMB() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
this.mensagens = (MensagensMB) resolver.getValue(
facesContext.getELContext(), null, "mensagensMB");
}
@Override
public String selecionarInstituicao() {
try {
this.instituicao = this.editarInstituicaoEJB
.getInstituicao(this.id);
return this.redirecionar("/restrito/excluirinstituicao.jsf", true);
} catch (ModeloException m) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
m.printStackTrace();
return null;
}
}
public List<SelectItem> getAnalistas() {
List<SelectItem> opcoes = new ArrayList<SelectItem>();
try {
Usuario usuario = (Usuario) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("usuario");
List<Usuario> analistas = this.excluirInstituicaoEJB
.listarAnalistas(this.instituicao, usuario);
for (Usuario u : analistas) {
opcoes.add(new SelectItem(u.getId(), u.getNomeCompleto()));
}
} catch (ModeloException m) {
m.printStackTrace();
}
return opcoes;
}
public String solicitarExclusao() {
if (this.validar()) {
try {
int dias = new Integer(this.validade).intValue();
Calendar calendario = Calendar.getInstance();
calendario.setTime(new Date());
calendario.add(Calendar.DATE, dias);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiraEm = dateFormat.format(calendario.getTime());
Aprovacao aprovacao = new Aprovacao();
aprovacao.setAcao(MVModeloAcao.excluir_instituicao);
Usuario analista = memoriaVirtualEJB.getUsuario(this.analista);
aprovacao.setAnalista(analista);
aprovacao.setDados("id;" + this.instituicao.getId()
+ ";justificativa;" + this.justificativa);
aprovacao.setExpiraEm(calendario.getTime());
Usuario solicitante = (Usuario) FacesContext
.getCurrentInstance().getExternalContext()
.getSessionMap().get("usuario");
aprovacao.setSolicitante(solicitante);
Long id = this.excluirInstituicaoEJB.solicitarExclusao(
this.instituicao, aprovacao);
Map<String, String> tags = new HashMap<String, String>();
tags.put(MVModeloParametrosEmail.ANALISTA000.toString(),
analista.getNomeCompleto());
tags.put(MVModeloParametrosEmail.EXPIRACAO000.toString(),
expiraEm);
tags.put(MVModeloParametrosEmail.INSTITUICAO000.toString(),
this.instituicao.getNome());
tags.put(MVModeloParametrosEmail.JUSTIFICATIVA000.toString(),
this.justificativa);
tags.put(MVModeloParametrosEmail.SOLICITANTE000.toString(),
solicitante.getNomeCompleto());
Map<String, String> parametros = new HashMap<String, String>();
parametros.put("id", id.toString());
String url = this.memoriaVirtualEJB.getUrl(
MVModeloMapeamentoUrl.excluirInstituicao, parametros);
tags.put(MVModeloParametrosEmail.URL000.toString(), url);
String email = new MVModeloEmailParser().getMensagem(tags,
MVModeloEmailTemplates.excluirInstituicao);
String assunto = this
.traduzir("excluirInstituicaoAssuntoEmail");
this.memoriaVirtualEJB.enviarEmail(analista.getEmail(),
assunto, email);
this.getMensagens().mensagemSucesso(this.traduzir("sucesso"));
} catch (Exception e) {
e.printStackTrace();
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
}
}
return null;
}
public String aprovar() {
try {
this.aprovacao.setDados("instituicao;" + this.instituicao.getNome()
+ ";justificativa;" + this.justificativa);
this.excluirInstituicaoEJB
.aprovar(this.instituicao, this.aprovacao);
this.getMensagens().mensagemSucesso(this.traduzir("sucesso"));
return this.redirecionar("/restrito/index.jsf", true);
} catch (Exception e) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
e.printStackTrace();
return null;
}
}
public String negar() {
try {
this.aprovacao.setDados("instituicao;" + this.instituicao.getNome()
+ ";justificativa;" + this.justificativa);
this.excluirInstituicaoEJB.negar(this.instituicao, this.aprovacao);
this.getMensagens().mensagemSucesso(this.traduzir("sucesso"));
return this.redirecionar("/restrito/index.jsf", true);
} catch (Exception e) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
e.printStackTrace();
return null;
}
}
public void carregar() {
try {
String dados = this.aprovacao.getDados();
String[] tokens = dados.split(";");
for (int i = 0; i < tokens.length; ++i) {
if (tokens[i].equals("id")) {
this.instituicao = editarInstituicaoEJB
.getInstituicao(new Long(tokens[i + 1]));
}
if (tokens[i].equals("justificativa")) {
this.justificativa = tokens[i + 1];
}
}
this.solicitante = aprovacao.getSolicitante();
} catch (Exception e) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
e.printStackTrace();
}
}
@Override
public boolean validar() {
return this.validarJustificativa();
}
public boolean validarJustificativa() {
if (!this.justificativa.equals(null) && this.justificativa != null
&& this.justificativa.length() > 0) {
return true;
} else {
String args[] = { this.traduzir("justificativa") };
MensagensDeErro.getErrorMessage("erroCampoVazio", args,
"validacao-justificativa");
this.getMensagens().mensagemErro(this.traduzir("erroFormulario"));
return false;
}
}
// Getters e Setters
public Aprovacao getAprovacao() {
return aprovacao;
}
public void setAprovacao(Aprovacao aprovacao) {
this.aprovacao = aprovacao;
}
public String getNome() {
return nome;
}
public void setNome(String pnome) {
nome = pnome;
}
public void setInstituicao(Instituicao instituicao) {
this.instituicao = instituicao;
}
public Instituicao getInstituicao() {
return instituicao;
}
public void setValidade(String validade) {
this.validade = validade;
}
public String getValidade() {
return validade;
}
public void setJustificativa(String justificativa) {
this.justificativa = justificativa;
}
public String getJustificativa() {
return justificativa;
}
public String getAnalista() {
return analista;
}
public void setAnalista(String analista) {
this.analista = analista;
}
public MensagensMB getMensagens() {
return mensagens;
}
public void setMensagens(MensagensMB mensagens) {
this.mensagens = mensagens;
}
public Usuario getSolicitante() {
return solicitante;
}
public void setSolicitante(Usuario solicitante) {
this.solicitante = solicitante;
}
}
|
import java.util.*;
public class LinkListOne {
public static void main(String args[]) {
LinkedList mylist = new LinkedList();
mylist.add("It");// 链表中的第一个节点。
mylist.add("is");// 链表中的第二个节点。
mylist.add("a");// 链表中的第三个节点。
mylist.add("door");// 链表中的第四个节点。
int number = mylist.size();// 获取链表的长度。
for (int i = 0; i < number; i++) {
String temp = (String) mylist.get(i);
System.out.println("第" + i + "节点中的数据:" + temp);
}
}
}
|
package com.xiaoxiao.contorller.backend;
import com.xiaoxiao.feign.UserSSOFeignClient;
import com.xiaoxiao.pojo.XiaoxiaoUsers;
import com.xiaoxiao.service.backend.UserFeignService;
import com.xiaoxiao.utils.Cookie;
import com.xiaoxiao.utils.CookieUtils;
import com.xiaoxiao.utils.Result;
import com.xiaoxiao.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_blogs
* @date:2019/11/26:18:51
* @author:shinelon
* @Describe:
*/
@Controller
@RequestMapping(value = "/admin")
@CrossOrigin
public class UserController
{
@Autowired
private UserSSOFeignClient userSSOFeignClient;
@Autowired
private UserFeignService userFeignService;
@Value("${COOKIE_NAME}")
private String COOKIE_NAME;
/**
* 登录
*
* @param userName
* @param password
* @param response
* @param request
* @return
* @throws Exception
*/
@PostMapping(value = "/login")
public String login(@RequestParam(name = "userName") String userName,
@RequestParam(name = "password") String password,
HttpServletResponse response,
HttpServletRequest request) throws Exception
{
try
{
/**
* 获取Cookie
*/
String token = CookieUtils.getCookieValue(request, COOKIE_NAME, "utf-8");
Result login = this.userSSOFeignClient.login(userName, password, token);
if (login.getData() != null && login.getCode() == StatusCode.OK)
{
if (StringUtils.isEmpty(token) || !token.equals(login.getMessage()))
{
Cookie.setCookie(request, response, COOKIE_NAME, login.getMessage(), 259200, true);
/*CookieUtils.setCookie(request, response, COOKIE_NAME, login.getMessage(), 1800, "utf-8");*/
}
return "redirect:/admin/blogs";
}
} catch (Exception e)
{
e.printStackTrace();
}
return "redirect:/login";
}
/**
* 登出
*
* @param request
* @param response
*/
@GetMapping(value = "/login_out")
public String loginOut(HttpServletRequest request, HttpServletResponse response)
{
String token = CookieUtils.getCookieValue(request, COOKIE_NAME, "utf-8");
CookieUtils.deleteCookie(request, response, this.COOKIE_NAME);
this.userSSOFeignClient.loginOut(token);
return "redirect:/";
}
/**
* 展示我的个人信息
*
* @return
*/
@GetMapping(value = "/show_me")
@ResponseBody
public Result showMe(HttpServletRequest request)
{
String token = CookieUtils.getCookieValue(request, COOKIE_NAME, "utf-8");
return this.userSSOFeignClient.showMe(token);
}
/**
* 修改用户个人信息
* @return
*/
@PostMapping(value = "/update")
@ResponseBody
public Result update(XiaoxiaoUsers users){
return this.userFeignService.update(users);
}
/**
* 修改密码
* @return
*/
@PostMapping(value = "/updatePassword")
@ResponseBody
public Result updatePassword(XiaoxiaoUsers users,HttpServletRequest request){
String token = CookieUtils.getCookieValue(request, COOKIE_NAME, "utf-8");
return this.userFeignService.updatePassword(users,token);
}
}
|
package Index.Model;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.*;
public class CourseModel {
String course_name,course_begin,course_end;
String class_id,lesson_begin,lesson_end,teacher;
String course_date,place,action="";
ResultSet result;
public String toS(String s){
String str;
try{
str = new String(s.getBytes("ISO-8859-1"),"utf-8");
}
catch(Exception e){str="";}
return str;
}
public ResultSet getResult(){
return result;
}
public void setResult(ResultSet result){
this.result=result;
}
public String getAction(){
return action;
}
public void setAction(String action){
this.action=action;
}
public String getCourse_name(){
return course_name;
}
public void setCourse_name(String course_name){
this.course_name=toS(course_name);
}
public String getCourse_begin(){
return course_begin;
}
public void setCourse_begin(String course_begin){
this.course_begin=toS(course_begin);
}
public String getCourse_end(){
return course_end;
}
public void setCourse_end(String course_end){
this.course_end=toS(course_end);
}
public String getLesson_begin(){
return lesson_begin;
}
public void setLesson_begin(String lesson_begin){
this.lesson_begin=toS(lesson_begin);
}
public String getClass_id(){
return class_id;
}
public void setClass_id(String class_id){
this.class_id=toS(class_id);
}
public String getLesson_end(){
return lesson_end;
}
public void setLesson_end(String lesson_end){
this.lesson_end=toS(lesson_end);
}
public String getTeacher(){
return teacher;
}
public void setTeacher(String teacher){
this.teacher=toS(teacher);
}
public String getPlace(){
return place;
}
public void setPlace(String place){
this.place=toS(place);
}
public String getCourse_date(){
return course_date;
}
public void setCourse_date(String course_date){
this.course_date=toS(course_date);
}
}
|
import java.util.*;
public class ArraysTwo {
Scanner scanner = new Scanner(System.in);
void inputMatrix(int martix[][], int rows, int columns){
System.out.println("Start entering the matrix : ");
for(int i = 0 ; i < rows ; i++){
for(int j = 0 ; j < columns ; j++){
martix[i][j] = scanner.nextInt();
}
System.out.println();
}
}
void printMatrix(int matrix[][], int rows, int columns){
System.out.println("Printing the matrix ");
for(int i = 0 ; i <rows ; i++){
for(int j = 0 ; j < columns ; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
void transpose(int matrix[][], int rows, int columns){
int transposeMatrix[][] = new int[rows][columns];
inputMatrix(matrix, rows, columns);
for(int i = 0 ; i <rows ; i++){
for(int j = 0 ; j < columns ; j++){
transposeMatrix[j][i] = matrix[i][j];
}
}
printMatrix(transposeMatrix, rows, columns);
}
public static void main(String[] args){
int choice, rows, columns;
Scanner scanner = new Scanner(System.in);
ArraysTwo at = new ArraysTwo();
System.out.println("How many rows do you want in your array ? ");
rows = scanner.nextInt();
System.out.println("How many columns do you want in your array ? ");
columns = scanner.nextInt();
int matrix[][] = new int[rows][columns];
do{
System.out.println("1 : Calculate the transpose of the matrix");
System.out.println("2 : Exit the program");
choice = scanner.nextInt();
switch (choice) {
case 1 :
at.transpose(matrix,rows,columns);
break;
case 2 :
System.exit(1);
default:
System.out.println("Invalid input. Please try again.");
break;
}
}while(choice != 2);
}
}
|
package dr;
import java.io.Serializable;
public class MessageRequest implements Serializable {
private String id;
private String countryName;
private String cityName;
public MessageRequest(String id, String countryName, String cityName) {
this.id = id;
this.countryName = countryName;
this.cityName = cityName;
}
public String getId() {
return id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
|
package com.paleimitations.schoolsofmagic.common.blocks;
import com.paleimitations.schoolsofmagic.common.registries.BlockRegistry;
import com.paleimitations.schoolsofmagic.common.registries.TagRegistry;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.entity.item.ItemEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.ItemStack;
import net.minecraft.pathfinding.PathType;
import net.minecraft.state.IntegerProperty;
import net.minecraft.state.StateContainer;
import net.minecraft.state.properties.BlockStateProperties;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import javax.annotation.Nullable;
import java.util.Random;
public class HerbalTwineBlock extends Block {
public static final IntegerProperty AGE = BlockStateProperties.AGE_5;
protected static final VoxelShape SHAPE = Block.box(5.0D, 0.0D, 5.0D, 11.0D, 16.0D, 11.0D);
public HerbalTwineBlock(Properties prop) {
super(prop);
}
@Override
public ActionResultType use(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult result) {
ItemStack inHand = player.getItemInHand(hand);
if (state.getBlock() == BlockRegistry.HERBAL_TWINE.get()) {
for (HerbalTwineEntry entry : BlockRegistry.HERBAL_TWINE_ENTRIES) {
if (entry.undried.sameItem(inHand)) {
world.setBlockAndUpdate(pos, entry.block.defaultBlockState());
if(!player.isCreative())
inHand.shrink(1);
return ActionResultType.SUCCESS;
}
}
}
else {
HerbalTwineEntry entry = HerbalTwineEntry.getEntryFromBlock(this);
if(state.getValue(AGE) < 5) {
if(!player.addItem(entry.undried.copy())) {
if (world.isClientSide) {
world.addFreshEntity(new ItemEntity(world, pos.getX() + 0.5d, pos.getY() + 0.5d, pos.getZ() + 0.5d, entry.undried.copy()));
}
}
world.setBlockAndUpdate(pos, BlockRegistry.HERBAL_TWINE.get().defaultBlockState());
return ActionResultType.SUCCESS;
}
else {
if(!player.addItem(entry.dried.copy())) {
if (world.isClientSide) {
world.addFreshEntity(new ItemEntity(world, pos.getX() + 0.5d, pos.getY() + 0.5d, pos.getZ() + 0.5d, entry.dried.copy()));
}
}
world.setBlockAndUpdate(pos, BlockRegistry.HERBAL_TWINE.get().defaultBlockState());
return ActionResultType.SUCCESS;
}
}
return super.use(state, world, pos, player, hand, result);
}
public boolean isRandomlyTicking(BlockState state) {
return state.getValue(AGE) < 5;
}
public void randomTick(BlockState state, ServerWorld world, BlockPos pos, Random rand) {
if (state.getBlock() != BlockRegistry.HERBAL_TWINE.get()) {
int i = state.getValue(AGE);
if (i < 5 && rand.nextFloat() > 0.45f)
world.setBlock(pos, state.setValue(AGE, i + 1), 2);
}
}
public void onRemove(BlockState state, World world, BlockPos pos, BlockState p_196243_4_, boolean p_196243_5_) {
if (!state.is(p_196243_4_.getBlock())) {
if(state.getBlock() != BlockRegistry.HERBAL_TWINE.get()) {
HerbalTwineEntry entry = HerbalTwineEntry.getEntryFromBlock(this);
if (world.isClientSide) {
world.addFreshEntity(new ItemEntity(world, pos.getX() + 0.5d, pos.getY() + 0.5d, pos.getZ() + 0.5d, state.getValue(AGE) < 5 ? entry.undried.copy() : entry.dried.copy()));
}
}
super.onRemove(state, world, pos, p_196243_4_, p_196243_5_);
}
}
public VoxelShape getShape(BlockState p_220053_1_, IBlockReader p_220053_2_, BlockPos p_220053_3_, ISelectionContext p_220053_4_) {
return SHAPE;
}
public boolean propagatesSkylightDown(BlockState p_200123_1_, IBlockReader p_200123_2_, BlockPos p_200123_3_) {
return p_200123_1_.getFluidState().isEmpty();
}
public boolean isPathfindable(BlockState p_196266_1_, IBlockReader p_196266_2_, BlockPos p_196266_3_, PathType p_196266_4_) {
return p_196266_4_ == PathType.AIR && !this.hasCollision ? true : super.isPathfindable(p_196266_1_, p_196266_2_, p_196266_3_, p_196266_4_);
}
public boolean canSurvive(BlockState state, IWorldReader world, BlockPos pos) {
BlockState block = world.getBlockState(pos.relative(Direction.UP));
return block.isFaceSturdy(world, pos, Direction.DOWN);
}
@Nullable
public BlockState getStateForPlacement(BlockItemUseContext context) {
BlockState block = context.getLevel().getBlockState(context.getClickedPos());
return context.getClickedFace() == Direction.DOWN? this.defaultBlockState() : null;
}
public BlockState updateShape(BlockState blockstate, Direction direction, BlockState p_196271_3_, IWorld world, BlockPos pos, BlockPos p_196271_6_) {
return direction == Direction.UP && !blockstate.canSurvive(world, pos) ? Blocks.AIR.defaultBlockState() : super.updateShape(blockstate, direction, p_196271_3_, world, pos, p_196271_6_);
}
protected void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> p_206840_1_) {
p_206840_1_.add(AGE);
}
}
|
package com.foosbot.service.handlers.payloads;
import com.foosbot.service.match.TeamResult;
import com.foosbot.service.model.players.FoosballPlayer;
import lombok.Data;
import java.util.Set;
@Data
public class ExistingFoosballMatchPayload {
public FoosballPlayer reporter;
public Set<TeamResult> results;
public String timestamp;
public boolean isValid() {
return reporter.isValid()
&& !results.isEmpty()
&& timestamp != null;
}
}
|
package br.cwi.crescer.converters;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
/**
* @author Carlos H. Nonnemacher
*/
@FacesValidator("emailValidator")
public class EmailValidator implements Validator{
@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
//...
}
}
|
/**
* Created with IntelliJ IDEA.
* User: michael
* Date: 12/24/13
* Time: 12:00 AM
* To change this template use File | Settings | File Templates.
*/
import java.util.Scanner;
public class MethodsAndFields {
static double myPi = 3.14159;
static Scanner userInput = new Scanner(System.in);
static int randomNumber;
public static void main(String[] args){
System.out.println(addThem(1, 2));
int d = 5;
tryToChange(d);
System.out.println("main change "+d);
System.out.println(getRandomNum());
int guessResult = 1;
int randomGuess = 0;
while(guessResult!=-1){
System.out.print("Guess a number 1 - 10 ") ;
randomGuess = userInput.nextInt();
guessResult = checkGuess(randomGuess);
}
System.out.println("You got " + randomGuess);
}
public static int addThem(int a, int b){
double smallPi = 3.140 ;
return a+b;
}
/**
* Simple method to add 1 to to a variable
* @param d int to add number to
*/
public static void tryToChange (int d) {
d = d + 1;
System.out.println("try to change " + d);
}
public static int getRandomNum(){
randomNumber = (int) (Math.random() * 10);
return randomNumber;
}
public static int checkGuess(int guess){
if(guess == randomNumber){
return -1;
} else {
return 1;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.