text
stringlengths 10
2.72M
|
|---|
package com.tencent.mm.plugin.remittance.bankcard.ui;
import android.widget.Toast;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.remittance.bankcard.a.k;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.h.a;
class BankRemitBankcardInputUI$15 implements a {
final /* synthetic */ BankRemitBankcardInputUI mve;
final /* synthetic */ k mvk;
BankRemitBankcardInputUI$15(BankRemitBankcardInputUI bankRemitBankcardInputUI, k kVar) {
this.mve = bankRemitBankcardInputUI;
this.mvk = kVar;
}
public final void g(int i, int i2, String str, l lVar) {
x.e("MicroMsg.BankRemitBankcardInputUI", "operation response error: %s, %s", new Object[]{Integer.valueOf(this.mvk.muc.hUm), this.mvk.muc.hUn});
if (!bi.oW(this.mvk.muc.hUn)) {
Toast.makeText(this.mve, this.mvk.muc.hUn, 1).show();
}
this.mve.finish();
}
}
|
package com.example.hara.wkflsrhqlv11.DBConnect;
public class Value {
//login
public static String login_url = "http://cslab2.kku.ac.kr/~201341363/login.php";
//오늘,이번주 목표량 보내기
public static String reg_url = "http://cslab2.kku.ac.kr/~201341363/register_day.php";
//오늘 목표량 가져오기
public static String goal_get = "http://cslab2.kku.ac.kr/~201341363/Goal_get.php";
//이번주 목표량 가져오기
public static String goal_week = "http://cslab2.kku.ac.kr/~201341363/Goal_get_week.php";
//어제 목표량 가져오기
public static String goal_yesterday = "http://cslab2.kku.ac.kr/~201341363/Goal_get_yesterday.php";
//아이디 등록하기
public static String reg_user = "http://cslab2.kku.ac.kr/~201341363/register_user.php";
//리스트 가져오기
public static String List_get = "http://cslab2.kku.ac.kr/~201341363/List_get.php";
//리스트 가져오기
public static String List_day = "http://cslab2.kku.ac.kr/~201341363/Get_daysum.php";
//리스트 가져오기
public static String List_week = "http://cslab2.kku.ac.kr/~201341363/Get_weeksum.php";
//리스트 등록하기
public static String reg_list = "http://cslab2.kku.ac.kr/~201341363/register_List.php";
//카드 번호 가져오기
public static String Card_get = "http://cslab2.kku.ac.kr/~201341363/Card_get.php";
//올해 각 달마다 지출 내역
public static String Get_year_each_month = "http://cslab2.kku.ac.kr/~201341363/Get_year_each_month.php";
//원하는 달의 지출 내역
public static String want_day = "http://cslab2.kku.ac.kr/~201341363/want_day.php";
//모든 리스트 가져오기
public static String Get_list_day = "http://cslab2.kku.ac.kr/~201341363/Get_list_day.php";
// 이번달 각 목표량 가져오기
public static String Get_list_goal = "http://cslab2.kku.ac.kr/~201341363/Get_list_goal.php";
// 이번달 각 사용량 가져오기
public static String Goal_get_daysum = "http://cslab2.kku.ac.kr/~201341363/Goal_get_daysum.php";
}
|
package com.example.segundoparcialprog2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
static TextView titulo,resultado,respuesta1,respuesta2,respuesta3,respuesta4,respuesta5;
static RadioGroup grupo1;
static RadioButton unoa,unob,unoc,unod,dosa,dosb,dosc,dosd,tresa,tresb,tresc,tresd,cuatroa,cuatrob,cuatroc,cuatrod,cincoa,cincob,cincoc,cincod;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------------------------------------------------------------------------------------------------
cargarImportacionaesXML();
loadEvents();
//-----------------------------------------------------------------------------------------------------------------
titulo.setText(Html.fromHtml("<b>REAL QUIZ PROGRAMACION 2<BR/>BRANDOX MEJIA</b>"));
}
public void loadEvents(){
findViewById(R.id.verResultado).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Logica.getInstance().resolver();
}
});
findViewById(R.id.salir).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
System.exit(0);
}
});
}
public void cargarImportacionaesXML(){
titulo = findViewById(R.id.tituloprincipal);
resultado = findViewById(R.id.resultado);
respuesta1 = findViewById(R.id.respuesta1); respuesta2 = findViewById(R.id.respuesta2); respuesta3 = findViewById(R.id.respuesta3);
respuesta4 = findViewById(R.id.respuesta4);respuesta5 = findViewById(R.id.respuesta5);
grupo1 = findViewById(R.id.radioGroup1);
unoa = findViewById(R.id.unoa); unob = findViewById(R.id.unob); unoc = findViewById(R.id.unoc); unod = findViewById(R.id.unod);
dosa = findViewById(R.id.dosa); dosb = findViewById(R.id.dosb); dosc = findViewById(R.id.dosc); dosd = findViewById(R.id.dosd);
tresa = findViewById(R.id.tresa); tresb = findViewById(R.id.tresb); tresc = findViewById(R.id.tresc); tresd = findViewById(R.id.tresd);
cuatroa = findViewById(R.id.cuatroa); cuatrob = findViewById(R.id.cuatrob); cuatroc = findViewById(R.id.cuatroc); cuatrod = findViewById(R.id.cuatrod);
cincoa = findViewById(R.id.cincoa); cincob = findViewById(R.id.cincob); cincoc = findViewById(R.id.cincoc); cincod = findViewById(R.id.cincod);
}
}
|
package edu.floridapoly.polycamsportal;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import edu.floridapoly.polycamsportal.Database.CourseItem;
import edu.floridapoly.polycamsportal.Database.DatabaseHelper;
import edu.floridapoly.polycamsportal.Database.ScheduleItem;
import edu.floridapoly.polycamsportal.Database.UserItem;
import edu.floridapoly.polycamsportal.schedule.Course;
import edu.floridapoly.polycamsportal.schedule.CourseFetcher;
import edu.floridapoly.polycamsportal.schedule.CourseSession;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
public static final String USERNAME = "USERNAME";
private String username = "Username";
private DrawerLayout drawer;
public final DatabaseHelper myDb = new DatabaseHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
Bundle extras = getIntent().getExtras();
if (extras != null) {
username = extras.getString(USERNAME);
}
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
List<Course> fetched;
try {
fetched = new CourseFetcher().fetchCourses(28);
Log.d(TAG, "Fetched " + fetched.size() + " courses");
} catch (IOException ex) {
Log.e(TAG, "Failed to fetch courses", ex);
return null;
}
ArrayList<CourseItem> courses = new ArrayList<>();
for (Course c : fetched) {
CourseSession s = c.getSections().get(0).getSessions().get(0);
courses.add(new CourseItem(c.getTitle(), s.getStartTime().toString(), s.getEndTime().toString(),
s.getInstructor(), s.getRoom()));
}
for (CourseItem c: courses) {
myDb.insertCourse(c);
}
UserItem user;
//Add user
if (!myDb.userExists(username))
{
user = new UserItem(username, null);
myDb.insertUser(user);
ScheduleItem sample_schedule = new ScheduleItem("Sample Schedule", user.getName());
myDb.insertSchedule(sample_schedule);
user = new UserItem(user.getName(), sample_schedule.getName());
myDb.updateUser(user);
for (CourseItem c: courses.subList(0, 5))
{
myDb.insertCourseList(user, sample_schedule, c);
}
}
return null;
}
}.execute();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
TextView navUsername = (TextView) headerView.findViewById(R.id.username_header);
navUsername.setText(username);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = new CourseListFragment();
Bundle bundle = new Bundle();
String favSchedule = "";
if (myDb.getUser(username) != null)
{
favSchedule = myDb.getUser(username).getFavoriteSchedule();
}
bundle.putString(CourseListFragment.USERNAME, username);
bundle.putString(CourseListFragment.SCHEDULENAME, favSchedule);
fragment.setArguments(bundle);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
navigationView.setCheckedItem(R.id.nav_schedule);
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment fragment;
Bundle bundle;
switch (item.getItemId())
{
case R.id.nav_schedules:
fragment = new SchedulesFragment();
bundle = new Bundle();
bundle.putString(SchedulesFragment.USERNAME, username);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
break;
case R.id.nav_schedule:
fragment = new CourseListFragment();
bundle = new Bundle();
// TODO: Modify to be favorite schedule
String favSchedule = "";
if (myDb.getUser(username) != null)
{
favSchedule = myDb.getUser(username).getFavoriteSchedule();
}
bundle.putString(CourseListFragment.USERNAME, username);
bundle.putString(CourseListFragment.SCHEDULENAME, favSchedule);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, new SettingsFragment())
.commit();
break;
case R.id.nav_logout:
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra(LoginActivity.ACTION, LoginActivity.LOGOUT);
startActivity(intent);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed()
{
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
|
import java.util.ArrayList;
public class Ctrl {
Net best_Net;
double best_Score;
public Ctrl(int pop_per_generation, int number_of_generations, ArrayList<ArrayList<Double>> input, ArrayList<ArrayList<Double>> answers, double mod_W, double mod_Bias) {
this.best_Net = (new Generation(pop_per_generation, input, answers)).best;
this.best_Score = (new Scorer(this.best_Net, input, answers)).score;
Net current = this.best_Net;
for(int i = 0; i < pop_per_generation; i++) {
current.modulate(mod_W, mod_Bias);
if((new Scorer(current, input, answers)).score < this.best_Score) {
this.best_Net = current;
this.best_Score = (new Scorer(this.best_Net, input, answers)).score;
}
}
}
}
|
package playerAuction.client;
import java.util.Scanner;
import com.mindtree.exceptions.DuplicateEntryException;
import com.mindtree.exceptions.InvalidBestFigureException;
import com.mindtree.exceptions.InvalidCategoryException;
import com.mindtree.exceptions.InvalidTeamNameException;
import com.mindtree.exceptions.NotABatsmanException;
import com.mindtree.exceptions.NotABowlerException;
import playerAuctionSystem.dao.PlayerDaoImpl;
import playerAuctionSystem.entity.Player;
import playerAuctionSystem.entity.Team;
import playerAuctionSystem.entity.TeamPlayer;
import playerAuctionSystem.manager.PlayerManagerImpl;
import playerAuctionSystem.manager.TeamManagerImpl;
public class PlayerAuctionSystemClient {
public static void main(String[] args) throws InvalidCategoryException, InvalidTeamNameException,
NotABatsmanException, NotABowlerException, DuplicateEntryException, InvalidBestFigureException {
PlayerManagerImpl validationPlayer = new PlayerManagerImpl();
TeamManagerImpl validationTeam = new TeamManagerImpl();
Player playerDetails1 = new Player();
Team team1 = new Team();
TeamPlayer teamPlayer = new TeamPlayer();
PlayerDaoImpl playerDetails = new PlayerDaoImpl();
System.out.println("Enter your choice \n1. Add a player\n2. Display player \n3. Exit");
Scanner scan = new Scanner(System.in);
int choice = scan.nextInt();
while (choice != 3) {
switch (choice) {
case 1:
System.out.println(" Add a player ");
System.out.print("Enter player name :-");
String playerName = scan.next();
if (!validationPlayer.isPlayerNameValid(playerName))
throw new DuplicateEntryException("Player details already exist in the database");
else
playerDetails1.setPlayerName(playerName);
System.out.print("Enter category :-");
String category = scan.next();
if (validationPlayer.validateCategory(category) == false) {
throw new InvalidCategoryException("Invalid category name please check your input");
} else
playerDetails1.setCategory(category);
System.out.print("Enter Highest Score :-");
int highestScore = scan.nextInt();
if (category.equalsIgnoreCase("Batsman")) {
if (validationPlayer.validateHighestScore(highestScore) == false)
throw new NotABatsmanException("Invalid Batsman, please check your input");
else
playerDetails1.setHighestScore(highestScore);
} else
playerDetails1.setHighestScore(highestScore);
System.out.print("Enter Best figure :-");
String bestFigure = scan.next();
if (bestFigure.matches("[\\d]+[/][\\d]+"))
if (category.equalsIgnoreCase("Bowler")) {
if (validationPlayer.validateBestFigure(highestScore, bestFigure) == false)
throw new NotABowlerException("Invalid Batsman, please check your input");
else
playerDetails1.setBestFigure(bestFigure);
} else
playerDetails1.setBestFigure(bestFigure);
else
throw new InvalidBestFigureException("Inavalid bestfigure, please check your input");
System.out.print("Enter Team Name :-");
String teamName = scan.next();
if (validationTeam.validateTeamName(teamName) == false) {
throw new InvalidTeamNameException("Invalid team name, please check your input");
} else
team1.setTeamName(teamName.toUpperCase());
playerDetails.insertPlayers(playerDetails1);
break;
case 2:
System.out.println(" Display players ");
System.out.println(" Enter team name: ");
String teamNameInput = scan.next();
if (validationTeam.validateTeamName(teamNameInput) == false) {
throw new InvalidTeamNameException("Invalid team name, please check your input");
} else
team1.setTeamName(teamNameInput.toUpperCase());
break;
case 3:
System.out.println("Exit");
break;
default:
System.out.println("you entered a wrong choice");
}
System.out.println("Enter your choice \n1. Add a player\n2. Display player \n3. Exit");
choice = scan.nextInt();
}
}
}
|
package logic.data;
public enum EnumGenders {
MALE("Male"),
FEMALE("Female"),
OTHER("Other");
private final String gender;
EnumGenders(String gender) {
this.gender = gender;
}
public String toString() {
return this.gender;
}
}
|
package lnyswz.oa.dao.impl;
import java.util.List;
import lnyswz.oa.bean.Duty;
import lnyswz.oa.dao.DutyDAO;
import lnyswz.oa.utils.AbstractPagerManager;
import lnyswz.oa.utils.PagerModel;
public class DutyDAOImpl extends AbstractPagerManager implements DutyDAO {
public void addDuty(Duty duty) {
this.getHibernateTemplate().save(duty);
}
public void deleteDuty(int dutyId) {
this.getHibernateTemplate().delete(this.getHibernateTemplate().load(Duty.class, dutyId));
}
public void modifyDuty(Duty duty) {
this.getHibernateTemplate().update(duty);
}
public Duty findDuty(int dutyId) {
return (Duty)this.getHibernateTemplate().load(Duty.class, dutyId);
}
public PagerModel findDuties() {
//return this.getHibernateTemplate().find("from Duty");
return this.searchPaginated("from Duty");
}
public List<Duty> getDuties() {
return this.getHibernateTemplate().find("from Duty");
//return this.searchPaginated("from Duty");
}
}
|
package com.eagle.order.service.impl;
import com.eagle.order.mapper.PermissionMapper;
import com.eagle.order.mapper.RoleMapper;
import com.eagle.order.domain.Role;
import com.eagle.order.domain.RoleExample;
import com.eagle.order.service.RoleService;
import com.eagle.order.util.QueryData;
import com.eagle.order.util.ReturnResult;
import com.eagle.order.vo.PermissionVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
* @Description
* @Author hongling.lin
* @Date 2019/4/15
*/
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionMapper permissionMapper;
@Override
public ReturnResult queryList(QueryData<RoleExample> queryData) {
PageInfo pageInfo = queryData.getPageInfo();
RoleExample param = queryData.getParam();
if (pageInfo == null) {
List<Role> roleList = roleMapper.selectByExample(param);
return ReturnResult.ok(roleList);
}
PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
List<Role> roleList = roleMapper.selectByExampleNew(param);
PageInfo<Role> resultInfo = new PageInfo<Role>(roleList);
return ReturnResult.ok(resultInfo);
}
@Override
@Transactional
public ReturnResult saveOrUpdate(Role role) {
if (role.getId() == null) {
role.setCreateTime(new Date());
role.setUpdateTime(new Date());
roleMapper.insert(role);
} else {
role.setUpdateTime(new Date());
roleMapper.updateByPrimaryKey(role);
}
return ReturnResult.ok();
}
@Override
@Transactional
public ReturnResult delete(int id) {
roleMapper.deleteByPrimaryKey(id);
return ReturnResult.ok();
}
@Override
public ReturnResult permissionList(){
List<PermissionVO> permissionVOList = permissionMapper.permissionList();
return ReturnResult.ok(permissionVOList);
}
}
|
package com.gtfs.service.interfaces;
import java.io.Serializable;
import java.util.List;
import com.gtfs.bean.LicPremFreqAllowARMst;
public interface LicPremFreqAllowARMstService extends Serializable{
List<String> findPayModeByProdId(Long prodId);
List<Object> checkForAddbRiderByAgeAndProdId(Integer age,Long prodId);
List<LicPremFreqAllowARMst> checkForSumAssuredByProdIdTerm(Long term,Long prodId);
}
|
import java.util.ArrayList;
public class RoomManager {//대화방의 정보표현 객체
String title = null;//방제목
int count;//방 인원수
String boss;//방장(방 개설자)
ArrayList<String> userName = new ArrayList<>(); //userName을 담는다.
}
|
package example.testgrader.test;
import android.test.AndroidTestCase;
public class AndroidTest extends AndroidTestCase {
protected double fValue1;
protected double fValue2;
protected void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
public void testAdd() {
double result= fValue1 + fValue2;
assertTrue(result == 5.0);
}
}
|
package pl.connectis.cschool.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import pl.connectis.cschool.shared.Invoice;
import pl.connectis.cschool.shared.Product;
import pl.connectis.cschool.shared.dto.InvoiceDTO;
import java.util.List;
public interface InvoiceServiceAsync {
void allInvoiceDTO(AsyncCallback<List<InvoiceDTO>> async);
void findProductById(Long invoiceId, AsyncCallback<List<Product>> async);
void addInvoice(Invoice invoice, AsyncCallback<Void> async);
}
|
package com.omnicuris.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.omnicuris.dto.OrderDto;
import com.omnicuris.service.OrderProductsService;
@RestController
public class OrderProductsController {
@Autowired
OrderProductsService productService;
// creating new order
@PostMapping(path = "/createNewOrder", consumes = MediaType.APPLICATION_JSON_VALUE)
public void addItems(@RequestBody OrderDto orderDto) {
productService.addItems(orderDto);
}
// getting specific orderId
@GetMapping(path = "/getOrderInfo/{orderId}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<OrderDto> getOrderById(@PathVariable("orderId") int orderId) {
OrderDto orderDto = productService.getOrder(orderId);
return new ResponseEntity<OrderDto>(orderDto, new
HttpHeaders(), HttpStatus.OK);
}
}
|
package week5lab1.sidm.com.game;
/**
* Created by User on 25/11/2017.
*/
import android.graphics.Canvas;
import android.graphics.Color;
import android.provider.Settings;
import android.view.SurfaceHolder;
public class UpdateThread extends Thread
{
static final long targetFPS = 60;
private Gameview view = null;
private SurfaceHolder holder = null;
private boolean isRunning = false;
//Constructor
public UpdateThread(Gameview _view)
{
view = _view;
holder = _view.getHolder();
//Init here game
SGame.Instance.Init(_view);
}
public boolean isRunning()
{
return isRunning;
}
public void Initialize()
{
isRunning = true;
}
public void Terminate()
{
isRunning = false;
}
@Override
public void run()
{
//FPS
long FPS = 1000 / targetFPS; //1000 is milliseconds
//Delta Time
long startTime = 0;
//Another variable to calculate delta time
long prevTime = System.nanoTime();
while (isRunning)
{
// Update Start!
startTime = System.currentTimeMillis(); //For framerate controller
// Using prevtime vs currtime to get delta time
long currTime = System.nanoTime();
float deltaTime = (float)((currTime - prevTime) / 1000000000.0f);
prevTime = currTime;
SGame.Instance.Update(deltaTime);
// Update End...
// Rendering Start!
Canvas canvas = holder.lockCanvas(null);
if (canvas != null)
{
// prevents 2 threads from rendering at same time
synchronized (holder)
{
//Render the whole screen black
canvas.drawColor(Color.BLACK);
//Render game
SGame.Instance.Render(canvas);
}
// This is the part to do the render
holder.unlockCanvasAndPost(canvas);
}
// Rendering System end.
//Post Update/Render
try
{
long sleepTime = FPS - (System.currentTimeMillis() - startTime);
if (sleepTime > 0)
sleep(sleepTime);
}
catch (InterruptedException e)
{
Terminate();;
}
//End of loop!
}
}
}
|
/**
*
*/
package io.github.liuzm.manage.api;
import java.util.List;
import io.github.liuzm.distribute.common.model.Node;
/**
*
* @author qydpc
*
*/
public interface ClientService {
public List<Node> getClients();
}
|
package view;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import railroad.Facade;
public class SpeedWindow {
JFrame _window;
public SpeedWindow()
{
_window = new JFrame("Adicionador de trem");
_window.setSize(300, 140);
_window.setLocationRelativeTo(null);
_window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_setupView();
_window.setVisible(true);
_window.setResizable(false);
}
private void _setupView()
{
JPanel panel = new JPanel();
/************************ 60 **************************/
JButton left60Button = new JButton("Add 60 esquerda");
left60Button.setAlignmentX(Component.CENTER_ALIGNMENT);
left60Button.addActionListener(e -> {
Facade.getInstance().AddLeft(60);
});
panel.add(left60Button);
JButton right60Button = new JButton("Add 60 direita");
right60Button.setAlignmentX(Component.CENTER_ALIGNMENT);
right60Button.addActionListener(e -> {
Facade.getInstance().AddRight(60);
});
panel.add(right60Button);
/************************ 80 **************************/
JButton left80Button = new JButton("Add 80 esquerda");
left80Button.setAlignmentX(Component.CENTER_ALIGNMENT);
left80Button.addActionListener(e -> {
Facade.getInstance().AddLeft(80);
});
panel.add(left80Button);
JButton right80Button = new JButton("Add 80 direita");
right80Button.setAlignmentX(Component.CENTER_ALIGNMENT);
right80Button.addActionListener(e -> {
Facade.getInstance().AddRight(80);
});
panel.add(right80Button);
/************************ 100 **************************/
JButton left100Button = new JButton("Add 100 esquerda");
left100Button.setAlignmentX(Component.CENTER_ALIGNMENT);
left100Button.addActionListener(e -> {
Facade.getInstance().AddLeft(100);
});
panel.add(left100Button);
JButton right100Button = new JButton("Add 100 direita");
right100Button.setAlignmentX(Component.CENTER_ALIGNMENT);
right100Button.addActionListener(e -> {
Facade.getInstance().AddRight(100);
});
panel.add(right100Button);
_window.setContentPane(panel);
}
}
|
package com.javazuki.samples.javase.array;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
public class ArrayTest {
/**
* 「EFFECTIVE JAVA 第2版」P.116より引用。<br/>
* コンパイルエラーにならず、実行時にArrayStoreExceptionになる。
*/
@Test(expected = ArrayStoreException.class) public void testVariant() {
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in";
}
/**
* 参照型による配列→List変換の検証
*/
@Test public void testReferenceArrayConvertToList() throws Exception {
String[] arrayMessages = { "good morning", "hello", "good afternoon" };
List<String> listMessages = Arrays.asList(arrayMessages);
assertThat("good morning", is(listMessages.get(0)));
assertThat("hello", is(listMessages.get(1)));
assertThat("good afternoon", is(listMessages.get(2)));
}
/**
* プリミティブ型による配列→List変換の検証<br/>
* プリミティブ型の場合は、 Arrays.asList()ではダメ。
*/
@Test public void testPrimitiveArrayConvertToList() throws Exception {
int[] arrayScores = { 30, 80, 40 };
List<Object> fromAsListScores = Arrays.asList(arrayScores);
assertThat(30, is(not(fromAsListScores.get(0))));
System.out.println(fromAsListScores);
List<Integer> listScores = Arrays.stream(arrayScores)
.mapToObj(Integer::valueOf)
.collect(Collectors.toList());
assertThat(30, is(listScores.get(0)));
assertThat(80, is(listScores.get(1)));
assertThat(40, is(listScores.get(2)));
}
@Test public void testEqualsArray() throws Exception {
int[] firstArray = { 30, 80, 40 };
int[] secondArray = { 30, 80, 40 };
assertThat(firstArray.equals(secondArray), is(false));
assertThat(Arrays.equals(firstArray, secondArray), is(true));
System.out.println("firstArray.equals(secondArray) is " + firstArray.equals(secondArray));
System.out.println("Arrays.equals(firstArray, secondArray) is " + Arrays.equals(firstArray, secondArray));
}
}
|
package com.company.Data.initialize;
import com.company.Data.connection.ConnectionToDatabase;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.SQLException;
/**
* Created by semen on 08.10.2015.
*/
public class NewDatabaseCreator {
private String dataBaseName;
private String createDatabaseQuery =
"CREATE DATABASE " +dataBaseName+" data CHARACTER SET utf8 COLLATE utf8_general_ci";
public NewDatabaseCreator(String dataBaseName){
this.dataBaseName=dataBaseName;
if (new ExistenceDataBase(dataBaseName).checkExeistanceDataBase()==false)
createDatabase();
}
public boolean createDatabase(){
Boolean flag = false;
Connection connection = null;
Statement statement = null;
try {
//Загружаем драйвер
Class.forName("com.mysql.jdbc.Driver");
connection = new ConnectionToDatabase().getConnection();
statement = (Statement) connection.createStatement();
statement.executeUpdate(createDatabaseQuery);
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
//позакрываем теперь все
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return flag;
}
}
|
package edu.cmu.lti.oaqa.openqa.test.team10.retrieval;
/*
* Copyright 2012 Carnegie Mellon University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.List;
import dragon.nlp.tool.PorterStemmer;
import edu.cmu.lti.bio.alkesh.customtypes.GeneCount;
import edu.cmu.lti.oaqa.framework.data.Keyterm;
import edu.cmu.lti.oaqa.framework.data.RetrievalResult;
import edu.cmu.lti.oaqa.openqa.test.team10.keyterm.SimilarNGramExtractor;
/**
* RS boosting phrase information
*
* @author Zeyuan Li <zeyuanl@cs.cmu.edu>
*
*/
public class BoostedSolrRetrievalStrategist extends QueryRelaxationSolrRetrievalStrategist {
@Override
protected List<RetrievalResult> retrieveDocuments(String questionText, List<Keyterm> keyterms) {
String query = "";
try {
query = formulateQuery(questionText, keyterms);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retrieveDocuments(query);
}
/**
* formulateQuery: boosting the long phrase and using stemming
* @throws Exception
*
* */
protected String formulateQuery(String questionText, List<Keyterm> keyterms) throws Exception {
StringBuffer result = new StringBuffer();
PorterStemmer stemmer = new PorterStemmer();
SimilarNGramExtractor synextrator = new SimilarNGramExtractor();
for (int i = 0; i < keyterms.size(); i++) {
Keyterm keyterm = keyterms.get(i);
String text = keyterm.getText();
// add quotation marks for compound phrases
if (text.matches(".*?\\s.*+"))
text = "\"" + text + "\"";
String textstem = stemmer.stem(text);
double weight = (keyterm.getProbability()-0.0)<1e-6 ? 1.0 : keyterm.getProbability();
int coef = text.split(" ").length;
String qs = String.format("(%s OR %s)^%f", text, textstem, coef * weight);
// append synonym in query string
List<GeneCount> syns = synextrator.getSynonyms(text);
result.append("(" + qs);
for (int j = 0; j < syns.size(); j++) {
String cursyn = syns.get(j).getGeneName();
if (cursyn.matches(".*?\\s.*+"))
cursyn = "\"" + cursyn + "\"";
result.append(" OR " + cursyn);
}
result.append(")"); // TODO: boost by keyterm weight
if (i < keyterms.size() - 1)
result.append(" AND ");
}
String query = result.toString();
System.out.println(" QUERY: " + query);
return query;
}
}
|
package com.cskaoyan.bean;
public class MaterialReceive {
private String receiveId;
private int amount;
private MaterialMessage material;
private String receiveDate;
private String receiver;
private String sender;
private String note;
@Override
public String toString() {
return "MaterialReceive{" +
"receiveId='" + receiveId + '\'' +
", amount=" + amount +
", material=" + material +
", receiveDate='" + receiveDate + '\'' +
", receiver='" + receiver + '\'' +
", sender='" + sender + '\'' +
", note='" + note + '\'' +
'}';
}
public MaterialMessage getMaterial() {
return material;
}
public void setMaterial(MaterialMessage material) {
this.material = material;
}
public String getReceiveId() {
return receiveId;
}
public void setReceiveId(String receiveId) {
this.receiveId = receiveId;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getReceiveDate() {
return receiveDate;
}
public void setReceiveDate(String receiveDate) {
this.receiveDate = receiveDate;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
|
package com.example.onlineshop.view.fragments;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.onlineshop.R;
import com.example.onlineshop.model.Product;
import com.example.onlineshop.view.Adapter.ProductListSubCategoryAdapter;
import com.example.onlineshop.view.activities.EndlessRecyclerViewScrollListener;
import com.example.onlineshop.viewmodel.HomePageViewModel;
import java.util.List;
public class ProductsListSeeAllFragment extends VisibleFragment {
public static final String ARG_STATUS_LIST = "ARG_STATUS_LIST";
private RecyclerView mRecyclerView;
private ProductListSubCategoryAdapter mAdapter;
private List<Product> mProductList;
private String mStatusList;
private HomePageViewModel mHomePageViewModel;
private EndlessRecyclerViewScrollListener mEndlessRecyclVScrollListener;
private int mPageNumber = 1;
public ProductsListSeeAllFragment() {
// Required empty public constructor
}
public static ProductsListSeeAllFragment newInstance(String statusList) {
ProductsListSeeAllFragment fragment = new ProductsListSeeAllFragment();
Bundle args = new Bundle();
args.putString(ARG_STATUS_LIST, statusList);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mStatusList = getArguments().getString(ARG_STATUS_LIST);
}
mHomePageViewModel = new ViewModelProvider(this).get(HomePageViewModel.class);
if (mStatusList.equals("date")) {
mHomePageViewModel.getListNewestProMutableLiveData().observe(this, list -> {
mProductList = list;
setupAdapter();
});
} else if (mStatusList.equals("popularity")) {
mHomePageViewModel.getListPopularProMutableLiveData().observe(this, list -> {
mProductList = list;
setupAdapter();
});
} else if (mStatusList.equals("rating")) {
mHomePageViewModel.getListMostPointProMutableLiveData().observe(this, list -> {
mProductList = list;
setupAdapter();
});
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_detail_list_category, container, false);
initUI(view);
return view;
}
private void initUI(View view) {
mRecyclerView = view.findViewById(R.id.recycler_view_detail_list_category);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(linearLayoutManager);
mEndlessRecyclVScrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
mPageNumber++;
loadNextDataFromApi(mPageNumber);
// mEndlessRecyclVScrollListener.resetState();
}
};
mRecyclerView.addOnScrollListener(mEndlessRecyclVScrollListener);
}
public void loadNextDataFromApi(int offset) {
if (mStatusList.equals("date")) {
mHomePageViewModel.getListNewestProByPageMutableLiveData(mStatusList, offset).observe(this, list -> {
mProductList.addAll(list);
setupAdapter();
});
} else if (mStatusList.equals("popularity")) {
mHomePageViewModel.getListPopularProByPageMutableLiveData(mStatusList, offset).observe(this, list -> {
mProductList.addAll(list);
setupAdapter();
});
} else if (mStatusList.equals("rating")) {
mHomePageViewModel.getListMostPointProByPageMutableLiveData(mStatusList, offset).observe(this, list -> {
mProductList.addAll(list);
setupAdapter();
});
}
}
private void setupAdapter() {
if (isAdded()) {
if (mAdapter == null) {
mAdapter = new ProductListSubCategoryAdapter(getContext(), mProductList);
mRecyclerView.setAdapter(mAdapter);
} else {
mAdapter.setListadapter(mProductList);
mAdapter.notifyDataSetChanged();
}
}
}
}
|
import java.util.Scanner;
public class coba {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("SHELL SORTING");
System.out.print("Enter the number of elements : ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " + n + " elements :");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.print("Before sorted array : ");
for(int x = 0; x < n; x++)
System.out.print(arr[x]+" ");
shellSort(arr);
System.out.print("\nAfter sorted array : ");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
static void shellSort(int[] nums) {
int h = 1;
int n = nums.length;
while(h < n) {
h = h * 3 + 1;
}
h = h / 3;
int c, j;
while (h > 0) {
for (int i = h; i < n; i++) {
c = nums[i];
j = i;
while (j >= h && nums[j - h] > c) {
nums[j] = nums[j - h];
j = j - h;
}
nums[j] = c;
}
h = h / 2;
}
}
}
|
import java.util.*;
import polyhedra.*;
public class CubeDemo {
public static void main(String[] args) {
List<Prism> prisms = new ArrayList<>();
prisms.add(new Cube(4));
prisms.add(new Cube(1));
prisms.add(new Cylinder(4, 0.5));
prisms.add(new Cube(2));
System.out.println(prisms);
Collections.sort(prisms, new ByVolume());
System.out.println(prisms);
Collections.sort(prisms, new ByArea());
System.out.println(prisms);
}
}
|
package example;
import java.util.Scanner;
public class StringPrac {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String st = s.nextLine();
System.out.println("STRING : " + st);
StringBuilder sb = new StringBuilder(st);
System.out.println("String Builder : " + sb);
sb.append(5);
sb.deleteCharAt(2);
String array[] = sb.toString().split(" ");
for(String ss: array){
System.out.println(ss);
}
}
}
|
package File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class FileClassIlkin {
public static void main(String[] args) throws IOException {
String[] array=null;
String setr;
ArrayList<Integer> arlist=new ArrayList<Integer>();
int a;
File file3=null;
File file4=null;
FileWriter fw=null;
BufferedWriter bw=null;
FileReader fr=null;
BufferedReader br=null;
try{
file3=new File("C:/Users/User/Desktop/java/file3.txt");
file4 =new File("C:/Users/User/Desktop/java/file4.txt");
fr=new FileReader(file3);
br=new BufferedReader(fr);
fw=new FileWriter(file4);
bw=new BufferedWriter(fw);
}catch (Exception e) {
// TODO: handle exception
System.out.println("Fayl problemi");
}
while((setr=br.readLine())!=null){
try{
a=Integer.parseInt(setr);
// System.out.println("int "+a);
arlist.add(a);
System.out.println(setr);
//System.out.println(arlist);
} catch (Exception e) {
System.out.println("yazilis sehvi: " + setr);
}
}
System.out.println("******");
Collections.sort(arlist);
System.out.println(arlist);
br.close();
fr.close();
bw.close();
fw.close();
}
}
|
package com.sendi.netrequest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Process;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
///import android.support.annotation.NonNull;
@TargetApi(Build.VERSION_CODES.M) ////高版本API的代码在低版本SDK不报错
public class PermissionUtils {
private static String TAG = "PermissionUtils";
private static HashMap<String, Object> map = new HashMap<String, Object>();
private static boolean checkSDK()
{
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
public static void requestPermissions(Context context, String[] permissions,
int requestCode, String explainMsg, OnPermissionResult onPermissionResult)
{
onPermissionResult = initOnPermissionResult(onPermissionResult, permissions, requestCode, explainMsg);
if (permissions.length == 0)
{
invokeOnRequestPermissionsResult(context, onPermissionResult);
} else if (context instanceof Activity || (Object) context instanceof Fragment)
{
if (checkSDK())
{
onPermissionResult.deniedPermissions = getDeniedPermissions(context, permissions);
if (onPermissionResult.deniedPermissions.length > 0)
{
//存在被拒绝的权限
onPermissionResult.rationalePermissions = getRationalePermissions(context, onPermissionResult.deniedPermissions);
if (onPermissionResult.rationalePermissions.length > 0)
{//向用户解释请求权限的理由
// LogUtil.lI(TAG, "1111you quan xian bei jinzhi");
shouldShowRequestPermissionRationale(context, onPermissionResult);
} else
{
// LogUtil.lI(TAG, "you quan xian bei jinzhi");
invokeRequestPermissions(context, onPermissionResult);
}
} else
{
//所有权限允许
onPermissionResult.grantResults = new int[permissions.length];
for (int i = 0; i < onPermissionResult.grantResults.length; i++)
{
onPermissionResult.grantResults[i] = PackageManager.PERMISSION_GRANTED;
}
//LogUtil.lI(TAG, "you quan xian bei yunxu");
invokeOnRequestPermissionsResult(context, onPermissionResult);
}
} else
{
onPermissionResult.grantResults = getPermissionsResults(context, permissions);
invokeOnRequestPermissionsResult(context, onPermissionResult);
}
}
}
/**
* 获取被拒绝的权限
*
* @param context
* @param permissions
* @return
*/
private static String[] getDeniedPermissions(Context context, String[] permissions)
{
List<String> list = new ArrayList<>();
for (String permission : permissions)
{
if (checkPermission(context, permission) != PackageManager.PERMISSION_GRANTED)
{
list.add(permission);
}
}
return list.toArray(new String[list.size()]);
}
/**
* 获取权限请求结果
*
* @param context
* @param permissions
* @return
*/
private static int[] getPermissionsResults(Context context, String[] permissions)
{
int[] results = new int[permissions.length];
for (int i = 0; i < results.length; i++)
results[i] = checkPermission(context, permissions[i]);
return results;
}
private static String[] getRationalePermissions(Context context, String[] deniedPermissions)
{
List<String> list = new ArrayList<>();
for (String permission : deniedPermissions)
{
if (context instanceof Activity)
{
if (((Activity) context).shouldShowRequestPermissionRationale(permission))
{
list.add(permission);
}
} else if ((Object) context instanceof Fragment)
{
if (((Fragment) (Object) context).shouldShowRequestPermissionRationale(permission))
{
list.add(permission);
}
} else
{
throw new IllegalArgumentException("context 只能是Activity或Fragment");
}
}
return list.toArray(new String[list.size()]);
}
/**
* 调用权限请求方法
*
* @param context
* @param onPermissionResult
*/
private static void invokeRequestPermissions(Context context, OnPermissionResult onPermissionResult)
{
if (context instanceof Activity)
((Activity) context).requestPermissions(onPermissionResult.deniedPermissions, onPermissionResult.requestCode);
else if ((Object) context instanceof Fragment)
((Fragment) (Object) context).requestPermissions(onPermissionResult.deniedPermissions, onPermissionResult.requestCode);
}
/**
* 调用权限请求结果回调
*
* @param context
* @param onPermissionResult
*/
private static void invokeOnRequestPermissionsResult(Context context, OnPermissionResult onPermissionResult)
{
if (context instanceof Activity)
{
if (checkSDK())
{
((Activity) context).onRequestPermissionsResult(onPermissionResult.requestCode,
onPermissionResult.permissions, onPermissionResult.grantResults);
} else if (context instanceof ActivityCompat.OnRequestPermissionsResultCallback)
{
((ActivityCompat.OnRequestPermissionsResultCallback) context)
.onRequestPermissionsResult(onPermissionResult.requestCode, onPermissionResult.permissions, onPermissionResult.grantResults);
} else
{
onRequestPermissionsResult(onPermissionResult.requestCode, onPermissionResult.permissions, onPermissionResult.grantResults);
}
} else if ((Object) context instanceof Fragment)
{
((Fragment) (Object) context).onRequestPermissionsResult(onPermissionResult.requestCode,
onPermissionResult.permissions, onPermissionResult.grantResults);
}
}
/**
* 显示权限解释
*
* @param context
* @param onPermissionResult
*/
private static void shouldShowRequestPermissionRationale(final Context context, final OnPermissionResult onPermissionResult)
{
invokeRequestPermissions(context, onPermissionResult);
}
/**
* 检查权限
*
* @param context
* @param permission
* @return
*/
private static int checkPermission(Context context, String permission)
{
return context.checkPermission(permission, Process.myPid(), Process.myUid());
}
public static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
synchronized (map)
{
OnPermissionResult onPermissionResult = (OnPermissionResult) map.get(String.valueOf(requestCode));
if (onPermissionResult != null)
{
List<String> deniedPermissions = new ArrayList<>();
for (int i = 0; i < grantResults.length; i++)
{
if (grantResults[i] != PackageManager.PERMISSION_GRANTED)
{
deniedPermissions.add(permissions[i]);
}
}
if (deniedPermissions.size() > 0)
{
onPermissionResult.denied(requestCode);
} else
{
onPermissionResult.granted(requestCode);
}
map.remove(String.valueOf(requestCode));
}
}
}
/**
* 初始化权限请求回调
*
* @param onPermissionResult
* @param permissions
* @param requestCode
* @param explainMsg @return
*/
private static OnPermissionResult initOnPermissionResult(OnPermissionResult onPermissionResult, String[] permissions,
int requestCode, String explainMsg)
{
synchronized (map)
{
if (onPermissionResult == null)
{
onPermissionResult = new OnPermissionResult()
{
@Override
public void granted(int requestCode)
{
}
@Override
public void denied(int requestCode)
{
}
};
}
onPermissionResult.permissions = permissions;
onPermissionResult.requestCode = requestCode;
onPermissionResult.explainMsg = explainMsg;
onPermissionResult.grantResults = new int[0];
map.put(String.valueOf(requestCode), onPermissionResult);
return onPermissionResult;
}
}
public abstract static class OnPermissionResult
{
int requestCode;
String explainMsg;
String[] permissions;
String[] deniedPermissions;
String[] rationalePermissions;
int[] grantResults;
//权限允许
public abstract void granted(int requestCode);
//权限拒绝
public abstract void denied(int requestCode);
}
}
|
package dev.mariogrimaldi.kata.fizzbuzz;
import dev.mariogrimaldi.kata.fizzbuzz.rule.DivisibleByRule;
import dev.mariogrimaldi.kata.fizzbuzz.rule.deluxe.DeluxeRule;
import dev.mariogrimaldi.kata.fizzbuzz.rule.deluxe.FakeDeluxe;
import dev.mariogrimaldi.kata.fizzbuzz.rule.deluxe.OldDeluxeBehaviour;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class OldDeluxeFizzBuzzShould {
private FizzBuzz fizzBuzz;
@Before
public void setUp() throws Exception {
fizzBuzz = new FizzBuzz(Arrays.asList(
new DivisibleByRule(3, "Fizz"),
new DivisibleByRule(5, "Buzz"),
new DivisibleByRule(7, "Bang"),
new DivisibleByRule(11, "Puff"),
new DeluxeRule(new OldDeluxeBehaviour()),
new FakeDeluxe(new OldDeluxeBehaviour())
));
}
@Test
public void print_one_for_1() {
assertEquals("1", fizzBuzz.play(1));
}
@Test
public void print_two_for_2() {
assertEquals("2", fizzBuzz.play(2));
}
@Test
public void print_four_for_4() {
assertEquals("4", fizzBuzz.play(4));
}
@Test
public void print_fizz_for_3() {
assertEquals("Fizz", fizzBuzz.play(3));
}
@Test
public void print_fizz_for_6() {
assertEquals("Fizz", fizzBuzz.play(6));
}
@Test
public void print_fizz_for_9() {
assertEquals("Fizz", fizzBuzz.play(9));
}
@Test
public void print_buzz_for_5() {
assertEquals("Buzz", fizzBuzz.play(5));
}
@Test
public void print_buzz_for_10() {
assertEquals("Buzz", fizzBuzz.play(10));
}
@Test
public void print_buzz_for_20() {
assertEquals("Buzz", fizzBuzz.play(20));
}
@Test
public void print_fizzbuzz_for_15() {
assertEquals("FizzBuzz", fizzBuzz.play(15));
}
@Test
public void print_fizzbuzz_for_30() {
assertEquals("FizzBuzz", fizzBuzz.play(30));
}
@Test
public void print_fizzbuzz_for_45() {
assertEquals("FizzBuzz", fizzBuzz.play(45));
}
@Test
public void print_bang_for_7() {
assertEquals("Bang", fizzBuzz.play(7));
}
@Test
public void print_bang_for_14() {
assertEquals("Bang", fizzBuzz.play(14));
}
@Test
public void print_bang_for_28() {
assertEquals("Bang", fizzBuzz.play(28));
}
@Test
public void print_fizzbang_for_21() {
assertEquals("FizzBang", fizzBuzz.play(21));
}
@Test
public void print_fizzbang_for_42() {
assertEquals("FizzBang", fizzBuzz.play(42));
}
@Test
public void print_fizzbang_for_63() {
assertEquals("FizzBang", fizzBuzz.play(63));
}
@Test
public void print_buzzbang_for_35() {
assertEquals("BuzzBang", fizzBuzz.play(35));
}
@Test
public void print_fizzbuzzbang_for_105() {
assertEquals("FizzBuzzBang", fizzBuzz.play(105));
}
@Test
public void print_fizzbuzzpuff_for_165() {
assertEquals("FizzBuzzPuff", fizzBuzz.play(165));
}
@Test
public void print_fizzbuzzbangpuff_for_1155() {
assertEquals("FizzBuzzBangPuff", fizzBuzz.play(1155));
}
@Test
public void print_puffdeluxe_for_22() {
assertEquals("PuffDeluxe", fizzBuzz.play(22));
}
@Test
public void print_fizzpufffakedeluxe_for_33() {
assertEquals("FizzPuffFakeDeluxe", fizzBuzz.play(33));
}
@Test
public void print_buzzpufffakedeluxe_for_55() {
assertEquals("BuzzPuffFakeDeluxe", fizzBuzz.play(55));
}
@Test
public void print_bangpufffakedeluxe_for_77() {
assertEquals("BangPuffFakeDeluxe", fizzBuzz.play(77));
}
@Test
public void acceptanceWithRules() {
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 , 13, 14, 15 };
String[] expected = new String[] { "1", "2", "Fizz", "4", "Buzz", "Fizz", "Bang", "8", "Fizz", "Buzz", "PuffFakeDeluxe", "Fizz", "13", "Bang", "FizzBuzz" };
String[] actual = Arrays.stream(numbers)
.mapToObj(fizzBuzz::play)
.toArray(String[]::new);
assertArrayEquals(expected, actual);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.model.dao;
import com.model.entity.Veiculo;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author renanmarceluchoa
*/
@Stateless
public class VeiculoDaoBean implements VeiculoDao {
@PersistenceContext(unitName="FrotaPU")
private EntityManager em;
@Override
public void inserir(Veiculo veiculo) {
em.persist(veiculo);
}
@Override
public void atualizar(Veiculo veiculo) {
em.merge(veiculo);
}
@Override
public void remover(Veiculo veiculo) {
veiculo = em.merge(veiculo);
em.remove(veiculo);
}
@Override
public Veiculo buscar(Integer id) {
return em.find(Veiculo.class, id);
}
@Override
public List<Veiculo> listar() {
Query query = em.createNamedQuery("Veiculo.findAll");
return query.getResultList();
}
@Override
public List<Veiculo> buscarPorModelo(String modelo) {
Query query = em.createNamedQuery("Veiculo.findByModelo");
query.setParameter("modelo", modelo);
return query.getResultList();
}
}
|
package com.noteshare.project.utils;
import java.util.ArrayList;
public class ShowJavaProjectConstant {
/**项目文件存储路径*/
public static final String PROJECTPATH = "project.projectPath";
/**项目库文件夹路径*/
public static final String PROJECTLIBPATH = "project.projectLibPath";
public static ArrayList<String> SUFFIXLIST = new ArrayList<String>();
static{
SUFFIXLIST.add("java");
SUFFIXLIST.add("xml");
SUFFIXLIST.add("html");
SUFFIXLIST.add("js");
SUFFIXLIST.add("css");
}
}
|
package main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import org.json.JSONArray;
import org.json.JSONObject;
import team.Squad;
import team.Team;
import team.coach.Coach;
import team.coach.CoachBehavior;
import team.player.Player;
import team.player.PlayerAttribute;
import team.player.PlayerMorale;
import team.player.PlayerPosition;
public class LoadFromResources {
public static Team loadTeam(String filePath) throws IOException {
InputStream is = LoadFromResources.class.getResourceAsStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
JSONObject json = new JSONObject(sb.toString());
String name = json.getString("name");
Coach coach = loadCoach(json.getJSONObject("coach"));
Squad squad = loadSquad(json.getJSONArray("players"));
return new Team(name, coach, squad);
}
private static Coach loadCoach(JSONObject json) {
String name = json.getString("name");
int age = json.getInt("age");
CoachBehavior behaviour = CoachBehavior.valueOf(json.getString("behaviour"));
return new Coach(name, age, behaviour);
}
private static Squad loadSquad(JSONArray jsonArray) {
LinkedList<Player> players = new LinkedList<Player>();
for(int i=0; i<jsonArray.length(); i++) {
players.add(loadPlayer(jsonArray.getJSONObject(0)));
}
return new Squad(players);
}
private static Player loadPlayer(JSONObject json) {
String name = json.getString("name");
int age = json.getInt("age");
PlayerPosition position = PlayerPosition.valueOf(json.getString("position"));
PlayerAttribute attribute = new PlayerAttribute(json.getInt("agility"), json.getInt("strength"), json.getInt("stamina"));
PlayerMorale morale = PlayerMorale.GOOD;
int injuredTime = 0;
int fatigue = Player.MAXIMUM_FATIGUE_VALUE;
return new Player(name, age, position, attribute, morale, injuredTime, fatigue);
}
}
|
package com.accp.entity;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import java.time.LocalDate;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ljq
* @since 2019-08-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="Stockapply对象", description="")
public class Stockapply extends Model<Stockapply> {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "请购单编号")
private String appid;
@ApiModelProperty(value = "请购单日期")
private LocalDate appdate;
@ApiModelProperty(value = "请购采购类型")
private String apptype;
@ApiModelProperty(value = "默认0 未结案,1:已结案 2:无效")
private Integer appcircs;
@ApiModelProperty(value = "请购人员id")
private Integer apppersonid;
@ApiModelProperty(value = "请购部门id")
private Integer appdeptid;
@ApiModelProperty(value = "制单人员")
private String appmaker;
@ApiModelProperty(value = "复核人员")
private String appauditingperson;
@ApiModelProperty(value = "审核状态:未审核/已审核/无效")
private String appauditing;
@ApiModelProperty(value = "标识是否删除")
private Integer enables;
@ApiModelProperty(value = "保留字段")
private String safetyone;
@ApiModelProperty(value = "保留字段")
private String safetytwo;
public static final String APPID = "appid";
public static final String APPDATE = "appdate";
public static final String APPTYPE = "apptype";
public static final String APPCIRCS = "appcircs";
public static final String APPPERSONID = "apppersonid";
public static final String APPDEPTID = "appdeptid";
public static final String APPMAKER = "appmaker";
public static final String APPAUDITINGPERSON = "appauditingperson";
public static final String APPAUDITING = "appauditing";
public static final String ENABLES = "enables";
public static final String SAFETYONE = "safetyone";
public static final String SAFETYTWO = "safetytwo";
@Override
protected Serializable pkVal() {
return this.appid;
}
}
|
package com.tencent.mm.pluginsdk.g.a.a;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.bho;
import com.tencent.mm.protocal.c.oi;
import com.tencent.mm.protocal.c.oj;
import com.tencent.mm.sdk.platformtools.x;
public final class m extends n {
protected final String getTag() {
return "MicroMsg.ResDownloader.CheckResUpdate.NetSceneCheckResUpdate";
}
protected final oj i(q qVar) {
return (oj) ((b) qVar).dIE.dIL;
}
public m(int i) {
x.i("MicroMsg.ResDownloader.CheckResUpdate.NetSceneCheckResUpdate", "NetSceneCheckResUpdate init, resType:%d", new Object[]{Integer.valueOf(i)});
bho bho = new bho();
bho.hcE = i;
this.qCJ.clear();
this.qCJ.add(bho);
}
protected final q ccA() {
a aVar = new a();
oi oiVar = new oi();
oiVar.rsF.addAll(this.qCJ);
aVar.dIG = oiVar;
aVar.dIH = new oj();
aVar.uri = "/cgi-bin/micromsg-bin/checkresupdate";
aVar.dIF = 721;
aVar.dII = 0;
aVar.dIJ = 0;
return aVar.KT();
}
public final int getType() {
return 721;
}
}
|
package com.cpe.mysql.webblog;
import com.cpe.mysql.webblog.entity.Role;
import com.cpe.mysql.webblog.entity.Tag;
import com.cpe.mysql.webblog.entity.User;
import com.cpe.mysql.webblog.repository.RoleRepository;
import com.cpe.mysql.webblog.repository.TagRepository;
import com.cpe.mysql.webblog.repository.UserRepository;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.sql.Timestamp;
import java.util.Date;
import java.util.stream.Stream;
@SpringBootApplication
public class WebBlogApplication {
public static void main(String[] args) {
SpringApplication.run(WebBlogApplication.class, args);
}
// @Bean
// ApplicationRunner init(TagRepository tagRepository, UserRepository userRepository, RoleRepository roleRepository) {
// return args -> {
//
// //create role
// Role role1 = new Role("Newbie");
// Role role2 = new Role("Experienced");
// Role role3 = new Role("Admin");
// Stream.of(role1, role2, role3).forEach((role -> {
// roleRepository.save(role);
// System.out.println(role);
// }));
//
// //create tag
// Tag tag1 = new Tag("Stock", "orange");
// Tag tag2 = new Tag("News", "indigo");
// Tag tag3 = new Tag("Mutual Funds", "teal");
// Stream.of(tag1, tag2, tag3).forEach((tag -> {
// tagRepository.save(tag);
// System.out.println(tag);
// }));
//
// // set date time
// Timestamp time1 = new Timestamp(System.currentTimeMillis());
// Date date1 = new Date(time1.getTime());
// //create user
// User usr1 = new User("admin1", "admin1", "IAM ADMIN1", "admin1@gmail.com", date1, role3, role3.getRoleOfUser());
//
// // set date time
// Timestamp time3 = new Timestamp(System.currentTimeMillis());
// Date date3 = new Date(time3.getTime());
// //create user
// User usr3 = new User("admin2", "admin2", "IAM ADMIN2", "admin2@gmail.com", date3, role3, role3.getRoleOfUser());
//
// // set date time
// Timestamp time2 = new Timestamp(System.currentTimeMillis());
// Date date2 = new Date(time2.getTime());
// //create user
// User usr2 = new User("imbac", "imbac", "Bac Natthawut", "imbac@gmail.com", date2, role2, role2.getRoleOfUser());
//
// // set date time
// Timestamp time4 = new Timestamp(System.currentTimeMillis());
// Date date4 = new Date(time4.getTime());
// //create user
// User usr4 = new User("newbac", "newbac", "newBac Natthawut", "newbac@gmail.com", date4, role1, role1.getRoleOfUser());
//
// Stream.of(usr1, usr2, usr3, usr4).forEach((usr -> {
// userRepository.save(usr);
// System.out.println(usr);
// }));
// };
// }
}
|
package com.rockwellcollins.atc.limp.translate.lustre.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jkind.lustre.BinaryExpr;
import jkind.lustre.BinaryOp;
import jkind.lustre.BoolExpr;
import jkind.lustre.Equation;
import jkind.lustre.Expr;
import jkind.lustre.IdExpr;
import jkind.lustre.NamedType;
import jkind.lustre.Node;
import jkind.lustre.NodeCallExpr;
import jkind.lustre.UnaryExpr;
import jkind.lustre.UnaryOp;
import jkind.lustre.VarDecl;
/**
* PLTL is a utility that generates some commonly used PLTL expressions as Lustre node because
* we need them to generate some of our autogenerated properties.
*/
public class PLTL {
/**
* Y is a pre operator with the initial value set to FALSE
*/
public static Node Y() {
String name = "Y";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl signal = new VarDecl("signal", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new BoolExpr(false), BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, new IdExpr(signal.id))));
inputs.add(signal);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
/**
* Y is a pre operator with the initial value set to TRUE
*/
public static Node Z() {
String name = "Z";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl signal = new VarDecl("signal", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new BoolExpr(true), BinaryOp.ARROW, new UnaryExpr(UnaryOp.PRE, new IdExpr(signal.id))));
inputs.add(signal);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
/**
* H is the node that implements Historically. Historically EXPR must be true on the current step and every previous step.
*/
public static Node H() {
String name = "H";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl signal = new VarDecl("signal", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
List<Expr> args = new ArrayList<>();
args.add(new IdExpr(holds.id));
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new IdExpr(signal.id), BinaryOp.AND, new NodeCallExpr("Z",args)));
inputs.add(signal);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
/**
* O is the node that implements Once. Once EXPR must be true at least once on the current step and every previous step.
*/
public static Node O() {
String name = "O";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl signal = new VarDecl("signal", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
List<Expr> args = new ArrayList<>();
args.add(new IdExpr(holds.id));
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new IdExpr(signal.id), BinaryOp.OR, new NodeCallExpr("Y",args)));
inputs.add(signal);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
/**
* S is the node that implements Since.
*/
public static Node S() {
String name = "S";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl a = new VarDecl("a", NamedType.BOOL);
VarDecl b = new VarDecl("b", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
List<Expr> args = new ArrayList<>();
args.add(new IdExpr(holds.id));
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new IdExpr(b.id), BinaryOp.OR, new BinaryExpr(new IdExpr(a.id), BinaryOp.AND, new NodeCallExpr("Y",args))));
inputs.add(a);
inputs.add(b);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
/**
* T is the node that implements Trigger
*/
public static Node T() {
String name = "T";
List<VarDecl> inputs = new ArrayList<>();
List<VarDecl> locals = new ArrayList<>();
List<VarDecl> outputs = new ArrayList<>();
List<Equation> equations = new ArrayList<>();
//inputs
VarDecl a = new VarDecl("a", NamedType.BOOL);
VarDecl b = new VarDecl("b", NamedType.BOOL);
//outputs
VarDecl holds = new VarDecl("holds", NamedType.BOOL);
List<Expr> args = new ArrayList<>();
args.add(new IdExpr(holds.id));
//equations
Equation equation = new Equation(new IdExpr(holds.id), new BinaryExpr(new IdExpr(b.id), BinaryOp.AND, new BinaryExpr(new IdExpr(a.id), BinaryOp.OR, new NodeCallExpr("Z",args))));
inputs.add(a);
inputs.add(b);
outputs.add(holds);
equations.add(equation);
return new Node(name,inputs,outputs,locals,equations);
}
public static Map<String,Node> getAllPLTL() {
List<Node> nodes = new ArrayList<>();
Map<String,Node> map = new HashMap<>();
nodes.add(Y());
nodes.add(Z());
nodes.add(H());
nodes.add(O());
nodes.add(S());
nodes.add(T());
for(Node n : nodes) {
map.put(n.id, n);
}
return map;
}
}
|
package test15PiDataProvidersEx;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestDataExcelListEmp {
@DataProvider(name = "excelData")
public static Object[][] Authentication() throws Exception {
return ExcelUtils.getLoginObjs("C://test//data.xlsx", "input");
}
@Test(dataProvider = "excelData")
public void Registration_data(Login login) throws Exception {
System.out.println(login.getName());
System.out.println(login.getPass());
}
}
|
package com.ys.service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* Created by yushi on 2017/3/27.
*/
@RequestMapping("/hdfs")
@ResponseBody
public interface HdfsClient {
@RequestMapping(value = "/init", method = RequestMethod.GET)
public void init() throws IOException, URISyntaxException, InterruptedException;
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public void upload() throws IOException;
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download() throws Exception;
@RequestMapping(value = "/conf", method = RequestMethod.GET)
public void conf();
@RequestMapping(value = "/makdir", method = RequestMethod.GET)
public void makdir() throws Exception;
/**
* 删除
*/
@RequestMapping(value = "/delete", method = RequestMethod.GET)
public void delete() throws Exception;
@RequestMapping(value = "/list", method = RequestMethod.GET)
public void list() throws Exception;
}
|
package com.blog.system.Dto;
public class DailyBean {
private int dailyid;
private int userid;
private String dailyname;
private String daily;
private java.sql.Date postingdate;
private java.sql.Date modifytime;
private String keyword;
private String tab;
public int getDailyid() {
return dailyid;
}
public void setDailyid(int dailyid) {
this.dailyid = dailyid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getDailyname() {
return dailyname;
}
public void setDailyname(String dailyname) {
this.dailyname = dailyname;
}
public String getDaily() {
return daily;
}
public void setDaily(String daily) {
this.daily = daily;
}
public java.sql.Date getPostingdate() {
return postingdate;
}
public void setPostingdate(java.sql.Date postingdate) {
this.postingdate = postingdate;
}
public java.sql.Date getModifytime() {
return modifytime;
}
public void setModifytime(java.sql.Date modifytime) {
this.modifytime = modifytime;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getTab() {
return tab;
}
public void setTab(String tab) {
this.tab = tab;
}
}
|
/**
*
* @author Bassem E-Hamedy
* @version : V 3
* OverDue object class created to have an object of over view to hold the Overdue members
*/
public class OverDue {
private int overdueDays;
private String email;
private String bookName;
private String entryDate;
private String BorrowDate;
private String returnDate;
public OverDue(int overdueDays, String email, String bookName, String entryDate, String BorrowDate,
String returnDate) {
super();
this.overdueDays = overdueDays;
this.email = email;
this.bookName = bookName;
this.entryDate = entryDate;
this.BorrowDate = BorrowDate;
this.returnDate = returnDate;
}
public int getOverdueDays() {
return overdueDays;
}
public void setOverdueDays(int overdueDays) {
this.overdueDays = overdueDays;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getEntryDate() {
return entryDate;
}
public void setEntryDate(String entryDate) {
this.entryDate = entryDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBorrowDate() {
return BorrowDate;
}
public void setBorrowDate(String BorrowDate) {
this.BorrowDate = BorrowDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
/**
* @Override
* Returns a formatted Overdue Object using the below sequence
*/
public String toString() {
return String.format(
"Overdue [overdueDays=%s, email=%s, bookName=%s, entryDate=%s, BorrowDate=%s, returnDate=%s]",
overdueDays, email, bookName, entryDate, BorrowDate, returnDate);
}
}
|
/*
* 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 game;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author kahlaoui
*/
public class Partie {
private final String date ;
private final String mot ;
private final int niveau ;
private int trouve ;
private double temps ;
public Partie(String date, String mot, int niveau) {
this.date = date ;
this.mot = mot ;
this.niveau = niveau ;
}
public Partie(Element partieElt) {
this.date = partieElt.getAttribute("date") ;
this.temps = Double.parseDouble(partieElt.getFirstChild().getNodeValue()) ;
this.niveau = Integer.parseInt(((Element)(partieElt.getLastChild())).getAttribute("niveau")) ;
this.mot = partieElt.getLastChild().getNodeValue() ;
}
public Element getPartie(Document doc) {
Element parties = doc.createElement("parties");
Element partie = doc.createElement("partie");
partie.setAttribute("date", this.date);
Element temps = doc.createElement("temps");
Element mot = doc.createElement("mot");
mot.setAttribute("niveau", Integer.toString(this.niveau));
mot.setTextContent(this.mot);
if(this.temps != 0) partie.appendChild(temps) ;
partie.appendChild(mot);
parties.appendChild(partie);
return parties;
}
public int getTrouve() {
return trouve;
}
public void setTrouve(int nbLettresRestantes) {
this.trouve = (int) (((mot.length()-nbLettresRestantes)*100)/mot.length()) ;
}
public void setTemps(double temps) {
this.temps = temps ;
}
public double getTemps() {
return this.temps ;
}
public int getNiveau() {
return niveau ;
}
public String toString() {
return "Partie de "+date+" mot joué '"+mot+"' niveau "+niveau+" temp de partie "+temps ;
}
public String getMot() {
return this.mot ;
}
public String getDate() {
return date ;
}
}
|
package zm.gov.moh.core.utils;
import java.util.AbstractMap;
import java.util.concurrent.TimeUnit;
import io.reactivex.Maybe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiConsumer;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
public class ConcurrencyUtils {
public static <T>Disposable consumeAsync(Consumer<T> consumer, Consumer<Throwable> onError, T items){
return Single.just(items)
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.subscribe(consumer, onError);
}
public static <T1, T2>Disposable consumeAsync(BiConsumer<T1,T2> consumer, Consumer<Throwable> onError, T1 param1, T2 param2){
AbstractMap.SimpleImmutableEntry<T1,T2> params = new AbstractMap.SimpleImmutableEntry<>(param1,param2);
return Single.just(params)
.observeOn(Schedulers.io())
.subscribeOn(Schedulers.io())
.subscribe(p -> consumer.accept(p.getKey(),p.getValue()), onError);
}
public static <T,R>Disposable asyncFunction(Function<T,R> function, Consumer<R> consumer, T items, Consumer<Throwable> onError){
return Single.just(items)
.subscribeOn(Schedulers.io())
.map(function)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer, onError);
}
public static Disposable asyncRunnable(Runnable runnable, Consumer<Throwable> onError){
return Single.just("")
.subscribeOn(Schedulers.io())
.map(a->{ runnable.run(); return "";})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(a->{ }, onError);
}
public static <T>Disposable consumeAsync(Consumer<T> consumer, Consumer<Throwable> onError, Maybe<T> observable, final int timeout) {
return observable.timeout(timeout, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(consumer, onError);
}
public static <T>Disposable consumeAsync(Consumer<T[]> consumer, Consumer<Throwable> onError, Action onComplete, Maybe<T[]> observable, final int timeout) {
return observable.timeout(timeout, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.doOnComplete(onComplete)
.subscribe(consumer, onError);
}
public static <T>Disposable consume(Consumer<T> consumer, Consumer<Throwable> failure, Maybe<T> observable, final int timeout) {
return observable.timeout(timeout, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer, failure);
}
public static <T>Disposable consumeOnMainThread(Consumer<T> consumer, T param) {
return Single.just(param)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(consumer);
}
public static <T>Disposable consumeBlocking(Consumer<T> consumer, Consumer<Throwable> failure, Maybe<T> observable, final int timeout) {
return observable.timeout(timeout, TimeUnit.MILLISECONDS)
.subscribe(consumer, failure);
}
}
|
package com.ibeiliao.pay.impl.thirdpay.jdpay.response;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import com.ibeiliao.pay.api.enums.PayCode;
import com.ibeiliao.pay.impl.thirdpay.BaseResponse;
import com.ibeiliao.pay.impl.thirdpay.jdpay.JdpayNotify;
/**
* 功能:京东支付交易信息
*
* @author liuying 2016年8月30日
*
*/
public class JdpayTradeResponse extends BaseResponse {
/**
* 版本号
*/
private String version;
/**
* 商户号
*/
private String merchant;
/**
* 支付交易结果
*/
private Result result;
/**
* 交易状态,0-创建,1-处理中,2-成功,3-失败,4-关闭
*/
private String status;
/**
* 设备号
*/
private String device;
/**
* 交易流水 ,数字或字母
*/
private String tradeNum;
/**
* 0:消费,1:退款
*/
private String tradeType;
/**
* 数据签名
*/
private String sign;
/**
* 交易列表
*/
private List<PayTradeVo> payList;
/**
* 支付总金额
*/
private Long amount;
/**
* 返回原交易备注,如果没有备注就没有这个参数
*/
private String note;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public List<PayTradeVo> getPayList() {
return payList;
}
public void setPayList(List<PayTradeVo> payList) {
this.payList = payList;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getTradeNum() {
return tradeNum;
}
public void setTradeNum(String tradeNum) {
this.tradeNum = tradeNum;
}
public String getTradeType() {
return tradeType;
}
public void setTradeType(String tradeType) {
this.tradeType = tradeType;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public Long getAmount() {
return amount;
}
public void setAmount(Long amount) {
this.amount = amount;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
return "JdpayNotifyResponse [version=" + version + ", merchant=" + merchant + ", result="
+ result + ", status=" + status + ", device=" + device + ", tradeNum=" + tradeNum
+ ", tradeType=" + tradeType + ", sign=" + sign + ", payList=" + payList
+ ", amount=" + amount + ", note=" + note + "]";
}
@Override
public boolean isSuccess() {
return JdpayNotify.isSuccess(NumberUtils.toInt(status));
}
@Override
public String getOuterSerialNo() {
return StringUtils.trimToEmpty(tradeNum);
}
@Override
public BigDecimal getPayAmount() {
return amount == null ? BigDecimal.ZERO : new BigDecimal(amount);
}
@Override
public PayCode getPayCode() {
return PayCode.JDPAY;
}
}
|
package nb.queryDomain;
import java.io.Serializable;
import java.math.BigDecimal;
public class BidDetails implements Serializable {
private Long bidId;
private BigDecimal startPrice;
public BidDetails() {
}
public BidDetails(Long bidId, BigDecimal startPrice) {
this.bidId = bidId;
this.startPrice = startPrice;
}
public Long getBidId() {
return bidId;
}
public void setBidId(Long bidId) {
this.bidId = bidId;
}
public BigDecimal getStartPrice() {
return startPrice;
}
public void setStartPrice(BigDecimal startPrice) {
this.startPrice = startPrice;
}
@Override
public String toString() {
return "BidDetails{" +
"bidId=" + bidId +
", startPrice=" + startPrice +
'}';
}
}
|
package br.ufrgs.rmpestano.intrabundle.event;
import java.io.Serializable;
/**
* Created by rmpestano on 1/26/14.
*/
public class LocaleChangeEvent implements Serializable {
}
|
package lab3bZad1;
// DeckOfCards class represents a deck of playing cards.
import java.util.Random;
public class DeckOfCards
{
private String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
private String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
private Card deck[]; // array of Card objects
private int currentCard; // the index of next Card to be dealt
private final int NUMBER_OF_CARDS = 52; // constant number of cards
private Random randomNumbers; // random number generator
// constructor fills deck of cards
public DeckOfCards()
{
deck = new Card[ NUMBER_OF_CARDS ]; // create array of Card objects
currentCard = 0; // initialize currentCard
randomNumbers = new Random(); // create random number generator
// populate deck with Card objects
for ( int count = 0; count < deck.length; count++ )
deck[ count ] =
new Card( faces[ count % 13 ], suits[ count / 13 ] );
} // end DeckOfCards constructor
// shuffle deck of cards with one-pass algorithm
public void shuffle()
{
currentCard = 0; // reinitialize currentCard
// for each card, pick another random card and swap them
for ( int first = 0; first < deck.length; first++ )
{
// select a random number between 0 and 51
int second = randomNumbers.nextInt( NUMBER_OF_CARDS );
// swap current Card with randomly selected Card
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ] = temp;
} // end for
} // end method shuffle
// deal one card
public Card dealCard()
{
// determine whether cards remain to be dealt
if ( currentCard < deck.length )
return deck[ currentCard++ ]; // return current Card in array
else
return null; // return null to indicate that all cards were dealt
} // end method dealCard
// tally the number of each face card in hand
private int[] totalHand( Card hand[] )
{
int numbers[] = new int[ faces.length ]; // store number of face
// initialize all elements of numbers[] to zero
for ( int i = 0; i < faces.length; i++ )
numbers[ i ] = 0;
// compare each card in the hand to each element in the faces array
for ( int h = 0; h < hand.length; h++ )
{
for ( int f = 0; f < faces.length; f++ )
{
if ( hand[ h ].getFace().equals(faces[ f ]) )
++numbers[ f ];
} // end for
} // end for
return numbers;
} // end method totalHand
// determine if hand contains pairs
public int pairs( Card hand[] )
{
int couples = 0;
int numbers[] = totalHand( hand );
// count pairs
for ( int k = 0; k < numbers.length; k++ )
{
if ( numbers[ k ] == 2 )
{
System.out.printf( "Pair of %s\n", faces[ k ] );
++couples;
} // end if
} // end for
return couples;
} // end method pairs
// determine if hand contains a three of a kind
public int threeOfAKind( Card hand[] )
{
int triples = 0;
int numbers[] = totalHand( hand );
// count three of a kind
for ( int k = 0; k < numbers.length; k++ )
{
if ( numbers[ k ] == 3 )
{
System.out.printf( "Three %s\n", faces[ k ] );
++triples;
break;
} // end if
} // end for
return triples;
/*
int numbers[] = totalHand( hand );
// count three of a kind
for ( int k = 0; k < numbers.length; k++ )
{
if ( numbers[ k ] == 3 )
{
System.out.printf( "Three %s\n", faces[ k ] );
return 1;
} // end if
} // end for
return 0;
*/
} // end method threeOfAKind
// determine if hand contains a four of a kind
public void fourOfAKind( Card hand[] )
{
int numbers[] = totalHand( hand );
for ( int k = 0; k < faces.length; k++ )
{
if ( numbers[ k ] == 4 ) {
System.out.printf("Four %s\n", faces[k]);
return;
}
} // end for
} // end fourOfAKind
// determine if hand contains a flush
public void flush( Card hand[] )
{
String theSuit = hand[ 0 ].getSuit();
for ( int s = 1; s < hand.length; s++ )
{
if ( !hand[ s ].getSuit().equals(theSuit) )
return; // not a flush
} // end for
System.out.printf( "Flush in %s\n", theSuit );
} // end method flush
// determine if hand contains a straight
public void straight( Card hand[] )
{
int locations[] = new int[ 5 ];
int z = 0;
int numbers[] = totalHand( hand );
for ( int y = 0; y < numbers.length; y++ )
{
if ( numbers[ y ] == 1 )
locations[ z++ ] = y;
} // end for
int faceValue = locations[ 0 ];
if ( faceValue == 0 ) // special case, faceValue is Ace
{
faceValue = 13;
for ( int m = locations.length - 1; m >= 1; m-- )
{
if ( faceValue != locations[ m ] + 1 )
return; // not a straight
else
faceValue = locations[ m ];
} // end if
} // end if
else
{
for ( int m = 1; m < locations.length; m++ )
{
if ( faceValue != locations[ m ] - 1 )
return; // not a straight
else
faceValue = locations[ m ];
} // end if
} // end else
System.out.println( "Straight" );
} // end method straight
// determine if hand contains a full house
public void fullHouse( int couples, int triples )
{
if ( couples == 1 && triples == 1 )
System.out.println( "\nFull House!" );
} // end method fullHouse
// determine if hand contains two pairs
public void twoPairs( int couples )
{
if ( couples == 2 )
System.out.println( "\nTwo Pair!" );
} // end method twoPair
} // end class DeckOfCards
|
package com.canby.weather;
import com.canby.observer.Observable;
import com.canby.observer.Observer;
import java.util.HashSet;
import java.util.Set;
/**
* Created by acanby on 12/10/2014.
*/
public class WeatherStation implements Observable {
private Set<Observer> observers = new HashSet<>();
private boolean changed = false;
private float temperature;
private float humidity;
private float pressure;
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.setUpdated();
}
changed = false;
}
@Override
public void setChanged() {
changed = true;
}
public boolean isChanged() {
return changed;
}
/**
* Update the temperature and notify any observers
*
* @param temperature new temperature
* @param humidity new humidity
* @param pressure new pressure
*/
public void updateMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
private void measurementsChanged() {
setChanged();
notifyObservers();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
|
package org.kuali.mobility.computerlabs.dao;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.kuali.mobility.computerlabs.entity.Lab;
import org.kuali.mobility.computerlabs.entity.Location;
import org.kuali.mobility.computerlabs.helper.Building;
import org.kuali.mobility.computerlabs.helper.Buildings;
import org.kuali.mobility.computerlabs.helper.LabNameSort;
import org.kuali.mobility.computerlabs.helper.Room;
import org.kuali.mobility.util.mapper.DataMapper;
import com.thoughtworks.xstream.XStream;
public class ComputerLabsDaoUMImpl implements ComputerLabsDao
{
private static final Logger LOG = Logger.getLogger( ComputerLabsDaoUMImpl.class );
private String buildingsSourceURL;
private Map<String, List<String>> labUrls;
private Map<String, Location> locations;
private List<Lab> labs;
/**
* @return the labs
*/
public List<Lab> getLabs() {
return labs;
}
/**
* @param labs the labs to set
*/
public void setLabs(List<Lab> labs) {
this.labs = labs;
}
// @Autowired
private DataMapper dataMapper;
private String dataMappingUrl;
/**
* @return the Collection<Location>
*/
@SuppressWarnings("unchecked")
public Collection<Location> findAllLabsByCampus(String campus)
{
Map<String, Location> locations = null;
if(campus.equals("ALL") ) //umich
{
initData();
}
else //kme
{
for (String sourceUrl : labUrls.get(campus))
{
try
{
URL url = new URL(sourceUrl);
LOG.debug("SourceUrl: " + sourceUrl );
if (dataMappingUrl != null && !"".equals(dataMappingUrl.trim()))
{
LOG.info("***** data mapping URL ****") ;
setLabs(dataMapper.mapData(getLabs(), url, new URL(dataMappingUrl)));
}
else
{
LOG.info("---------------- labMapping.xml");
LOG.info("URL: " + url.toString()) ;
LOG.info("dataMapper: " + dataMapper) ;
List<Lab> labs = dataMapper.mapData(getLabs(), url, "labMapping.xml") ;
LOG.info("back from dataMapper") ;
setLabs(labs) ;
// setLabs(dataMapper.mapData(getLabs(), url, "labMapping.xml"));
}
}
catch (Exception e)
{
LOG.error("errors", e);
}
}
}
locations = new LinkedHashMap<String,Location>();
List<Lab> l = getLabs();
if (l != null) {
for (Lab lab : l)
{
Location location = null;
if (locations.get(lab.getBuildingCode()) != null) {
location = locations.get(lab.getBuildingCode());
} else {
location = new Location(lab.getBuilding());
locations.put(lab.getBuildingCode(), location);
}
/* LOG.debug("location: " + location.getName() );
LOG.debug("lab: " + lab.getAvailability() );*/
location.getLabs().add(lab);
}
/* for (Location curl : locations.values())
{
LOG.debug("Building " + curl.getName());
}*/
}
return locations.values();
}
/**
* Load Locations and labs from umich webservice.
*/
private void initData()
{
XStream xstream = new XStream();
xstream.processAnnotations(Buildings.class );
Buildings buildings = null;
try
{
buildings = (Buildings) xstream.fromXML( new URL(getBuildingsSourceURL()));
}
catch( MalformedURLException e )
{
LOG.error( e );
}
List<Building> bls = buildings.getBuildings();
if(bls == null || bls.isEmpty())
{
LOG.error("No Buildings found");
}
else
{
List<Lab> curlabs = new ArrayList<Lab>();
for (Building b : bls)
{
for (Room r : b.getRooms() )
{
Lab l = new Lab();
l.setBuildingCode(b.getBuildingName());
l.setBuilding(b.getBuildingName());
l.setLab(r.getName());
// LOG.debug("Add %%%% l.getLab() : " + l.getLab() + ", linux use" + r.getLinux_inuse() +", "+ r.getMac_inuse() + ", " + r.getWindows_inuse());
// LOG.debug(" linux free " + r.getLinux_free() +", "+ r.getMac_free() + ", " + r.getWindows_free());
int in_use = r.getLinux_inuse()+ r.getMac_inuse() + r.getWindows_inuse();
int free = r.getLinux_free() + r.getMac_free() + r.getWindows_free();
int total = in_use + free;
l.setWindowsAvailability(r.getWindows_free() + "/" + (r.getWindows_inuse()+r.getWindows_free()));
l.setLinuxAvailability(r.getLinux_free() + "/" + (r.getLinux_inuse() + r.getLinux_free()));
l.setMacAvailability(r.getMac_free() + "/" + (r.getMac_inuse() + r.getMac_free()));
l.setAvailability(Integer.toString(free) + "/" + Integer.toString(total));
//
curlabs.add(l);
}//room
}
//LOG.debug("Building size " + bls.size());
Collections.sort(curlabs,new LabNameSort());
setLabs(curlabs);
// LOG.debug("labs size " + curlabs.size());
}
}
public String getDataMappingUrl() {
return dataMappingUrl;
}
public void setDataMappingUrl(String dataMappingUrl) {
this.dataMappingUrl = dataMappingUrl;
}
public Map<String, List<String>> getLabUrls() {
return labUrls;
}
public void setLabUrls(Map<String, List<String>> labUrls) {
this.labUrls = labUrls;
}
/**
* @return the buildingsSourceURL
*/
public String getBuildingsSourceURL() {
return buildingsSourceURL;
}
/**
* @param buildingsSourceURL the buildingsSourceURL to set
*/
public void setBuildingsSourceURL(String buildingsSourceURL) {
this.buildingsSourceURL = buildingsSourceURL;
}
public DataMapper getDataMapper() {
return dataMapper;
}
public void setDataMapper(DataMapper dataMapper) {
this.dataMapper = dataMapper;
}
}
|
public class Speaker {
int maxVolume;
int crtVolume;
public Speaker(int maxVolume){
this.maxVolume=maxVolume;
this.crtVolume=maxVolume/4;
}
public Speaker(int maxVolume,int crtVolume){
this.maxVolume=maxVolume;
this.crtVolume=crtVolume;
}
public boolean increaseVolume(){
if(this.crtVolume<this.maxVolume){
this.crtVolume++;
return true;
}else return false;
}
public boolean decreaseVolume(){
if(this.crtVolume>0){
this.crtVolume--;
return true;
}
else return false;
}
public void setSilenceMode(){
this.crtVolume=0;
}
public void setCrtVolume(int crtVolume) {
if(crtVolume+this.crtVolume<this.maxVolume)
this.crtVolume = crtVolume;
else this.crtVolume=this.maxVolume;
}
}
|
package org.liuchang.service.finance.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.liuchang.bean.finance.PayVO;
import org.liuchang.bean.finance.SearchData;
import org.liuchang.dao.finance.IFinanceDetailDao;
import org.liuchang.service.finance.IFinanceDetailService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by liuchang on 2016/4/6.
*/
@Service("financeDetailService")
public class FinanceDetailServiceImpl implements IFinanceDetailService {
@Resource
IFinanceDetailDao financeDetailDao;
@Override
public void sayHello() {
System.out.println("Hello Mybatis!");
}
@Override
public int count() {
return financeDetailDao.count();
}
@Override
public String getDataJson(SearchData searchData) {
String json = "";
try {
Map dataMap = new HashMap();
dataMap.put("data", financeDetailDao.getData(searchData));
dataMap.put("sum", financeDetailDao.getDataTotal(searchData));
//dataMap.put("total",100);
ObjectMapper om = new ObjectMapper();
json = om.writeValueAsString(dataMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
@Override
public HSSFWorkbook getDataForExcel(SearchData searchData) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet("sheet1");
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short) 15);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
//style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
//font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style2.setFont(font2);
//// 声明一个画图的顶级管理器
//HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
//// 定义注释的大小和位置,详见文档
//HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
//// 设置注释内容
//comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
//// 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
//comment.setAuthor("leno");
String[] headers = {"日期", "类型", "名称", "金额"};
//产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍历集合数据,产生数据行
List<PayVO> list = financeDetailDao.getData(searchData);
for (int i = 0; i < list.size(); i++) {
PayVO p = list.get(i);
row = sheet.createRow(i + 1);
HSSFCell cell = row.createCell(0);
cell.setCellStyle(style);
cell.setCellValue(p.getDate());
cell = row.createCell(1);
cell.setCellStyle(style);
cell.setCellValue(p.getType_name());
cell = row.createCell(2);
cell.setCellStyle(style);
cell.setCellValue(p.getName());
cell = row.createCell(3);
cell.setCellStyle(style);
cell.setCellValue(p.getMoney());
}
return workbook;
}
@Override
public void addData(PayVO payVO) {
financeDetailDao.addData(payVO);
}
@Override
public void modifyData(PayVO payVO) {
financeDetailDao.modifyData(payVO);
}
@Override
public void delData(String id) {
financeDetailDao.delData(id);
}
}
|
package com.yy.lite.brpc.interceptor.domain;
import com.yy.aomi.sdk.tracecontext.HandleTraceContext;
public class BrpcHandleTraceContext extends HandleTraceContext {
public static final String BRPC_THREADPOOL_MODEL_KEY = "brpc_work_threadpool";
public BrpcHandleTraceContext() {
this(BRPC_THREADPOOL_MODEL_KEY);
}
public BrpcHandleTraceContext(String handleId) {
super(handleId);
}
}
|
/*
* 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 guioptimiser;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Random;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Mahmoud-Uni
*/
public class GuiOptimiser {
//private static String TARGET_APP = "calculator.jar";
private static String TARGET_APP = "simpleApp.jar";
private static final String TARGET_APP_COLOR = "color.csv";
private static final int TARGET_APP_RUNNINGTIME = 2000;
private static final String JAVA_COMMAND = "java -jar ";
private static String parentDir = "";
private static int screenshotsNum = 1000;
private static int screenshot = 1;
private static ArrayList<Long> results = new ArrayList<Long>();
private static String line = "";
private static long solution = 999999999;
private static long bestsolution = 999999999;
private static int RS = 3;
//simulated annealing operators
private static double temperature = 110.0;
private static double coolingRate = 0.99;
private final static double minTemperature = 0.5;
private static ArrayList<ArrayList<Integer>> randomRGB = new ArrayList<>();
private static Random randomGenerator = new Random();
private static int saNeigbourhoodSize = 200;
private static int sanumberOfNeighbours = 20 ;
private static int noResult = 0;
private static ArrayList<String> guiComponents = new ArrayList<>();
private static ArrayList<ArrayList<Integer>> RGB = new ArrayList<>();
private static ArrayList<ArrayList<Integer>> prevRGB = new ArrayList<>();
private static ArrayList<ArrayList<Integer>> RGBNew = new ArrayList<>();
private static Random randomInt = new Random();
private static String filename = "";
private static int numberOfScreenShots = 0;
private static int hillClimbingNeigbourhoodSize = 50;
private static int numberOfNeighbours = 20;
/**
* @param args the command line arguments
* @throws IOException
*/
public static void main(String[] args) throws IOException{
// first run the target app
switch (args[0]) {
case "calculator.jar":
TARGET_APP = args[0].trim();
System.out.println(args[0]);
break;
case "simpleApp.jar":
TARGET_APP = args[0].trim();
System.out.println(args[0]);
break;
default:
System.out.println(args[0]);
return;
}
parentDir = getParentDir();
solution = solution*solution;
//System.out.println(parentDir.concat(TARGET_APP));
for (int i = 0; i < screenshotsNum; i++) //RunTargetApp runTargetApp = new RunTargetApp(parentDir.concat(TARGET_APP), TARGET_APP_RUNNINGTIME);
{
//runApp(parentDir.concat(TARGET_APP), TARGET_APP_RUNNINGTIME);
//runApp(TARGET_APP, TARGET_APP_RUNNINGTIME);
if(RS == 1) {
randomSearch(screenshotsNum,i);
}
if(RS == 3) {
simulatedAnnealingSearch(screenshotsNum,i, saNeigbourhoodSize, sanumberOfNeighbours);
}
}
if(RS == 2){
hillClimbingSearch(screenshotsNum, hillClimbingNeigbourhoodSize, numberOfNeighbours);
}
writeResultsToExcel(parentDir.concat("finalResults.csv"),results);
}
public static void runApp(String path, int targetAppRunningtime) {
try {
//java -jar C:\Users\Mahmoud-Uni\Documents\NetBeansProjects\calculator\dist\calculator.jar
//path = "\""+path+"\"";
//System.out.println("Target App" + path);
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec(JAVA_COMMAND.concat(path));
try {
Thread.sleep(targetAppRunningtime);
Capture capture = new Capture();
filename = capture.takeScreenShoot();
// BufferedReader stdError = new BufferedReader(new
// InputStreamReader(process.getErrorStream()));
// String line = "";
// while((line=stdError.readLine())!=null)
// {
// System.out.println("error!");
// System.out.println(line);
// }
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("Target App");
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
public static long calculateChargeConsumptionPerPixel(String path) throws IOException {
BufferedImage image = ImageIO.read(new File(path));
int width = image.getWidth();
int height = image.getHeight();
int pixelCount = 0;
long consumption = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height ; y++) {
int pixel = image.getRGB(x, y);
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
consumption += red*(120) + green*(140) + blue*(240);
pixelCount++;
}
}
//System.out.printf("pixelCount = %d Total Consumtion = %d Number = %d %n", pixelCount, consumption, screenshot);
System.out.println(screenshot);
screenshot++;
return consumption/3686400;
}
public static void deleteCapture() {
File file = new File(parentDir.concat(filename));
file.delete();
}
public static void randomSearch(int num, int count) throws IOException {
changeColorAll();
long result = calculateChargeConsumptionPerPixel(parentDir.concat(filename));
results.add( result );
if ( result < solution) {
solution = result;
}
else {
deleteCapture();
}
System.out.println(solution);
}
public static void writeResultsToExcel(String filePath, ArrayList<Long> results){
try {
BufferedWriter br = new BufferedWriter(new FileWriter(new File(filePath)));
String line = "";
for (int i = 0; i < results.size(); i++) {
line += results.get(i)+ "\n";
//System.out.println(line);
}
br.write(line);
br.flush();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void changeColorAll() {
try {
// guiComponents contains GUI components' name.
ArrayList<String> guiComponents = new ArrayList<>();
guiComponents.add("mainFrameColor"); // both apps
guiComponents.add("jButton1");// both apps
guiComponents.add("jButton2");
guiComponents.add("jButton3");
guiComponents.add("jButton4");
guiComponents.add("jButton5");
guiComponents.add("jButton6");
guiComponents.add("jButton7");
guiComponents.add("jButton8");
guiComponents.add("jButton9");
guiComponents.add("jButton10");
guiComponents.add("jButton11");
guiComponents.add("jButton12");
guiComponents.add("jButton13");
guiComponents.add("jButton14");
guiComponents.add("jButton15");
guiComponents.add("jButton16");
guiComponents.add("jButton17");
guiComponents.add("jButton18");
guiComponents.add("jTextField1");// both apps
guiComponents.add("jTextField1TextColor");// both apps
guiComponents.add("jLabel1");// both apps
guiComponents.add("jPanel1");// both apps
guiComponents.add("jPanel2");
guiComponents.add("jPanel3");
guiComponents.add("jPanel4");
guiComponents.add("jPanel5");
ArrayList<ArrayList<Integer>> RGB = new ArrayList<>();
Random randomInt = new Random();
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)}))); //jTextField1
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)}))); //jTextField1TextColor
while(Math.sqrt((RGB.get(20).get(0)-RGB.get(21).get(0))^2 + (RGB.get(20).get(1)-RGB.get(21).get(1))^2 + (RGB.get(20).get(2)-RGB.get(21).get(2))^2) < 128) {
RGB.get(21).set( 0, randomInt.nextInt(256));
RGB.get(21).set( 1, randomInt.nextInt(256));
RGB.get(21).set( 2, randomInt.nextInt(256));
}
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
RGB.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{randomInt.nextInt(256), randomInt.nextInt(256), randomInt.nextInt(256)})));
saveToCSV(parentDir.concat(TARGET_APP_COLOR), guiComponents, RGB);
prevRGB = RGB;
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveToCSV(String filePath, ArrayList<String> guiComponents, ArrayList<ArrayList<Integer>> RGB) {
try {
BufferedWriter br = new BufferedWriter(new FileWriter(new File(filePath)));
String line = "";
for (int i = 0; i < guiComponents.size(); i++) {
line += guiComponents.get(i).concat(",").concat(RGB.get(i).toString().replace("[", "").replace("]", "").replaceAll("\\s", "")) + "\n";
//System.out.println(line);
}
br.write(line);
br.flush();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedWriter br = new BufferedWriter(new FileWriter(new File(parentDir.concat("results.csv"))));
for (int i = 0; i < guiComponents.size(); i++) {
if(i == (guiComponents.size()-1)){
line += RGB.get(i).toString().replace("[", "").replace("]", "").replaceAll("\\s", "") +"\n";
}
else {
line += RGB.get(i).toString().replace("[", "").replace("]", "").replaceAll("\\s", "") + ",";
}
//System.out.println(line);
}
br.write(line);
br.flush();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getParentDir() {
String dir = "";
try {
File temp = new File("temp");
dir = temp.getAbsolutePath().replace("temp", "");
//System.out.println(dir);
} catch (Exception e) {
e.printStackTrace();
}
return dir;
}
//hill climbing search with give size of neigbourhood
public static void hillClimbingSearch(int totalScreenShots, int sizeOfNeighbourHood, int numberOfNeighbours) throws IOException{
//the first claculator has a random intal value
//generate a random RGB array
changeColorAll();
boolean betterNeighbourFound = true;
//run method until we used up all the screenshots
while((numberOfScreenShots < totalScreenShots)){
//generate neibouring solutions
ArrayList<ArrayList<ArrayList<Integer>>> RGBNeigbours = GenerateNeighbours(prevRGB, sizeOfNeighbourHood, numberOfNeighbours);
betterNeighbourFound = false;
for (ArrayList<ArrayList<Integer>> RGBValue : RGBNeigbours) {
//run app and save to file so app can read it
addGUIComponetsCalculator();
runApp(TARGET_APP, TARGET_APP_RUNNINGTIME);
saveToCSV(parentDir.concat(TARGET_APP_COLOR), guiComponents, RGBValue);
// get the result of the charge cosumtion
long result = calculateChargeConsumptionPerPixel(parentDir.concat(filename));
//check if solution is good
if ( result < solution) {
solution = result;
prevRGB = RGBValue;
betterNeighbourFound = true;
results.add( result );
System.out.println(solution);
System.out.println(filename);
}
else {
//delete bad solution screenshots
deleteCapture();
}
numberOfScreenShots++;
}
//reduce the scope of the neighbourhood
if(sizeOfNeighbourHood > 5){
float newSize = sizeOfNeighbourHood / 1.1f;
sizeOfNeighbourHood = (int) newSize;
}
//if no new neigbours are found this is the local optimum so try anoter random starting point
if(!betterNeighbourFound){
System.out.println("no better Neighbour found generating another random");
changeColorAll();
}
}
}
//adds the componets needed for the calculator
public static void addGUIComponetsCalculator(){
//guiComponents contains GUI components' name.
guiComponents = new ArrayList<>();
guiComponents.add("mainFrameColor"); // both apps
guiComponents.add("jButton1");// both apps
guiComponents.add("jButton2");
guiComponents.add("jButton3");
guiComponents.add("jButton4");
guiComponents.add("jButton5");
guiComponents.add("jButton6");
guiComponents.add("jButton7");
guiComponents.add("jButton8");
guiComponents.add("jButton9");
guiComponents.add("jButton10");
guiComponents.add("jButton11");
guiComponents.add("jButton12");
guiComponents.add("jButton13");
guiComponents.add("jButton14");
guiComponents.add("jButton15");
guiComponents.add("jButton16");
guiComponents.add("jButton17");
guiComponents.add("jButton18");
guiComponents.add("jTextField1");// both apps
guiComponents.add("jTextField1TextColor");// both apps
guiComponents.add("jLabel1");// both apps
guiComponents.add("jPanel1");// both apps
guiComponents.add("jPanel2");
guiComponents.add("jPanel3");
guiComponents.add("jPanel4");
guiComponents.add("jPanel5");
}
//returns a neigbourhood from a give RGB array
public static ArrayList<ArrayList<ArrayList<Integer>>> GenerateNeighbours(ArrayList<ArrayList<Integer>> currentRGB, int sizeOfNeighbourHood, int numberOfNeighbours){
ArrayList<ArrayList<ArrayList<Integer>>> allRGBNeigbours = new ArrayList<>();
//generate neibours
//loop over each RGB component
for(int i = 0; i < numberOfNeighbours; i++){
ArrayList<ArrayList<Integer>> neighbourRGB = new ArrayList<ArrayList<Integer>>();
for(int j = 0; j < currentRGB.size(); j++){
//get a random RGB index colour
int index = randomInt.nextInt(3);
int currentRGBValue = currentRGB.get(j).get(index);
int randomNumber = randomInt.nextInt(3);
//randomlly pick either to add or subtract colours or do nothing
if(randomNumber == 0){
if(currentRGBValue - sizeOfNeighbourHood >= 0) currentRGBValue -= randomInt.nextInt(sizeOfNeighbourHood);
}
else if(randomNumber == 1){
if(currentRGBValue + sizeOfNeighbourHood <= 255) currentRGBValue += randomInt.nextInt(sizeOfNeighbourHood);
}
else{
//do nothing
}
//create array with the new values in it
ArrayList<Integer> newRGB = new ArrayList<Integer>(currentRGB.get(j));
newRGB.set(index, currentRGBValue);
neighbourRGB.add(newRGB);
}
//if neigbour doesn't satsify, dont add it to the neighbourhood
if(isNotValidEuclidenDistance(neighbourRGB)){
// System.out.println("Limted by Euclidean Distance");
}else{
allRGBNeigbours.add(neighbourRGB);
}
}
return allRGBNeigbours;
}
public static boolean isNotValidEuclidenDistance(ArrayList<ArrayList<Integer>> inputRGB){
ArrayList<Integer> colour1 = new ArrayList<Integer>();
ArrayList<Integer> colour2 = new ArrayList<Integer>();
if(TARGET_APP.equals("calculator.jar")){
colour1 = inputRGB.get(20);
colour2 = inputRGB.get(21);
}
if(TARGET_APP.equals("simpleApp.jar")){
colour1 = inputRGB.get(2);
colour2 = inputRGB.get(3);
}
if(EuclideanDistanceBetweenTheColours(colour1, colour2) < 128){
return false;
}
return true;
}
//reutrns the difference between colors where ArrayList<Integer> = [red, green, blue]
public static double EuclideanDistanceBetweenTheColours(ArrayList<Integer> colour1, ArrayList<Integer> colour2){
double red = Math.pow(colour1.get(0) - colour2.get(0), 2);
double green = Math.pow(colour1.get(1) - colour2.get(1), 2);
double blue = Math.pow(colour1.get(2) - colour2.get(2), 2);
double distance = Math.sqrt(red + green + blue);
return distance;
}
public static void simulatedAnnealingSearch(int totalScreenShots, int current, int sizeOfNeighbourHood, int numberOfNeighbours) throws IOException{
//generate one random solution
if(current == 0){
changeColorAll();
}
//run method until 1000 screenshots are reached
while((numberOfScreenShots < totalScreenShots)){
//generate neighbouring solutions
ArrayList<ArrayList<ArrayList<Integer>>> RGBNeigbours = GenerateNeighbours(prevRGB, sizeOfNeighbourHood,numberOfNeighbours);
System.out.println("new neigbourhoods");
System.out.println(RGBNeigbours.size());
//variable for deciding the new neighbour usage
boolean usenew = false;
//loop through the neighbours
for (ArrayList<ArrayList<Integer>> RGBValue : RGBNeigbours) {
//pick one neighbour at random
int index = randomGenerator.nextInt(RGBNeigbours.size());
randomRGB = RGBNeigbours.get(index);
//System.out.println("current " + RGBValue);
//System.out.println("random " + randomRGB);
//evaluate the chargeConsumption
//run app and save to file so app can read it
addGUIComponetsCalculator();
runApp(TARGET_APP, TARGET_APP_RUNNINGTIME);
//neighbour result
long neighbourresult1 = calculateChargeConsumptionPerPixel(parentDir.concat(filename));
//difference between neighbour/working solution and current solution
long chargedifference = solution - neighbourresult1;
System.out.println("current consumption " + solution);
System.out.println("working consumption " + neighbourresult1);
//check if current neighbour solution is good
if ( neighbourresult1 < solution) {
usenew = true;
solution = neighbourresult1;
}
//allow bad neighbours with certain probability p = exp(loss/temp) < 1
else if (Math.exp((chargedifference) / temperature) < Math.random()) {
solution = neighbourresult1;
prevRGB = randomRGB;
results.add(neighbourresult1 );
usenew = true;
System.out.println("worse neighbour, still allowed with certain probability");
System.out.println(solution);
// System.out.println(filename);
}else {
//delete bad solution screenshots
deleteCapture();
}
//if we are using the new value, compare it with previous best solutions
if(usenew) {
usenew = false;
prevRGB = randomRGB;
if(neighbourresult1 < bestsolution ) {
bestsolution = neighbourresult1;
saveToCSV(parentDir.concat(TARGET_APP_COLOR), guiComponents, prevRGB);
}else
{
solution = neighbourresult1;
saveToCSV(parentDir.concat(TARGET_APP_COLOR), guiComponents, prevRGB);
//delete unwanted screenshots
deleteCapture();
}
}
System.out.println("best solution "+ bestsolution);
System.out.println("file name " + filename);
// RGBNeigbours = GenerateNeighbours(prevRGB, sizeOfNeighbourHood,numberOfNeighbours);
//reduce the scope of the neighbourhood
if(sizeOfNeighbourHood > 5){
float newSize = sizeOfNeighbourHood / 1.1f;
sizeOfNeighbourHood = (int) newSize;
}
numberOfScreenShots++;
System.out.println("temp " + temperature );
//reduce the temperature
temperature*=coolingRate;
//if the system cools down before the 1000 screenshots, restart the system
if (temperature < minTemperature) {
System.out.println("Temperature " + temperature);
System.out.println("Starting again");
changeColorAll();
temperature = 110.0;
}
}
}
}
}
|
package com.outsideintdd.katas.scoreboard;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ScoreKeeperShould {
@Mock BasketRepository basketRepository;
@Mock ScorePrinter scorePrinter;
private ScoreKeeper scoreKeeper;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
scoreKeeper = new ScoreKeeper(basketRepository, scorePrinter);
}
@Test public void
storeTeamA1pBasket() throws Exception {
scoreKeeper.scoreTeamA1();
verify(basketRepository).add1point(Team.A);
}
@Test public void
storeTeamA2pBasket() throws Exception {
scoreKeeper.scoreTeamA2();
verify(basketRepository).add2points(Team.A);
}
@Test public void
storeTeamA3pBasket() throws Exception {
scoreKeeper.scoreTeamA3();
verify(basketRepository).add3points(Team.A);
}
@Test public void
storeTeamB1pBasket() throws Exception {
scoreKeeper.scoreTeamB1();
verify(basketRepository).add1point(Team.B);
}
@Test public void
storeTeamB2pBasket() throws Exception {
scoreKeeper.scoreTeamB2();
verify(basketRepository).add2points(Team.B);
}
@Test public void
storeTeamB3pBasket() throws Exception {
scoreKeeper.scoreTeamB3();
verify(basketRepository).add3points(Team.B);
}
@Test public void
printTheScore() throws Exception {
int teamAScore = 0;
int teamBScore = 1;
when(basketRepository.getScore(Team.A)).thenReturn(teamAScore);
when(basketRepository.getScore(Team.B)).thenReturn(teamBScore);
scoreKeeper.getScore();
verify(scorePrinter).print(teamAScore, teamBScore);
}
}
|
package com.company;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Scanner;
public class TicketManager {
ArrayList<Ticket> tickets = new ArrayList<>();
void create(Ticket ticket, Scanner scanner, boolean isBusinessSeat){
System.out.println("please insert passenger's name");
String passengersName = scanner.next();
ticket.setPassengersName(passengersName);
ticket.setDateOfIssue(LocalDate.now());
System.out.println("please insert ticket's price");
ticket.setTicketPrice( Validator.requestInt(scanner));
tickets.add(ticket);
for(Ticket ticket1 : tickets) {
System.out.println(ticket1.toString());
}
}
void removeTicket(int ticketId) {
for (Ticket ticket1 : tickets){
if(ticket1.getTicketId() == ticketId){
tickets.remove(ticket1);
}
}
for(Ticket ticket1 : tickets) {
System.out.println(ticket1.toString());
}
}
}
|
package com.plexobject.dp.sample.dao;
public interface Filter<T> {
boolean accept(T object);
}
|
package com.example.localdatatimedemo.support;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
/**
* Description TODO
*
* @author Roye.L
* @date 2019/4/8 22:58
* @since 1.0
*/
public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
@Override
public JsonElement serialize(LocalDateTime dateTime, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateTime.toString());
}
}
|
package generic_test;
import java.util.ArrayList;
public class Test1 {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.setName("zs");
d1.setAge(10);
Dog d2 = new Dog();
d2.setName("ls");
d2.setAge(9);
ArrayList<Dog> al = new ArrayList<>();
ArrayList _al = new ArrayList();
al.add(d1);
al.add(d2);
_al.add(d1);
_al.add(d2);
Dog d = al.get(1);
Object o = _al.get(1);
System.out.println(d);
System.out.println(o);
Dog _d = null;
if (o instanceof Dog) {
_d = (Dog) o;
}
System.out.println(_d.getName());
System.out.println(_d.getAge());
// Cat c = (Cat) o;
// System.out.println(c.getName());// ClassCastException
// System.out.println(c.getAge());// ClassCastException
}
}
|
//Singletone with Enum
public class Connection
{
private static Connection connection=new Connection();
public enum ConnectionState
{
WIFI,MobileNetwork,NoConnection;
}
//Private ctor
private Connection( )
{
}
//public Connection( EnumState.ConnectionState c)
//{
//this.CS=C;
//}
public void getState(ConnectionState cs)
{
if(cs==ConnectionState.WIFI)
{
System.out.println("Connected to WIFI.");
}
if(cs==ConnectionState.MobileNetwork)
{
System.out.println("Connected to MobileNetwork");
}
}
//get only object
public static Connection getInstance()
{
return connection;
}
public static void main(String []args)
{
connection.getState(ConnectionState.WIFI);
//Connection object=Connection.getInstance();
//object.getState();
}
}
|
package com.tencent.mm.plugin.qqmail.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.qqmail.b.o;
import com.tencent.mm.plugin.qqmail.b.w;
import com.tencent.mm.plugin.qqmail.b.y;
import com.tencent.mm.plugin.qqmail.ui.b.3;
class b$3$1 implements OnClickListener {
final /* synthetic */ 3 mgw;
b$3$1(3 3) {
this.mgw = 3;
}
public final void onClick(DialogInterface dialogInterface, int i) {
if (this.mgw.mgu.state == 0 || this.mgw.mgu.state == 1) {
b bVar = this.mgw.mgt;
y yVar = this.mgw.mgu;
if (bVar.mode == 5) {
w.bow().cancel(yVar.mea);
} else if (bVar.mode == 6) {
o oVar = (o) bVar.mgn.get(yVar.path);
if (oVar != null) {
au.DF().c(oVar);
}
bVar.mgo.remove(yVar.path);
bVar.mgp.remove(yVar.path);
}
}
this.mgw.mgt.mgm.remove(this.mgw.mgu.path);
this.mgw.mgt.mgn.remove(this.mgw.mgu.path);
this.mgw.mgt.mgo.remove(this.mgw.mgu.path);
this.mgw.mgt.mgp.remove(this.mgw.mgu.path);
this.mgw.mgt.mgl.removeView(this.mgw.mgv);
this.mgw.mgt.boV();
}
}
|
package com.d3ti.pbolanj.thread3;
class ThreadUtama {
public void jalan(String name) {
for(int i=1;i<6;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread "+name+" posisi: "+i);
}
}
}
|
package com.luhc.blog.entity;
public class Author {
private Long id;
private String authorName;
private String authorPassword;
private String authorEmail;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getAuthorPassword() {
return authorPassword;
}
public void setAuthorPassword(String authorPassword) {
this.authorPassword = authorPassword;
}
public String getAuthorEmail() {
return authorEmail;
}
public void setAuthorEmail(String authorEmail) {
this.authorEmail = authorEmail;
}
@Override
public String toString() {
return "Author [id=" + id + ", authorName=" + authorName + ", authorPassword=" + authorPassword
+ ", authorEmail=" + authorEmail + "]";
}
}
|
package com.tencent.mm.plugin.wallet_core.ui.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import com.tencent.mm.sdk.platformtools.x;
public class WalletScratchShakeView extends FrameLayout {
boolean pAa;
boolean pAb;
private a pAc;
b pzZ;
public WalletScratchShakeView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
public WalletScratchShakeView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
}
public void setScratchShakeCallback(a aVar) {
this.pAc = aVar;
}
public final void onDestroy() {
if (this.pzZ != null) {
b bVar = this.pzZ;
x.i("MicroMsg.WalletScratchShakeView", "onDestroy");
if (bVar.lAY != null) {
bVar.lAY.aDc();
}
}
}
}
|
/*
* 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 myobs;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* @author egese
*/
public class NoteList extends UserLogin { // Not Listesi için
protected String[] Dersler = new String[]{"Nesneye Yönelik Programlama","Elektrik Devre Temelleri","Matematik","Fizik","İngilizce"};
protected int[][][] Notlar = new int[5][2][5];
java.util.Scanner scan = new java.util.Scanner(System.in);
MeanNote meanv = new MeanNote();
public void NoteList()
{
}
public void createList() // Girilen kullanıcının not listesini oluşturmak için
{
for (int i = 0; i < 5; i++) {
System.out.println(Dersler[i] + ":");
System.out.println("Vize : ");
Notlar[i][0][tempID-1] = scan.nextInt();
System.out.println("Final : ");
Notlar[i][1][tempID-1] = scan.nextInt();
meanv.FindLetterNote(Notlar, i) ;
}
}
public void checkList() // Not listesini göstermek için
{
for (int i = 0; i < 5; i++) {
System.out.println(Dersler[i] + ":");
System.out.print("Vize : " + Notlar[i][0][tempID-1]);
System.out.print(" Final : " + Notlar[i][1][tempID-1]);
System.out.println(" Harf : "+ meanv.FindLetterNote(Notlar, i));
}
System.out.println("GANO : "+meanv.ShowMeanNote());
}
public void saveList() throws FileNotFoundException, IOException // Not listesini dosyaya kaydetmek için
{
File file = new File("test.txt") ;
PrintWriter output = new PrintWriter(file);
for (int i = 0; i < 5; i++) {
output.println(Dersler[i] + ":");
output.print("Vize : " + Notlar[i][0][tempID-1]);
output.print(" Final : " + Notlar[i][1][tempID-1]);
output.println(" Harf : "+meanv.FindLetterNote(Notlar, i));
}
output.println("GANO : "+meanv.ShowMeanNote());
output.close();
}
}
|
public class CountingSemaphore {
int count = 0;
public CountingSemaphore (int count) {
this.count = count;
}
public synchronized void up () {
count++;
notifyAll();
}
public synchronized void down() throws InterruptedException {
if (count == 0) wait();
count++;
notifyAll();
}
public int getValue() {
return this.count;
}
}
|
package it.dstech.film.service;
import it.dstech.film.model.Genere;
public interface GenereService {
Genere findById(int id);
void save(Genere genere);
}
|
package Chapter6Review;
//E6.6
public class DataSet {
private double value;
private double sum = 0;
private int counter = 0;
private double smallest;
private double largest;
private Boolean firstRun = true;
public DataSet() {
}
public void add(double aValue) {
value = aValue;
sum = sum + value;
counter++;
if (firstRun) {
smallest = value;
largest = value;
firstRun = false;
} else if (!firstRun && smallest > value) {
smallest = value;
} else if (!firstRun && largest < value) {
largest = value;
}
}
public double getAverage() {
double average = sum / counter;
return average;
}
public double getSmallest() {
return smallest;
}
public double getLargest() {
return largest;
}
public double getRange() {
double range = largest - smallest;
return range;
}
}
|
package org.processmining.plugins.PromMasterPlugin.processmining.plugins.improvediscovery;
public class OLAPDiscoveryConfiguration {
String name;
public OLAPDiscoveryConfiguration(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package dev.etna.jabberclient.xmpp;
import android.content.Context;
import android.content.res.Resources;
public enum XMPPServiceError
{
LOGIN_BAD_CREDENTIALS,
LOGIN_UNEXPECTED_ERROR,
LOGOUT_UNEXPECTED_ERROR,
CONTACT_ADD_UNEXPECTED_ERROR,
CONTACT_DELETE_UNEXPECTED_ERROR,
CONTACT_FETCH_UNEXPECTED_ERROR,
CONTACT_PROFILE_NOT_FOUND,
CONTACT_PROFILE_UNEXPECTED_ERROR;
/**
* Returns a localized label used to represent this enumeration value. If no label
* has been defined, then this defaults to the result of {@link Enum#name()}.
*
* <p>The name of the string resource for the label must match the name of the enumeration
* value. For example, for enum value 'ENUM1' the resource would be defined as 'R.string.ENUM1'.
*
* @param context the context that the string resource of the label is in.
* @return a localized label for the enum value or the result of name()
*/
public String getLabel(Context context)
{
int resourceID;
Resources resources;
String key;
String label;
if (context == null)
{
return this.name();
}
key = "error_" + this.name().toLowerCase();
resources = context.getResources();
resourceID = resources.getIdentifier(key, "string", context.getPackageName());
label = (resourceID != 0) ? resources.getString(resourceID) : this.name();
return label;
}
}
|
/*
* UniTime 3.5 (University Timetabling Application)
* Copyright (C) 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.solver.jgroups;
import java.util.Date;
import java.util.List;
import org.jgroups.Address;
import org.unitime.timetable.interfaces.RoomAvailabilityInterface;
import org.unitime.timetable.onlinesectioning.OnlineSectioningServer;
import org.unitime.timetable.solver.SolverProxy;
import org.unitime.timetable.solver.exam.ExamSolverProxy;
import org.unitime.timetable.solver.studentsct.StudentSolverProxy;
/**
* @author Tomas Muller
*/
public interface SolverServer {
public static final short SCOPE_SERVER = 0, SCOPE_COURSE = 1, SCOPE_EXAM = 2, SCOPE_STUDENT = 3, SCOPE_AVAILABILITY = 4, SCOPE_ONLINE = 5;
public void start();
public void stop();
public boolean isLocal();
public boolean isCoordinator();
public Address getAddress();
public Address getLocalAddress();
public String getHost();
public Date getStartTime();
public int getUsage();
public String getVersion();
public void setUsageBase(int usage);
public long getAvailableMemory();
public int getAvailableProcessors();
public long getMemoryLimit();
public boolean isActive();
public boolean isAvailable();
public void shutdown();
public SolverContainer<SolverProxy> getCourseSolverContainer();
public SolverContainer<ExamSolverProxy> getExamSolverContainer();
public SolverContainer<StudentSolverProxy> getStudentSolverContainer();
public SolverContainer<OnlineSectioningServer> getOnlineStudentSchedulingContainer();
public RoomAvailabilityInterface getRoomAvailability();
public void refreshCourseSolution(Long... solutionId);
public void refreshExamSolution(Long sessionId, Long examTypeId);
public void setApplicationProperty(Long sessionId, String key, String value);
public void setLoggingLevel(String name, Integer level);
public void reset();
public List<SolverServer> getServers(boolean onlyAvailable);
public SolverServer crateServerProxy(Address address);
}
|
package com.magicalcoder.youyaboot.model;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.math.*;
import java.io.Serializable;
import lombok.Data;
/**
* 代码为自动生成 Created by www.magicalcoder.com
* 软件作者:何栋宇 qq:709876443
* 如果你改变了此类 read 请将此行删除
* 欢迎加入官方QQ群:648595928
*/
@Data
public class Goods implements Serializable{
private Long id;//主键
private String goodsName;//商品名
private String publishStatus;//是否发布
private Byte goodsStatus;//商品状态
private BigDecimal price;//价格
private Integer storeCount;//库存
private String shortBrief;//简介
private String goodsDescription;//商品描述
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Timestamp createTime;//创建时间
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm:ss" )
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private Timestamp updateTime;//更新时间
private String imgSrc;//图片
private Long goodsCategoryId;//所属类目
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public String getGoodsName(){
return goodsName;
}
public void setGoodsName(String goodsName){
this.goodsName = goodsName;
}
public String getPublishStatus(){
return publishStatus;
}
public void setPublishStatus(String publishStatus){
this.publishStatus = publishStatus;
}
public Byte getGoodsStatus(){
return goodsStatus;
}
public void setGoodsStatus(Byte goodsStatus){
this.goodsStatus = goodsStatus;
}
public BigDecimal getPrice(){
return price;
}
public void setPrice(BigDecimal price){
this.price = price;
}
public Integer getStoreCount(){
return storeCount;
}
public void setStoreCount(Integer storeCount){
this.storeCount = storeCount;
}
public String getShortBrief(){
return shortBrief;
}
public void setShortBrief(String shortBrief){
this.shortBrief = shortBrief;
}
public String getGoodsDescription(){
return goodsDescription;
}
public void setGoodsDescription(String goodsDescription){
this.goodsDescription = goodsDescription;
}
public Timestamp getCreateTime(){
return createTime;
}
public void setCreateTime(Timestamp createTime){
this.createTime = createTime;
}
public Timestamp getUpdateTime(){
return updateTime;
}
public void setUpdateTime(Timestamp updateTime){
this.updateTime = updateTime;
}
public String getImgSrc(){
return imgSrc;
}
public void setImgSrc(String imgSrc){
this.imgSrc = imgSrc;
}
public Long getGoodsCategoryId(){
return goodsCategoryId;
}
public void setGoodsCategoryId(Long goodsCategoryId){
this.goodsCategoryId = goodsCategoryId;
}
}
|
package bookexercises.chapter1.fundamentals.one;
import edu.princeton.cs.algs4.StdOut;
/**
* Puts the binary representation of a positive integer N into a String s
*/
public class Nine {
/**
*
* @author atlednolispe
*/
public static String convert1(int N) {
String res = "";
while (N > 0)
{
res = N % 2 + res;
N /= 2;
}
return res;
}
public static String convert2(int N) {
return Integer.toBinaryString(N);
}
public static String convert3(int N) {
String s = "";
for (int n = N; n > 0; n /= 2)
s = (n % 2) + s;
return s;
}
public static void main(String[] args) {
int N = 10;
StdOut.println(convert1(N));
StdOut.println(convert2(N));
StdOut.println(convert3(N));
}
}
|
package org.tyaa.java.springboot.gae.simplespa.JavaSpringBootGaeSimpleSpa.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.google.gson.annotations.Expose;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Ignore;
import com.googlecode.objectify.annotation.Index;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.tyaa.java.springboot.gae.simplespa.JavaSpringBootGaeSimpleSpa.utils.BigDecimalDeserializer;
import org.tyaa.java.springboot.gae.simplespa.JavaSpringBootGaeSimpleSpa.utils.MoneySerializer;
import java.math.BigDecimal;
@Data
@Builder(toBuilder = true)
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Entity(name = "Products")
public class ProductModel {
@Id
private Long id;
@Index
@Expose
private String title;
@Expose
private String description;
@Index
@Expose
private Double price;
@Index
@Expose
private Integer quantity;
private String image;
@Index
@Expose
private Long categoryId;
@Ignore
private CategoryModel category;
}
|
package net.tyas.laundry.ui.main;
import com.androidnetworking.error.ANError;
import io.reactivex.functions.Consumer;
import net.tyas.laundry.data.DataManager;
import net.tyas.laundry.data.network.model.Category;
import net.tyas.laundry.utils.rx.SchedulerProvider;
import net.tyas.laundry.ui.base.BasePresenter;
import io.reactivex.disposables.CompositeDisposable;
import javax.inject.Inject;
import java.util.List;
public class MainPresenter<V extends MainView> extends BasePresenter<V> implements MainMvpPresenter<V>{
@Inject
public MainPresenter(DataManager dataManager, SchedulerProvider schedulerProvider, CompositeDisposable compositeDisposable) {
super(dataManager, schedulerProvider, compositeDisposable);
}
}
|
package com.ahsel.simbirsoft.models;
import javax.persistence.*;
@Entity
@Table(name = "words")
public class Words {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String word;
private int count;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Words() {
}
public Words(String word, int count) {
this.word = word;
this.count = count;
}
}
|
package com.pfchoice.springboot.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.Where;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.pfchoice.springboot.util.JsonDateDeserializer;
import com.pfchoice.springboot.util.JsonDateSerializer;
/**
*
* @author SarathGandluri
*/
@Entity
@Table(name = "membership_problems")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class MembershipProblem extends RecordDetails implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "mbr_pbm_id", nullable = false)
private Integer id;
@JsonIgnore
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "mbr_id", nullable = false, referencedColumnName = "mbr_id")
@Where(clause = "active_ind ='Y'")
private Membership mbr;
@OneToOne(fetch = FetchType.LAZY)
@NotNull(message = "Select ICD")
@JoinColumn(name = "icd_id", nullable = false, referencedColumnName = "icd_id")
@Where(clause = "active_ind ='Y'")
private ICDMeasure icdMeasure;
@Column(name = "start_date", nullable = false)
@JsonSerialize(using = JsonDateSerializer.class)
@JsonDeserialize(using = JsonDateDeserializer.class)
private Date startDate;
@Column(name = "resolved_date", nullable = true)
@JsonSerialize(using = JsonDateSerializer.class)
@JsonDeserialize(using = JsonDateDeserializer.class)
private Date resolvedDate;
@Column(name = "file_id")
private Integer fileId;
/**
*
*/
public MembershipProblem() {
super();
}
/**
* @param id
*/
public MembershipProblem(final Integer id) {
super();
this.id = id;
}
/**
* @return
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(final Integer id) {
this.id = id;
}
/**
* @return the mbr
*/
public Membership getMbr() {
return mbr;
}
/**
* @param mbr
* the mbr to set
*/
public void setMbr(Membership mbr) {
this.mbr = mbr;
}
/**
* @return the icdMeasure
*/
public ICDMeasure getIcdMeasure() {
return icdMeasure;
}
/**
* @param icdMeasure the icdMeasure to set
*/
public void setIcdMeasure(ICDMeasure icdMeasure) {
this.icdMeasure = icdMeasure;
}
/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* @param startDate
* the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* @return the resolvedDate
*/
public Date getResolvedDate() {
return resolvedDate;
}
/**
* @param resolvedDate
* the resolvedDate to set
*/
public void setResolvedDate(Date resolvedDate) {
this.resolvedDate = resolvedDate;
}
/**
* @return the fileId
*/
public Integer getFileId() {
return fileId;
}
/**
* @param fileId
* the fileId to set
*/
public void setFileId(Integer fileId) {
this.fileId = fileId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof MembershipProblem)) {
return false;
}
MembershipProblem other = (MembershipProblem) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.pfchoice.springboot.model.MembershipProblem[ id=" + id + " ]";
}
}
|
package com.service;
import com.domain.model.FundModel;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author anthony_xu
* @version $$Id: bkpartner-parent, v 0.1 2018/05/15 13:20 anthony_xu Exp $$
*/
@Service
public class FundServiceImpl implements FundService {
@Override
public List<FundModel> queryFundModelList() {
return Lists.newArrayList(new FundModel());
}
}
|
package com.ak;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertRecord {
public static void main(String[] args) {
try {
String connectionString = "jdbc:sqlite:\\F:\\Learning stuff\\TestDB\\entertainment.db";
Connection connection = DriverManager.getConnection(connectionString);
Statement statement = connection.createStatement();
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Barfi', 'Ranbir Kapoor', 'Priyanka Chopra', 'Anurag Basu', 2012)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('PK', 'Aamir Khan', 'Anushka Sharma', 'Rajkumar Hirani', 2014)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Bajrangi Bhaijaan', 'Salman Khan', 'Harshaali Malhotra', 'Kabir Khan', 2015)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Jab We Met', 'Shahid Kapoor', 'Kareena Kapoor', 'Imtiaz Ali', 2007)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Baby', 'Akshay Kumar', 'Taapsee Pannu', 'Neeraj Pandey', 2015)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Airlift', 'Akshay Kumar', 'Nimrat Kaur', 'Raja Menon', 2016)");
statement.execute("INSERT INTO Movies (movie_name, actor, actress, director, yearOfRelease) VALUES ('Sanju', 'Ranbir Kapoor', 'Manisha Koirala', 'Rajkumar Hirani', 2018)");
statement.close();
connection.close();
}catch(SQLException e){
System.out.println("something went wrong: "+e.getMessage());
}
}
}
|
import java.util.Scanner;
public class StupidPassGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = Integer.parseInt(scanner.nextLine());
int n2 = Integer.parseInt(scanner.nextLine());
for (int i = 1; i <= n1; i++) {
for (int j = 1; j <= n1; j++) {
for (char k = 'a'; k < 'a' + n2; k++) {
for (char m = 'a'; m < 'a' + n2; m++) {
for (int o = 1; o <= n1; o++)
if (o > i && o > j) {
System.out.printf("" + i + j + k + m + o+" ");
}
}
}
}
}
}
}
|
package com.nbc.controller;
import com.nbc.utils.DateUtils;
import com.nbc.utils.NumberUtils;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Date;
public abstract class AbstractController<T> {
protected static final Logger logger = Logger.getLogger(AbstractController.class);
/**
* @param request
* @param name
* @return
*/
public String getString(HttpServletRequest request, String name) {
return request.getParameter(name);
}
public ObjectId getObjectId(HttpServletRequest request, String name) {
return new ObjectId(getString(request, name));
}
/**
* @param request
* @param name
* @return
*/
public Integer getInt(HttpServletRequest request, String name) {
String text = request.getParameter(name);
if (StringUtils.hasLength(text)) {
try {
return Integer.valueOf(text);
} catch (NumberFormatException ex) {
}
}
return null;
}
/**
* @param request
* @param name
* @param defaultValue
* @return
*/
public int getInt(HttpServletRequest request, String name, int defaultValue) {
String text = request.getParameter(name);
if (StringUtils.hasLength(text)) {
try {
return Integer.valueOf(text);
} catch (NumberFormatException ex) {
}
}
return defaultValue;
}
/**
* @param request
* @param name
* @param defaultValue
* @return
*/
public long getLong(HttpServletRequest request, String name, long defaultValue) {
String text = request.getParameter(name);
if (StringUtils.hasLength(text)) {
try {
return Integer.valueOf(text);
} catch (NumberFormatException ex) {
}
}
return defaultValue;
}
/**
* @param request
* @param name
* @param defaultValue
* @return
*/
public boolean getBoolean(HttpServletRequest request, String name, boolean defaultValue) {
String value = request.getParameter(name);
if (StringUtils.hasLength(value)) {
try {
return Boolean.valueOf(value);
} catch (Exception ex) {
}
}
return defaultValue;
}
/**
* @param request
* @param name
* @param defaultValue
* @return
*/
public float getFloat(HttpServletRequest request, String name, float defaultValue) {
String text = request.getParameter(name);
if (StringUtils.hasLength(text)) {
try {
return Float.valueOf(text);
} catch (NumberFormatException ex) {
}
}
return defaultValue;
}
/**
* @param request
* @param name
* @return
*/
public Date getDate(HttpServletRequest request, String name) {
return getDate(request, name, DateUtils.VIETNAM_DATE_PATTERN);
}
/**
* @param request
* @param name
* @param pattern
* @return
*/
public Date getDate(HttpServletRequest request, String name, String pattern) {
String text = request.getParameter(name);
if (StringUtils.hasLength(text)) {
return DateUtils.getDate(text, pattern);
}
return null;
}
@SuppressWarnings("unchecked")
protected T getModel(HttpServletRequest request, Class<T> model) {
try {
Class<?> clazzName = Class.forName(model.getSimpleName());
Object instance = clazzName.newInstance();
Class<?> clazz = instance.getClass();
Field[] fields = model.getDeclaredFields();
for (Field item : fields) {
while (clazz != null) {
try {
String fieldName = item.getName();
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(instance, getValue(request, fieldName));
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
return (T) instance;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
private Object getValue(HttpServletRequest request, String name) {
String tmpValue = getString(request, name);
if (name.equals("id"))
return getObjectId(request, name);
else if (NumberUtils.isInteger(tmpValue))
return getInt(request, name);
else if (NumberUtils.isLong(tmpValue))
return getLong(request, name, 0L);
else if (NumberUtils.isFloat(tmpValue))
return getFloat(request, name, 0F);
else if (NumberUtils.isBoolean(tmpValue))
return getBoolean(request, name, false);
return null;
}
}
|
package com.sharpower.action;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;
import org.apache.struts2.json.JSONUtil;
import com.opensymphony.xwork2.ActionSupport;
public class Text2AudioAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private InputStream inputStream;
private int contentLength;
private String contentDisposition;
private String text;
public InputStream getInputStream() {
return inputStream;
}
public int getContentLength() {
return contentLength;
}
public String getContentDisposition() {
return contentDisposition;
}
public void setText(String text) {
this.text = text;
}
public String textToAudio(){
try {
URL url = new URL("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=dcFP41BoCqemHDhIy00zcPX1Pgu7MKUV&client_secret=j7pytnwQP5aAeOtlLUU1WI651xfUPp8L");
URLConnection urlConnection = url.openConnection(); // 打开连接
BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream(),"utf-8")); // 获取输入流
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
Map<String, Object> dataMap = (Map<String, Object>) JSONUtil.deserialize(sb.toString());
String tok = (String) dataMap.get("access_token");
URL url1 = new URL("http://tsn.baidu.com/text2audio?tex=" + text + "&ctp=1&cuid=54EE7593B904&lan=zh&tok=" + tok);
URLConnection urlConnection1 = url1.openConnection();
inputStream = urlConnection1.getInputStream();
contentLength = inputStream.available();
contentDisposition = "inline;filename=\"Donwload_" + new Date() + ".mp3\"";
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
}
|
package test;
import static org.junit.Assert.*;
import java.awt.event.ActionEvent;
import java.util.List;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import model.Cuidador;
import org.junit.Test;
import dao.CuidadorDao;
import dao.CuidadorDaoImp;
public class CuidadorTest {
private Cuidador cuidador;
private DataModel listaCuidadores;
@Test
public DataModel getListarCuidadores() {
List<Cuidador> lista = new CuidadorDaoImp().list();
listaCuidadores = new ListDataModel(lista);
return listaCuidadores;
}
@Test
public Cuidador getCuidador() {
return this.cuidador;
}
@Test
public void prepararAdcionarCuidador(ActionEvent actionEvent) {
cuidador = new Cuidador();
}
@Test
public void prepararAlterarCuidador(ActionEvent actionEvent) {
cuidador = (Cuidador) (listaCuidadores.getRowData());
}
@Test
public String excluirCuidador() {
Cuidador cuidadorTemp = (Cuidador) (listaCuidadores.getRowData());
CuidadorDao dao = new CuidadorDaoImp();
dao.remove(cuidadorTemp);
return "index";
}
@Test
public void adicionarCuidador(ActionEvent actionEvent) {
CuidadorDao dao = new CuidadorDaoImp();
dao.save(cuidador);
}
@Test
public void alterarCuidador(ActionEvent actionEvent) {
CuidadorDao dao = new CuidadorDaoImp();
dao.update(cuidador);
}
}
|
package Test;
import GUI.Frame;
import Sound.SoundEnvironments;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class GUITest {
Frame gui = new Frame();
@Test
public void testStartButtonCreation() {
assertEquals(gui.getStart_sound().getText(), "Start");
}
@Test
public void testStopButtonCreation() {
assertEquals(gui.getStop_sound().getText(), "Stop");
}
@Test
public void testComboBoxCreation() {
SoundEnvironments.loadEnvironment("Beach");
gui.populateComboBox();
assertEquals(gui.getEnvironmentSelector().getSelectedItem(), "Beach");
}
}
|
/*処理ルール
入力されたモールス符号列を復号し、その単語を文字列として標準出力に出力してください。
使用されるモールス符号はA-Zのアルファベットのみ
復号した単語は必ず一般的な英単語(基本形)となるので、それをヒントに復号時に枝刈りを行ってください。
英単語はdictionary.txtに含まれるものになります。
ただし、dictionary.txtにある単語をすべてモールス符号化して、入力と比較するような実装は評価しません。必ず入力を復元しながら枝刈りするようにしてください。
仕様に反する入力を受け取った場合、終了コード1でプログラムを終了してください。
*/
/*
出力ルール
出力する単語はすべて小文字
複数の候補が得られた場合には、そのうちひとつを出力してください。
*/
import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class App2 {
private static Map morseMap;
public static void main(String[] args) {
inputCheck(args);
morseMapInitialize();
recursiveDecode(args[0],0);
}
private static void recursiveDecode(String input,int num){
if(isWord(input)){
System.out.println(input);
java.lang.System.exit(0);
}
if(num == input.length())return;
for(int i = num; i < input.length(); i++){
recursiveDecode(input.substring(0,num)+morseMap.get(input.substring(num,i+1))+input.substring(i+1),num+1);
}
}
private static boolean isWord(String input){
try{
File file = new File("dictionary.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String word = "";
while((word = br.readLine()) != null){
if(word.equals(input)){
return true;
}
}
br.close();
}catch(FileNotFoundException e){
System.out.println(e);
}catch(IOException e){
System.out.println(e);
}
return false;
}
private static void inputCheck(String[] input) {
if(input.length != 1)
java.lang.System.exit(1);
if(input[0].matches("^[^\\.|\\-]+$"))
java.lang.System.exit(1);
}
private static void morseMapInitialize(){
morseMap = new HashMap<String,String>();
morseMap.put(".-","a");
morseMap.put("-...","b");
morseMap.put("-.-.","c");
morseMap.put("-..","d");
morseMap.put(".","e");
morseMap.put("..-.","f");
morseMap.put("--.","g");
morseMap.put("....","h");
morseMap.put("..","i");
morseMap.put(".---","j");
morseMap.put("-.-","k");
morseMap.put(".--..","l");
morseMap.put("--","m");
morseMap.put("-.","n");
morseMap.put("---","o");
morseMap.put(".--.","p");
morseMap.put("--.-","q");
morseMap.put(".-.","r");
morseMap.put("...","s");
morseMap.put("-","t");
morseMap.put("..-","u");
morseMap.put("...-","v");
morseMap.put(".--","w");
morseMap.put("-..-","x");
morseMap.put("-.--","y");
morseMap.put("--..","z");
}
}
|
package com.spring.boot.rocks;
import java.util.Arrays;
import java.util.Collections;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.format.FormatterRegistry;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import com.spring.boot.rocks.RoleToUserProfileConverter;
@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = "com.spring.boot.rocks")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
DataSource dataSource;
@Autowired
RoleToUserProfileConverter roleToUserProfileConverter;
@Autowired
@Qualifier("persistentTokenRepository")
private PersistentTokenRepository persistentTokenRepository;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests()
.antMatchers("/webjars/**", "/resources/**", "/resources/css/**", "/fragments/**", "/registration",
"/login","/userreport", "/export-user-**")
.permitAll().antMatchers("/delete-user-**").access("hasAuthority('ADMIN')").antMatchers("/edit-user-**")
.access("hasAuthority('ADMIN') or hasAuthority('EDITOR')").antMatchers("/view-user-**").permitAll()
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll().and().rememberMe().rememberMeParameter("remember-me")
.tokenRepository(persistentTokenRepository).userDetailsService(userDetailsService).and().csrf()
.disable().exceptionHandling().accessDeniedPage("/Access_Denied");
}
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(roleToUserProfileConverter);
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
// @Bean
// public SimpleUrlHandlerMapping faviconHandlerMapping() {
// SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
// mapping.setOrder(Integer.MIN_VALUE);
// mapping.setUrlMap(Collections.singletonMap("favicon.ico", faviconRequestHandler()));
// return mapping;
// }
// @Bean
// protected ResourceHttpRequestHandler faviconRequestHandler() {
// ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
// requestHandler.setLocations(Arrays.<Resource>asList(new ClassPathResource("/")));
// return requestHandler;
// }
@Bean
public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
return tokenRepository;
}
}
|
public interface NumberFormatter {
String format(int input);
}
|
package com.qq.wx.voice.embed.recognizer;
public final class b {
public e bgl = new e();
}
|
package com.jasoftsolutions.mikhuna.model;
import com.google.gson.annotations.SerializedName;
/**
* Created by Hugo on 21/01/2015.
*/
public class Link extends AbstractModel {
private String link;
@SerializedName("type_link")
private Integer typeLink;
private Long restaurantServerId;
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Integer getTypeLink() {
return typeLink;
}
public void setTypeLink(Integer typeLink) {
this.typeLink = typeLink;
}
public Long getRestaurantServerId() {
return restaurantServerId;
}
public void setRestaurantServerId(Long restaurantServerId) {
this.restaurantServerId = restaurantServerId;
}
}
|
package com.ayantsoft.test.dao.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ayantsoft.test.dao.EmployeeDao;
import com.ayantsoft.test.pojo.Employee;
public class EmployeeDaoTest {
private EmployeeDao empdao;
//prepare for the test
@Before
public void setup() {
empdao = new EmployeeDao();
}
@Test
public void saveTest() {
//we are calling Employee class by creating an object emp1 and set variable data through object emp1
Employee emp1 = new Employee();
emp1.setAge(56);
emp1.setEmail("someone@gmail.com");
emp1.setName("harry");
emp1.setSalary(1000.00);
empdao.save(emp1);
// we are getting same value through empdao and store value in emp2
Employee emp2 = empdao.findByEmial("someone@gmail.com");
assertNotNull("Employee object is not null",emp2);
assertEquals("Salary is not equal",emp1.getSalary(),emp2.getSalary(),1.00);
assertEquals("Age is not equal",emp1.getAge(),emp2.getAge());
assertEquals("Name is not equal",emp1.getName(),emp2.getName());
assertEquals("Email is not equal",emp1.getEmail(),emp2.getEmail());
}
@Test
public void updateTest(Employee e) {
Employee a = empdao.findByEmial("someone@email.com");
a.setAge(56);
empdao.update(a);
Employee b = empdao.findByEmial("someone@email.com");
assertEquals("Age is not equals",56,b.getAge());
}
@Test
public void findByEmialTest() {
Employee abc = empdao.findByEmial("someone@gmail.com");
//if employee is null test fails
assertNotNull("employee is null",abc);
}
@Test
public void findAllTest() {
List<Employee> employees = empdao.findAll();
assertNotNull("emploee is null",employees);
assertEquals("List is empty",false,employees.isEmpty());
}
@Test
public void deleteTest() {
empdao.delete("someone@gmail.com");
Employee abc = empdao.findByEmial("someone@gmail.com");
assertNull("employee is null",abc);
}
//anything you want to deallocate or close the resources
@After
public void close() {
empdao = null;
}
}
|
package com.duanxr.yith.easy;
import java.util.HashMap;
import java.util.Map;
/**
* @author 段然 2021/3/8
*/
public class DegreeOfAnArray {
/**
* Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.
*
* Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.
*
*
*
* Example 1:
*
* Input: nums = [1,2,2,3,1]
* Output: 2
* Explanation:
* The input array has a degree of 2 because both elements 1 and 2 appear twice.
* Of the subarrays that have the same degree:
* [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
* The shortest length is 2. So return 2.
* Example 2:
*
* Input: nums = [1,2,2,3,1,4,2]
* Output: 6
* Explanation:
* The degree is 3 because the element 2 is repeated 3 times.
* So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
*
*
* Constraints:
*
* nums.length will be between 1 and 50,000.
* nums[i] will be an integer between 0 and 49,999.
*
* 给定一个非空且只包含非负数的整数数组 nums,数组的度的定义是指数组里任一元素出现频数的最大值。
*
* 你的任务是在 nums 中找到与 nums 拥有相同大小的度的最短连续子数组,返回其长度。
*
*
*
* 示例 1:
*
* 输入:[1, 2, 2, 3, 1]
* 输出:2
* 解释:
* 输入数组的度是2,因为元素1和2的出现频数最大,均为2.
* 连续子数组里面拥有相同度的有如下所示:
* [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
* 最短连续子数组[2, 2]的长度为2,所以返回2.
* 示例 2:
*
* 输入:[1,2,2,3,1,4,2]
* 输出:6
*
*
* 提示:
*
* nums.length 在1到 50,000 区间范围内。
* nums[i] 是一个在 0 到 49,999 范围内的整数。
*
*/
class Solution {
private class ArrayHelper {
public int left;
public int right;
public int count;
public int n;
}
public int findShortestSubArray(int[] nums) {
Map<Integer, ArrayHelper> count = new HashMap<>();
int max = 0;
for (int i = 0; i < nums.length; i++) {
int n = nums[i];
if (!count.containsKey(n)) {
ArrayHelper arrayHelper = new ArrayHelper();
arrayHelper.left = i;
arrayHelper.right = i;
arrayHelper.count = 1;
arrayHelper.n = n;
count.put(n, arrayHelper);
max = Math.max(max, 1);
} else {
ArrayHelper arrayHelper = count.get(n);
arrayHelper.count = arrayHelper.count + 1;
arrayHelper.right = i;
max = Math.max(max, arrayHelper.count);
}
}
int r = Integer.MAX_VALUE;
for (java.util.Map.Entry<Integer, ArrayHelper> entry : count.entrySet()) {
ArrayHelper arrayHelper = entry.getValue();
if (arrayHelper.count == max) {
int n = entry.getKey();
r = Math.min(arrayHelper.right - arrayHelper.left + 1, r);
}
}
return r;
}
}
}
|
package com.example.zealience.oneiromancy.mvp.presenter;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.steven.base.bean.UserInfo;
import com.example.zealience.oneiromancy.mvp.contract.LoginContract;
import com.steven.base.util.UserHelper;
import com.steven.base.util.ToastUitl;
import com.steven.base.widget.LoadingDialog;
/**
* @user steven
* @createDate 2019/3/6 10:34
* @description 自定义
*/
public class LoginPresenter extends LoginContract.Presenter {
private boolean isPhoneCorrect = false;
private boolean isPasswrodCorrect = false;
private LoadingDialog loadingDialog;
private Handler mHandler;
@Override
public void doLogin(String phone, String password) {
if (!"520".equals(phone)) {
ToastUitl.showShort("账号不正确");
return;
}
if (!"1314".equals(password)) {
ToastUitl.showShort("密码不正确");
return;
}
loadingDialog = new LoadingDialog();
loadingDialog.showDialogForLoading(mContext, "登录中...", false);
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
loadingDialog.cancelDialogForLoading();
UserInfo userInfo = new UserInfo();
userInfo.setPhone(phone);
UserHelper.saveUserInfo(mContext, userInfo);
mView.loginSuccess();
}
}, 1000);
}
@Override
public void observerInput(EditText phone, EditText password) {
phone.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() >= 3) {
isPhoneCorrect = true;
} else {
isPhoneCorrect = false;
}
updateView();
}
@Override
public void afterTextChanged(Editable s) {
}
});
password.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() >= 4) {
isPasswrodCorrect = true;
} else {
isPasswrodCorrect = false;
}
updateView();
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
private void updateView() {
if (isPhoneCorrect && isPasswrodCorrect) {
mView.inputSuccess(true);
} else {
mView.inputSuccess(false);
}
}
}
|
package mobi.wrt.oreader.app.test.feedly;
import mobi.wrt.oreader.app.clients.db.ClientEntity;
import mobi.wrt.oreader.app.clients.feedly.db.Subscriptions;
import mobi.wrt.oreader.app.clients.feedly.processor.SubscriptionsProcessor;
import mobi.wrt.oreader.app.test.common.AbstractTestProcessor;
/**
* Created by Uladzimir_Klyshevich on 4/23/2014.
*/
public class SubscriptionsProcessorTest extends AbstractTestProcessor {
public void testCategoryFeeds() throws Exception {
clear(Subscriptions.class);
clear(ClientEntity.class);
testExecute(SubscriptionsProcessor.APP_SERVICE_KEY, "feedly/subscriptions.json");
checkCount(Subscriptions.class, 5);
checkCount(ClientEntity.class, 5);
checkRequiredFields(Subscriptions.class,
Subscriptions.ID,
Subscriptions.ID_AS_STRING,
Subscriptions.TITLE,
Subscriptions.WEBSITE,
Subscriptions.CATEGORIES_JOINED,
Subscriptions.UPDATED,
Subscriptions.POSITION);
testExecute(SubscriptionsProcessor.APP_SERVICE_KEY, "feedly/subscriptions_updated.json");
checkCount(Subscriptions.class, 4);
checkCount(ClientEntity.class, 4);
checkRequiredFields(Subscriptions.class,
Subscriptions.ID,
Subscriptions.ID_AS_STRING,
Subscriptions.TITLE,
Subscriptions.WEBSITE,
//removed from one of item Subscriptions.CATEGORIES_JOINED,
Subscriptions.UPDATED,
Subscriptions.POSITION);
}
}
|
package edu.sit.erro.propriedades;
public class PropriedadesException extends Exception{
private static final long serialVersionUID = 1L;
public PropriedadesException(EErroPropriedade erro) {
super(erro.getMensage());
}
}
|
package com.wzy.class1;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
/**
* @author wzy
* @title: IndexDao
* @description: TODO
* @date 2019/7/10 10:43
*/
@Repository
public class IndexDao implements ApplicationContextAware {
private ApplicationContext applicationContext;
public IndexDao() {
System.out.println("indexDao construct");
}
@PostConstruct
public void init() {
System.out.println("indexDao init");
}
public void test() {
System.out.println("test");
applicationContext.getApplicationName();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
|
package agh.queueFreeShop.physical.weight;
import org.springframework.stereotype.Component;
/**
* Dummy entrance weight.
*/
@Component
public class EntranceWeight extends Weight {
}
|
package com.example.wanderlust;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.wanderlust.DatabaseHelper.DbInstance;
import com.example.wanderlust.Doa.BlogObject;
import java.util.ArrayList;
public class BlogView extends AppCompatActivity {
final DbInstance dbHelper = new DbInstance(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_view);
ActionBar actionBar = this.getSupportActionBar();
actionBar.hide();
// getSupportActionBar().setDisplayShowCustomEnabled(true);
// getSupportActionBar().setCustomView(R.layout.custom_action_bar);
//
//BlogObject bo = dbHelper.getOneBlogData(1);
ArrayList<byte[]> pics = new ArrayList<>();
BlogObject bo = new BlogObject("123","1", "Magnificent India","India","This is India, with an average population of 2 billion",pics,20.770773,73.7217954,5,"Should Visit");
//
// final TextView tv = (TextView) findViewById(R.id.textView2);
// if(bo == null){
// tv.setText("No Object");
// }else{
// tv.setText("Object Found" + bo.getBlogTitle());
// }
}
}
|
package com.mod.user_service.service;
import com.mod.user_service.document.Admin;
import com.mod.user_service.document.Trainer;
import com.mod.user_service.document.User;
import com.mod.user_service.document.auth.Login;
import com.mod.user_service.document.payload.request.AuthEvent;
import com.mod.user_service.repository.auth.LoginRepository;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class AuthService {
private final LoginRepository loginRepository;
private final UserService userService;
private final TrainerService trainerService;
private final AdminService adminService;
public AuthService(LoginRepository loginRepository, UserService userService, TrainerService trainerService, AdminService adminService) {
this.loginRepository = loginRepository;
this.userService = userService;
this.trainerService = trainerService;
this.adminService = adminService;
}
@StreamListener(target = "ModAuth")
public void authConsumer(AuthEvent event) {
switch (event.getEventType()) {
case "LOGIN":
login(event.getToken(), event.getUsername());
break;
case "SIGNUP":
signup(event.getUser());
break;
case "LOGOUT":
logout(event.getToken(), event.getUsername());
break;
case "LOGOUT_ALL":
logoutAll(event.getUsername());
break;
case "DELETE":
delete(event.getUsername());
break;
case "PATCH":
case "CHANGE_PWD":
patch(event.getUser());
default:
break;
}
}
private void patch(Login user) {
Login found = loginRepository.findByUsername(user.getUsername()).orElse(null);
if (found != null)
found = loginRepository.save(user);
if (found != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("ADMIN")))
adminService.put(new Admin(user.getId(), user.getUsername(), user.getEmail(), user.getMobileNumber(), null, null));
else if (found != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("TRAINER")))
trainerService.put(new Trainer(found.getId(), found.getUsername(), null, found.getEmail(), null, null, null, null, found.getMobileNumber()));
else if (found != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("USER")))
userService.put(new User(user.getUsername(), user.getEmail(), user.getMobileNumber(), null));
}
private void delete(String username) {
Login user = loginRepository.findByUsername(username).orElse(null);
if (user != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("ADMIN")))
adminService.delete(username);
else if (user != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("TRAINER")))
trainerService.delete(username);
else if (user != null && user.getRoles().stream().anyMatch(role -> role.getRole().equals("USER")))
userService.delete(username);
if (user != null)
loginRepository.delete(user);
}
private void logout(String jwt, String username) {
Login user = loginRepository.findByUsername(username).orElse(null);
if (user != null) {
List<String> activeTokens = user.getActiveTokens();
activeTokens = activeTokens.stream().filter(token -> {
boolean isTokePresent = token.equals(jwt);
return !(isTokePresent);
}).collect(Collectors.toList());
user.setActiveTokens(activeTokens);
loginRepository.save(user);
}
}
private void login(String jwt, String username) {
Login user = loginRepository.findByUsername(username).orElse(null);
List<String> tokens = user != null && user.getActiveTokens() != null ? user.getActiveTokens() : new ArrayList<>();
tokens.add(jwt);
if (user != null) {
user.setActiveTokens(tokens);
loginRepository.save(user);
}
}
private void logoutAll(String username) {
Login user = loginRepository.findByUsername(username).orElse(null);
if (user != null) {
user.setActiveTokens(new ArrayList<>());
loginRepository.save(user);
}
}
private void signup(Login user) {
if (!loginRepository.existsByUsername(user.getUsername())) {
loginRepository.save(user);
if (user.getRoles().stream().anyMatch(role -> role.getRole().equals("ADMIN")))
adminService.post(new Admin(user.getId(), user.getUsername(), user.getEmail(), user.getMobileNumber(), null, null));
else if (user.getRoles().stream().anyMatch(role -> role.getRole().equals("TRAINER")))
trainerService.post(new Trainer(user.getId(), user.getUsername(), null, user.getEmail(), null, null, null, null, user.getMobileNumber()));
else if (user.getRoles().stream().anyMatch(role -> role.getRole().equals("USER")))
userService.post(new User(user.getId(), user.getUsername(), user.getEmail(), user.getMobileNumber(), null));
}
}
}
|
package com.onplan.util;
import com.google.common.base.Strings;
import static com.onplan.util.MorePreconditions.checkNotNullOrEmpty;
public final class StringUtils {
/**
* When the text exceeds the maxLength returns the text trimmed with the trimmedSuffix, otherwise
* returns the full text. The resulting string always contains up to maxLength characters.
*
* @param text The text string.
* @param maxLength The maximum length of the resulting string.
* @param trimmedSuffix The trimmed suffix.
*/
public static String trimText(String text, int maxLength, String trimmedSuffix) {
checkNotNullOrEmpty(trimmedSuffix);
if (Strings.isNullOrEmpty(text)) {
return text;
} else if (text.length() > maxLength) {
text = text.substring(maxLength - trimmedSuffix.length());
text += trimmedSuffix;
}
return text;
}
}
|
package me.luliru.gateway.core.repository.entity;
import java.io.Serializable;
import java.util.Date;
/**
* ApplicationQa
* Created by luliru on 2019/7/8.
*/
public class ApplicationQa implements Serializable {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private Long id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.devep_id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private Long devepId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.app_name
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private String appName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.app_key
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private String appKey;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.app_secret
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private String appSecret;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.callback_url
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private String callbackUrl;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.callback_format
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private Byte callbackFormat;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.ins_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private Date insTm;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column application_qa.upd_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private Date updTm;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table application_qa
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.id
*
* @return the value of application_qa.id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.id
*
* @param id the value for application_qa.id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.devep_id
*
* @return the value of application_qa.devep_id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public Long getDevepId() {
return devepId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.devep_id
*
* @param devepId the value for application_qa.devep_id
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setDevepId(Long devepId) {
this.devepId = devepId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.app_name
*
* @return the value of application_qa.app_name
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public String getAppName() {
return appName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.app_name
*
* @param appName the value for application_qa.app_name
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setAppName(String appName) {
this.appName = appName == null ? null : appName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.app_key
*
* @return the value of application_qa.app_key
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public String getAppKey() {
return appKey;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.app_key
*
* @param appKey the value for application_qa.app_key
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setAppKey(String appKey) {
this.appKey = appKey == null ? null : appKey.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.app_secret
*
* @return the value of application_qa.app_secret
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public String getAppSecret() {
return appSecret;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.app_secret
*
* @param appSecret the value for application_qa.app_secret
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setAppSecret(String appSecret) {
this.appSecret = appSecret == null ? null : appSecret.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.callback_url
*
* @return the value of application_qa.callback_url
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public String getCallbackUrl() {
return callbackUrl;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.callback_url
*
* @param callbackUrl the value for application_qa.callback_url
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setCallbackUrl(String callbackUrl) {
this.callbackUrl = callbackUrl == null ? null : callbackUrl.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.callback_format
*
* @return the value of application_qa.callback_format
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public Byte getCallbackFormat() {
return callbackFormat;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.callback_format
*
* @param callbackFormat the value for application_qa.callback_format
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setCallbackFormat(Byte callbackFormat) {
this.callbackFormat = callbackFormat;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.ins_tm
*
* @return the value of application_qa.ins_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public Date getInsTm() {
return insTm;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.ins_tm
*
* @param insTm the value for application_qa.ins_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setInsTm(Date insTm) {
this.insTm = insTm;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column application_qa.upd_tm
*
* @return the value of application_qa.upd_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public Date getUpdTm() {
return updTm;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column application_qa.upd_tm
*
* @param updTm the value for application_qa.upd_tm
*
* @mbg.generated Mon Dec 17 16:59:07 CST 2018
*/
public void setUpdTm(Date updTm) {
this.updTm = updTm;
}
}
|
package com.issCollege.po;
import java.io.Serializable;
import java.util.Date;
/**
* sampleappoint
* @author
*/
public class Sampleappoint implements Serializable {
/**
* 样品下发单编号,自增主键
*/
private Long sampleappointId;
/**
* 报告编号,引用自样品表
*/
private Long reportnum;
/**
* 检验项目名称,引用自检测项目表
*/
private Long itemName;
/**
* 检验方法,引用自检测项目表
*/
private Long itemMethod;
/**
* 样品数量,引用自样品表
*/
private Long sampleCount;
/**
* 检测人员(员工姓名),引用员工表
*/
private Long staffName;
/**
* 工作量
*/
private String workload;
/**
* 完成日期
*/
private Date finishdate;
private static final long serialVersionUID = 1L;
public Long getSampleappointId() {
return sampleappointId;
}
public void setSampleappointId(Long sampleappointId) {
this.sampleappointId = sampleappointId;
}
public Long getReportnum() {
return reportnum;
}
public void setReportnum(Long reportnum) {
this.reportnum = reportnum;
}
public Long getItemName() {
return itemName;
}
public void setItemName(Long itemName) {
this.itemName = itemName;
}
public Long getItemMethod() {
return itemMethod;
}
public void setItemMethod(Long itemMethod) {
this.itemMethod = itemMethod;
}
public Long getSampleCount() {
return sampleCount;
}
public void setSampleCount(Long sampleCount) {
this.sampleCount = sampleCount;
}
public Long getStaffName() {
return staffName;
}
public void setStaffName(Long staffName) {
this.staffName = staffName;
}
public String getWorkload() {
return workload;
}
public void setWorkload(String workload) {
this.workload = workload;
}
public Date getFinishdate() {
return finishdate;
}
public void setFinishdate(Date finishdate) {
this.finishdate = finishdate;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.bag;
import android.os.Bundle;
import com.tencent.mm.sdk.platformtools.x;
import org.json.JSONException;
import org.json.JSONObject;
final class n$a extends JSONObject {
public n$a(Object obj) {
if (obj instanceof String) {
put("type", 1);
put("val", obj);
} else if (obj instanceof Integer) {
put("type", 2);
put("val", obj);
} else if (obj instanceof Long) {
put("type", 3);
put("val", obj);
} else if (obj instanceof Boolean) {
put("type", 4);
put("val", obj);
} else {
x.w("MicroMsg.WebViewBagIntentLogic", "put not support type;class:%s", new Object[]{obj.getClass()});
put("type", 0);
put("val", obj);
}
}
static void a(Bundle bundle, String str, JSONObject jSONObject) {
try {
x.i("MicroMsg.WebViewBagIntentLogic", "restoreToBundle key:%s type:%d", new Object[]{str, Integer.valueOf(jSONObject.getInt("type"))});
switch (jSONObject.getInt("type")) {
case 1:
bundle.putString(str, jSONObject.getString("val"));
return;
case 2:
bundle.putInt(str, jSONObject.getInt("val"));
return;
case 3:
bundle.putLong(str, jSONObject.getLong("val"));
return;
case 4:
bundle.putBoolean(str, jSONObject.getBoolean("val"));
return;
default:
x.w("MicroMsg.WebViewBagIntentLogic", "not support type");
return;
}
} catch (JSONException e) {
x.e("MicroMsg.WebViewBagIntentLogic", "restoreToBundle e:%s", new Object[]{e});
}
x.e("MicroMsg.WebViewBagIntentLogic", "restoreToBundle e:%s", new Object[]{e});
}
}
|
package com.markhetherington.thisishow.ui.controllers;
import com.markhetherington.thisishow.models.Project;
import java.util.ArrayList;
import java.util.List;
public class FeedController extends BaseViewController<FeedController.FeedControllerListener> {
@Override
protected void onListenerAdded() {
List<Project> projects = new ArrayList<>();
for (int i = 0; i < 100; i++) {
projects.add(ProjectController.createStubProject());
}
inform(listener -> listener.onProjectsUpdated(projects));
}
public interface FeedControllerListener {
void onProjectsUpdated(List<Project> projects);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.