text stringlengths 10 2.72M |
|---|
package com.yunwa.aggregationmall.service.tb;
/**
* Created on 2019/10/16.
*
* @author yueyang
*/
public interface TbSearchParaService {
}
|
package converters;
import javax.transaction.Transactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import repositories.FloatEntityRepository;
import domain.FloatEntity;
@Component
@Transactional
public class StringToFloatEntityConverter implements Converter<String, FloatEntity> {
@Autowired
FloatEntityRepository floatRepository;
@Override
public FloatEntity convert(final String text) {
FloatEntity result;
int id;
try {
if (StringUtils.isEmpty(text))
result = null;
else {
id = Integer.valueOf(text);
result = this.floatRepository.findOne(id);
}
} catch (final Throwable oops) {
throw new IllegalArgumentException(oops);
}
return result;
}
}
|
package com.company.warehouse;
public interface Warehouse {
public <T> void addSupplier(Supplier<T> supplier);
public <T> void addConsumer(Consumer<T> consumer);
public <T> void store(T widget);
public <T> T fetchNextWidget(Class<T> widgetClass);
public String toString();
}
|
package dao;
import entity.DepotOut_insert;
import entity.DepotOut_select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
@Repository
public class DepotOutDao {
@Autowired
JdbcTemplate jdbcTemplate;
//查询
public List select(String sql, DepotOut_select depotOutSelect) throws SQLException {
// DataSource ds = new ComboPooledDataSource();
// QueryRunner runner = new QueryRunner(ds);
// return runner.query(sql,new ArrayListHandler(),depotOutSelect.getId());
//System.out.println(depotOutSelect.toString());
return jdbcTemplate.queryForList(sql,depotOutSelect.getBdate(),depotOutSelect.getEdate(),depotOutSelect.getOut_no(),depotOutSelect.getVendor(),depotOutSelect.getStore(),depotOutSelect.getState(),depotOutSelect.getCreate());
}
public String insert(String sql, DepotOut_insert depotOutInsert) {
return String.valueOf(jdbcTemplate.update(sql,depotOutInsert.getOut_insert_no(),depotOutInsert.getInsert_date(),depotOutInsert.getStore(),depotOutInsert.getVendor(),depotOutInsert.getCreate_emp(),depotOutInsert.getMaker(),depotOutInsert.getState()));
}
public int delete(String sql, String id) {
return jdbcTemplate.update(sql,id);
// System.out.println(sql+id);
// return 0;
}
public int audit(String sql, String id, String user) {
//System.out.println(jdbcTemplate.update(sql,user,id));
return jdbcTemplate.update(sql,user,id);
// System.out.println(sql+id+user);
// return 0;
}
public int remove(String sql, String id) {
return jdbcTemplate.update(sql,id);
}
public List detail_select(String sql, String out_no) {
return jdbcTemplate.queryForList(sql,out_no);
// System.out.println(sql+out_no);
// return 0;
}
public int detail_insert(String sql, String out_no, String card_no) {
//System.out.println(sql+out_no+card_no);
return jdbcTemplate.update(sql,out_no,card_no);
}
public List detail_insert_select(String sql, String out_no, String card_no) {
return jdbcTemplate.queryForList(sql,out_no,card_no);
}
public int detail_delete(String sql, String id) {
return jdbcTemplate.update(sql,id);
}
}
|
package gromcode.main.lesson27.homework27_2;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
/*
UserRepository userRepository = new UserRepository();
userRepository.save(new User(1, "u1", "ses1"));
userRepository.save(new User(2, "u2", "ses2"));
userRepository.save(new User(3, "u3", "ses1"));
userRepository.save(new User(4, "u4", "ses2"));
System.out.println(Arrays.toString(userRepository.getUsers()));
userRepository.update(new User(2, "u22", "ses2"));
System.out.println(Arrays.toString(userRepository.getUsers()));
userRepository.delete(2);
System.out.println(Arrays.toString(userRepository.getUsers()));
*/
testGetMethod();
}
private static void testGetMethod(){
//arraylist
UserRepository userRepository = new UserRepository();
Date startAdd = new Date();
for(int i = 0; i < 20000; i++){
userRepository.save(new User(i, "user_"+i, "session_"+i));
}
Date finishAdd = new Date();
long addTime = finishAdd.getTime() - startAdd.getTime();
System.out.println("ArrayList add: "+addTime);
Date startGet = new Date();
userRepository.getUsers();
Date finishGet = new Date();
long getTime = finishGet.getTime() - startGet.getTime();
System.out.println("get - array list: "+ getTime);
//linkedlist
UserRepository2 userRepository2 = new UserRepository2();
Date startAdd2 = new Date();
for(int i = 0; i < 20000; i++){
userRepository2.save(new User(i, "user_"+i, "session_"+i));
}
Date finishAdd2 = new Date();
long addTime2 = finishAdd2.getTime() - startAdd2.getTime();
System.out.println("LinkedList add: "+addTime2);
Date startGet2 = new Date();
userRepository2.getUsers();
Date finishGet2 = new Date();
long getTime2 = finishGet2.getTime() - startGet2.getTime();
System.out.println("get - linked list: "+ getTime2);
}
} |
package com.example.coolcloudweather.gson;
import com.google.gson.annotations.SerializedName;
public class Hourly {
public Cond cond;
public class Cond{
public String code;
public String txt;
}
public String date;
public String tmp;
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.examples.resources.client.model;
public class MailItem {
private String sender;
private String email;
private String subject;
private String body;
public MailItem() {
}
public MailItem(String sender, String email, String subject) {
this();
setSender(sender);
setEmail(email);
setSubject(subject);
}
public MailItem(String sender, String email, String subject, String body) {
this(sender, email, subject);
this.body = body;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public String getBody() {
return body;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
}
|
package nl.esciencecenter.newsreader.hbase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DirectoryLoaderTest {
private DirectoryLoaderAction loader;
private HTable table;
@Before
public void setUp() {
Configuration config = mock(Configuration.class);
loader = new DirectoryLoaderAction(config);
table = mock(HTable.class);
loader.setTable(table);
}
@Test
public void testDefaultTableName() {
assertThat(loader.getTableName(), is("documents"));
}
@Test
public void testDefaultFamilyName() {
assertThat(loader.getFamilyName(), is("naf"));
}
@Test
public void testDefaultColumnName() {
assertThat(loader.getColumnName(), is("annotated"));
}
@Test
public void testDefaultRootDirectory() {
assertThat(loader.getRootDirectory(), is(nullValue()));
}
@Test
public void testRunNaf() throws Exception {
// TODO don't walk actual test directory
String rootDirectory = DirectoryLoaderTest.class.getClassLoader().getResource("naf-files").getPath();
loader.setRootDirectory(rootDirectory);
loader.run();
verify(table).put(Mockito.<Put>anyObject());
verify(table).close();
}
@Test
public void testRunNafBz2() throws Exception {
// TODO don't walk actual test directory
String rootDirectory = DirectoryLoaderTest.class.getClassLoader().getResource("naf-files-bz2").getPath();
loader.setRootDirectory(rootDirectory);
loader.run();
verify(table).put(Mockito.<Put>anyObject());
verify(table).close();
}
} |
package com.sinodynamic.hkgta.dao.crm;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.entity.crm.AgeRange;
@Repository
public class AgeRangeDaoImpl extends GenericDao<AgeRange> implements AgeRangeDao {
}
|
package User;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
/**
* Created by harduNel on 2015-01-20.
*/
@Entity
public class User {
//@GeneratedValue(strategy= GenerationType.AUTO)
//Long userid;
// @Column(name = "username", nullable = false)
@Id
private String username;
private String password;
@OneToMany(mappedBy = "u")
private List<UserGame> games = new ArrayList<>();
public void Gameadd(Game _game)
{
UserGame usergame = new UserGame();
usergame.setUsername(this.getUsername());
games.add(usergame);
}
// @Version
// @OneToMany(mappedBy="User",targetEntity=UserGame.class,
// fetch=FetchType.EAGER)
// private List<UserGame> games;
// @ManyToMany(mappedBy="users")
// private List<Game> games;
public User() {}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package kr.co.people_gram.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONException;
import org.json.JSONObject;
public class SettingActivity extends AppCompatActivity {
private TextView top_title;
private Intent intent;
private Switch push_switch, push_survey;
private ProgressDialog dialog;
private LinearLayout point_add, notice_btn, agree_btn, userinfo_btn, logout_btn, question_btn, people_btn, drop_btn;
private Boolean sync = false;
private TextView setting_version;
public static AppCompatActivity settingactivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
settingactivity = this;
top_title = (TextView) findViewById(R.id.top_title);
top_title.setText("설정");
setting_version = (TextView) findViewById(R.id.setting_version);
PackageInfo pi = null;
try {
pi = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String verSion = pi.versionName;
setting_version.setText("버전정보 : " + verSion);
push_switch = (Switch) findViewById(R.id.push_switch);
//push_survey = (Switch) findViewById(R.id.push_survey);
point_add = (LinearLayout) findViewById(R.id.point_add);
notice_btn = (LinearLayout) findViewById(R.id.notice_btn);
agree_btn = (LinearLayout) findViewById(R.id.agree_btn);
userinfo_btn = (LinearLayout) findViewById(R.id.userinfo_btn);
question_btn = (LinearLayout) findViewById(R.id.question_btn);
logout_btn = (LinearLayout) findViewById(R.id.logout_btn);
people_btn = (LinearLayout) findViewById(R.id.people_btn);
drop_btn = (LinearLayout) findViewById(R.id.drop_btn);
// point_add.setOnClickListener(onBtnClickListener);
//point_add.setOnTouchListener(onBtnTouchListener);
notice_btn.setOnTouchListener(onBtnTouchListener);
notice_btn.setOnClickListener(onBtnClickListener);
agree_btn.setOnTouchListener(onBtnTouchListener);
agree_btn.setOnClickListener(onBtnClickListener);
userinfo_btn.setOnTouchListener(onBtnTouchListener);
userinfo_btn.setOnClickListener(onBtnClickListener);
logout_btn.setOnTouchListener(onBtnTouchListener);
logout_btn.setOnClickListener(onBtnClickListener);
question_btn.setOnTouchListener(onBtnTouchListener);
question_btn.setOnClickListener(onBtnClickListener);
people_btn.setOnTouchListener(onBtnTouchListener);
people_btn.setOnClickListener(onBtnClickListener);
drop_btn.setOnTouchListener(onBtnTouchListener);
drop_btn.setOnClickListener(onBtnClickListener);
pushdata();
push_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String push_yn = "N";
if (isChecked == true) {
push_yn = "Y";
} else {
push_yn = "N";
}
RequestParams params = new RequestParams();
params.put("uid", SharedPreferenceUtil.getSharedPreference(SettingActivity.this, "uid"));
params.put("push_yn", push_yn);
HttpClient.post("/user/pushSetting", params, new AsyncHttpResponseHandler() {
public void onStart() {
//dialog = ProgressDialog.show(SettingActivity.this, "", "데이터 수신중");
}
public void onFinish() {
//dialog.dismiss();
}
@Override
public void onSuccess(String response) {
if (response.equals("000") == false) {
Toast.makeText(SettingActivity.this, "다시 시도해주세요.", Toast.LENGTH_LONG).show();
}
}
});
}
});
/*
push_survey.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String panel_push_yn = "N";
if (isChecked == true) {
panel_push_yn = "Y";
} else {
panel_push_yn = "N";
}
RequestParams params = new RequestParams();
params.put("uid", SharedPreferenceUtil.getSharedPreference(SettingActivity.this, "uid"));
params.put("panel_push_yn", panel_push_yn);
HttpClient.post("/user/surveyPushSetting", params, new AsyncHttpResponseHandler() {
public void onStart() {
}
public void onFinish() {
}
@Override
public void onSuccess(String response) {
if (response.equals("000") == false) {
Toast.makeText(SettingActivity.this, "다시 시도해주세요.", Toast.LENGTH_LONG).show();
}
}
});
}
});*/
}
private void pushdata() {
RequestParams params = new RequestParams();
params.put("uid", SharedPreferenceUtil.getSharedPreference(SettingActivity.this, "uid"));
HttpClient.post("/user/pushSelect", params, new AsyncHttpResponseHandler() {
public void onStart() {
dialog = ProgressDialog.show(SettingActivity.this, "", "데이터 수신중");
}
public void onFinish() {
dialog.dismiss();
}
public void onSuccess(String response) {
try {
JSONObject jobj = new JSONObject(response);
if(jobj.getString("PUSH_YN").equals("Y")) {
push_switch.setChecked(true);
} else {
push_switch.setChecked(false);
}
/*
if(jobj.getString("SURVEY_PUSH_YN").equals("Y")) {
push_survey.setChecked(true);
} else {
push_survey.setChecked(false);
}
*/
} catch (JSONException e) {
e.printStackTrace();
}
/*
if(response.equals("Y")) {
push_switch.setChecked(true);
} else {
push_switch.setChecked(false);
}
*/
}
});
}
private View.OnTouchListener onBtnTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()) {
case R.id.notice_btn:
if(event.getAction() == 2) {
notice_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
notice_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.agree_btn:
if(event.getAction() == 2) {
agree_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
agree_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.userinfo_btn:
if(event.getAction() == 2) {
userinfo_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
userinfo_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.logout_btn:
if(event.getAction() == 2) {
logout_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
logout_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.question_btn:
if(event.getAction() == 2) {
question_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
question_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.people_btn:
if(event.getAction() == 2) {
people_btn.setBackgroundColor(Color.rgb(241, 241, 241));
} else {
people_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
case R.id.drop_btn:
if(event.getAction() == 2) {
drop_btn.setBackgroundColor(Color.rgb(241,241,241));
} else {
drop_btn.setBackgroundColor(Color.rgb(255,255,255));
}
break;
}
return false;
}
};
private View.OnClickListener onBtnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
/*case R.id.point_add:
intent = new Intent(SettingActivity.this, SubGramPoint.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
*/
case R.id.notice_btn:
intent = new Intent(SettingActivity.this, NoticeActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.agree_btn:
intent = new Intent(SettingActivity.this, Setting_UserAgreeActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.userinfo_btn:
intent = new Intent(SettingActivity.this, Setting_UserInfoActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.logout_btn:
AlertDialog.Builder alert = new AlertDialog.Builder(SettingActivity.this);
alert.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "uid", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "username", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "point", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "mytype", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "my_speed", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "my_control", "");
SharedPreferenceUtil.putSharedPreference(SettingActivity.this, "email", "");
finish();
MainActivity2.mainActivity.finish();
Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
startActivity(intent);
}
});
alert.setMessage("로그아웃 하시겠습니까?");
alert.setNegativeButton("취소", null);
alert.show();
break;
case R.id.question_btn:
intent = new Intent(SettingActivity.this, SubQnaActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.people_btn:
intent = new Intent(SettingActivity.this, SubMyPagePeopleSync_Activity.class);
startActivityForResult(intent, 61);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
case R.id.drop_btn:
intent = new Intent(SettingActivity.this, SubMyDrop_Activity.class);
startActivity(intent);
overridePendingTransition(R.anim.start_enter, R.anim.start_exit);
break;
}
}
};
public void settingPrev(View v) {
finish();
}
public void finish()
{
if(sync == true) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
}
super.finish();
overridePendingTransition(R.anim.slide_close_down_info, R.anim.slide_clode_up_info);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sync = true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
|
package org.quickbundle.tools.support.transpage2htm;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpFileSucker {
private String proxyHost;
private String proxyPort;
public HttpFileSucker() {
}
public HttpFileSucker(String s, String s1) {
proxyHost = s;
proxyPort = s1;
}
public String getProxyHost() {
return proxyHost;
}
public String getProxyPort() {
return proxyPort;
}
public void setProxyHost(String s) {
proxyHost = s;
}
public void setProxyPort(String s) {
proxyPort = s;
}
public void suck(URL url, File file) throws HttpFileSuckerException
//throws HttpFileSuckerException
{
if (proxyHost != null) {
java.util.Properties properties = System.getProperties();
properties.put("http.proxyHost", proxyHost);
properties.put("http.proxyPort", proxyPort);
}
try {
HttpURLConnection httpurlconnection =
(HttpURLConnection) url.openConnection();
BufferedInputStream bufferedinputstream =
new BufferedInputStream(httpurlconnection.getInputStream());
BufferedOutputStream bufferedoutputstream =
new BufferedOutputStream(new FileOutputStream(file));
int i;
while ((i = bufferedinputstream.read()) != -1)
bufferedoutputstream.write(i);
bufferedinputstream.close();
bufferedoutputstream.close();
httpurlconnection.disconnect();
} catch (IOException _ex) {
try {
HttpURLConnection httpurlconnection1 =
(HttpURLConnection) url.openConnection();
httpurlconnection1.setRequestMethod("HEAD");
httpurlconnection1.connect();
HttpFileSuckerException httpfilesuckerexception =
new HttpFileSuckerException(
httpurlconnection1.getResponseMessage());
httpurlconnection1.disconnect();
throw httpfilesuckerexception;
} catch (Exception exception) {
throw new HttpFileSuckerException(
"Errore non gestito",
exception);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void transNews(
String baseURL,
String baseFilePath,
String channel_id,
String fileName)
throws HttpFileSuckerException {
URL u = null;
try {
u = new URL(baseURL + channel_id);
File f = new File(baseFilePath + fileName);
if (u != null)
this.suck(u, f);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void transNews(String url, String filePath)
throws HttpFileSuckerException {
URL u = null;
try {
u = new URL(url);
File f = new File(filePath);
if (u != null)
this.suck(u, f);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws HttpFileSuckerException {
HttpFileSucker hfs = new HttpFileSucker();
try {
String baseURL =
"http://127.0.0.1:9080/Eipco/news/NewsListAction.do?cmd=listNewsByChannel_id&channel_id=";
String baseFilePath = System.getProperty("file.separator");
String channel_id = "001001001";
String fileName = channel_id + ".htm";
hfs.transNews(baseURL, baseFilePath, channel_id, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.dgt.tools.dgtviewer.view;
import com.dgt.tools.dgtviewer.model.MonitorInfoConsole;
import javax.swing.JTextArea;
/**
*
* @author Wayssen
*/
public class MonitorInfoConsoleReder implements MonitorInfoConsole {
private JTextArea txtArea;
private static MonitorInfoConsoleReder instance;
private MonitorInfoConsoleReder(JTextArea txtArea) {
this.txtArea = txtArea;
}
public static MonitorInfoConsoleReder getInstance(JTextArea txtArea) {
if (instance == null) {
instance = new MonitorInfoConsoleReder(txtArea);
}
return instance;
}
@Override
public void infoMessage(String mssg) {
this.txtArea.append(mssg);
this.txtArea.append("\n");
}
}
|
package chartUI;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
/**
* @author xiebi
*服务端
*功能:接受客户端发来的消息,然后发送给所有在线的客户端
*/
public class Server
{
public static ArrayList<Socket> sockets=new ArrayList<Socket>();
public static void main(String[] args) {
try {
System.out.println("服务器启动");
ServerSocket server=new ServerSocket(1995);
while(true)
{
System.out.println("等待客户端连接");
Socket s = server.accept();//等待客户端连接
sockets.add(s);
System.out.println("客户端已连接,目前在线人数"+sockets.size());
new ServerThread(s).start();//服务器为每一个socket开启线程
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread extends Thread
{
private Socket s;
public ServerThread(Socket s)
{
this.s=s;
}
public void run()
{
try {
BufferedReader br=new BufferedReader
(new InputStreamReader(s.getInputStream()));
//获得登录的用户姓名,然后给所有的客户端发送欢迎XXX登录
String username = br.readLine();
for(Socket socket:Server.sockets)
{
OutputStreamWriter osw=
new OutputStreamWriter(socket.getOutputStream());
osw.write("[系统消息]欢迎"+username+"登录\n");
System.out.println("[系统消息]欢迎"+username+"登录\n");
osw.flush();
}
//接收聊天信息,然后转发给所有的客户端
while(true)
{
String content=br.readLine();
System.out.println(username+":"+content);
for(Socket socket:Server.sockets)
{
OutputStreamWriter osw =
new OutputStreamWriter(socket.getOutputStream());
osw.write(username+":"+content+'\n');
osw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.fomywo.wordAction.description;
public interface IFomywoTransformation<T> {
public abstract T action(String command);
} |
package com.cg.demo.ios;
import java.io.FileNotFoundException;
import java.io.FileReader;
// READ DATA FROM FILE USING FILE READER
public class CharDemo {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("sample.txt");
int i;
while((i=fr.read())!= -1)
System.out.print((char) i);
fr.close();
}
}
|
package iodatastream.statistics;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class HeightStatistics {
public void saveHeights(List<Integer> heights, Path path) {
if (path == null) {
throw new IllegalArgumentException("Path can't be null");
}
if (heights == null) {
throw new IllegalArgumentException("Heights can't be null");
}
try (DataOutputStream stream = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(path)))) {
stream.writeInt(heights.size());
for (int item : heights) {
stream.writeInt(item);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package by.epam.javatraining.myshko.controller;
import by.epam.javatraining.myshko.model.OperationsExecutor;
import by.epam.javatraining.myshko.view.ConsoleOut;
public class Controller {
public static void main(String[] args) {
int num = 7;
int a = 4, b = 30;
ConsoleOut.greatestDigitFinderOutput(OperationsExecutor.greatestDigitFinder(num));
ConsoleOut.palindromeCheckOutput(OperationsExecutor.palindromeCheck(num));
ConsoleOut.isSimpleOutput(OperationsExecutor.isSimple(num));
ConsoleOut.findGreatestCommonFactorOutput(OperationsExecutor.findGreatestCommonFactor(a, b));
ConsoleOut.findLeastCommonMultipleOutput(OperationsExecutor.findLeastCommonMultiple(a, b));
ConsoleOut.findNumberOfDifferentDigits(OperationsExecutor.findNumberOfDifferentDigits(num));
}
}
|
package br.com.fiap.fiapinteliBe21.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import br.com.fiap.fiapinteliBe21.domain.RespostaTeste;
@Repository
public interface RespostaTesteRepository extends JpaRepository<RespostaTeste, Long> {
@Transactional(readOnly = true)
@Query("select u from RespostaTeste u where u.cnpjOuCpf = ?1"
+ " and u.formulario.idFormulario = ?2 "
+ "order by u.candidato.idCandidato")
List <RespostaTeste> findByCnpjOuCpfAndFormulario(Long cnpjOuCpf, Long idFormulario) ;
}
|
package com.machao.base.model.exception;
public class RequestParamsErrorException extends RuntimeException{
private static final long serialVersionUID = 2722989932819775292L;
}
|
package com.nfschina.aiot.util;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 存储过程工具类
* @author wujian
*/
public class DBPro {
private static final String driveName = "com.mysql.jdbc.Driver";
private static final String username = "root";
private static final String password = "root";
//private static final String url = "jdbc:mysql://222.173.73.19:3306/zkghdb";
private static final String url = "jdbc:mysql://10.50.200.120:3306/zkghdb";
private Connection connection = null;
public CallableStatement cs;
public DBPro(String sql){
try {
Class.forName(driveName);
DriverManager.setLoginTimeout(8000);
connection = DriverManager.getConnection(url, username, password);
cs = connection.prepareCall(sql);
cs.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
try {
cs.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
import java.util.*;
public class Ques1
{
public static void mian()
{
Scanner sc= new Scanner (System.in);
System.out.println("Enter the size of the array:");
int n=sc.nextInt();
int nums[]=new int [n];
System.out.println("Enter the elements of the array");
for(int i=0;i<n;i++)
nums[i]=sc.nextInt();
int max=Integer.MIN_VALUE;
int sum=0;
for (int i=0; i <n; i++)
{
for (int j=i; j<n; j++)
{
for (int k=i; k<=j; k++)
sum+=nums[k];
if(sum>max)
{
max=sum;
}
sum=0;
}
}
System.out.println(max);
}
}
|
package verwalteStudent;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import source.studenten.VerwalteStudent;
import exceptions.FalscherEintragException;
/**
* Tests der Methode pruefeAbiturNoteAufGrenze der Klasse VerwalteStudent
*
* @author Timea Magyar
*
*/
@RunWith(Parameterized.class)
public class PruefeAbiturNote
{
static VerwalteStudent gueltigerStudent = new VerwalteStudent();
static float abiturNote;
static float abiturNoteStudent;
/**
* Konstruktor der Testklasse.
* <p>
* Wird für die Speicherung der Werte der in {@link #generiereDaten}
* erzeugten Parameterliste benötigt.
* <p>
* Die unten genannte Parameterliste besteht aus einem Array Collection. Die
* Anzahl der Klassenattribute (abiturNote) muss der Anzahl der Elemente in
* jedem einzelnen Array entsprechen.
* <p>
*/
public PruefeAbiturNote(float abiturNote)
{
PruefeAbiturNote.abiturNote = abiturNote;
}
/**
* Definiert mögliche falschen Eingaben.
* <p>
* Falsche Eingaben werden in der Testmethode
* {@link #testAbiturNoteAufGrenzeUngueltig} automatisch nacheinander als
* Testparameter übergeben und geprüft. Somit kann man mehrere falschen
* Eingabenkonstellationen in einer einzigen Testmethode nacheinander auf
* ein Exception prüfen.
* <p>
*
* @return abiturNoten
*
*/
@Parameters
public static Collection<Object[]> generiereDaten()
{
Object[][] abiturNoten = new Object[][] { { 0.7f }, { 12 }, { 5.4f } };
return Arrays.asList(abiturNoten);
}
@Rule
public ExpectedException thrown = ExpectedException.none();
/**
* Das jeweilige Arrayelement der in {@link #generiereDaten} definierten
* Parameterliste wird nacheinander zum Testen über das Klassenattribut
* abiturNote übergeben.
* <p>
* Dieser enthält den jeweiligen Parameterwert pro Testdurchlauf.
*
* @throws FalscherEintragException
*/
@Test
public void testAbiturNoteAufGrenzeUngueltig()
throws FalscherEintragException
{
abiturNoteStudent = abiturNote;
thrown.expect(FalscherEintragException.class);
gueltigerStudent.pruefeAbiturNoteAufGrenze(abiturNoteStudent);
}
/**
* Zeigt, dass eine richtige Abiturnote auch als solches akzeptiert wird.
* Richtig heißt in diesem Fall, dass die Note zwischen 1.0 und 5.0 liegt.
* Dieser Test wird nach jedem parametrisierten Test einmal ausgeführt.
* Daher ist die Anzahl der Tests insgesamt 6.
*
* @throws FalscherEintragException
*/
@Test
public void testAbiturNoteAufGrenzeGueltig()
throws FalscherEintragException
{
abiturNoteStudent = 1.3f;
assertTrue(gueltigerStudent
.pruefeAbiturNoteAufGrenze(abiturNoteStudent));
}
}
|
package com.example.nikit.news.ui.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.nikit.news.R;
import com.example.nikit.news.entities.Article;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by nikit on 14.03.2017.
*/
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ArticleViewHolder> {
private final ArrayList<Article> articles;
public NewsAdapter(){
articles = new ArrayList<>();
}
//public NewsAdapter(NewsEntity newsEntity) {
// articles = newsEntity.getArticles();
//}
// public NewsAdapter(ArrayList<Article> articles){
// this.articles = articles;
// }
@Override
public NewsAdapter.ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ArticleViewHolder(inflater.inflate(R.layout.article_item, parent, false));
}
@Override
public void onBindViewHolder(ArticleViewHolder holder, int position) {
if(articles!=null) {
holder.bindArticle(articles.get(position));
}
}
@Override
public int getItemCount() {
return articles.size();
}
public boolean swapData(ArrayList<Article> newDataList){
if(newDataList!=null && newDataList.size()>0){
this.articles.clear();
this.articles.addAll(newDataList);
this.notifyDataSetChanged();
return true;
} else return false;
}
class ArticleViewHolder extends RecyclerView.ViewHolder{
private TextView tvArticleTitle;
private ImageView ivArticleImage;
private TextView tvArticleDesc;
private TextView tvSourceId;
public ArticleViewHolder(View itemView) {
super(itemView);
tvArticleTitle = (TextView)itemView.findViewById(R.id.tv_article_title);
tvArticleDesc = (TextView)itemView.findViewById(R.id.tv_article_desc);
ivArticleImage = (ImageView)itemView.findViewById(R.id.iv_article_image);
tvSourceId = (TextView)itemView.findViewById(R.id.tv_source_id);
}
public void bindArticle(Article article){
tvArticleTitle.setText(article.getTitle());
tvArticleDesc.setText(article.getDescription());
Picasso.with(itemView.getContext()).load(article.getUrlToImage()).into(ivArticleImage);
}
}
}
|
/** https://www.spoj.com/problems/RPLA/ tag: #topological-sort */
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class AnswerBoss {
public static void topoSorting(
ArrayList<ArrayList<Integer>> graph, int[] inDegree, ArrayList<ArrayList<Integer>> rankArr) {
for (int i = 0; i < inDegree.length; i++) {
if (inDegree[i] == 0) {
rankArr.get(1).add(i);
}
}
for (int rank = 1; rank < rankArr.size(); rank++) {
for (int node : rankArr.get(rank)) {
for (int neighbour : graph.get(node)) {
inDegree[neighbour] -= 1;
if (inDegree[neighbour] == 0) {
rankArr.get(rank + 1).add(neighbour);
}
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
for (int t = 1; t < testcases + 1; t++) {
int n = sc.nextInt();
int r = sc.nextInt();
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
ArrayList<ArrayList<Integer>> rankArr = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
rankArr.add(new ArrayList<>());
}
rankArr.add(new ArrayList<>());
int[] inDegree = new int[n];
int u, v;
for (int i = 0; i < r; i++) {
u = sc.nextInt();
v = sc.nextInt();
graph.get(v).add(u);
inDegree[u] += 1;
}
topoSorting(graph, inDegree, rankArr);
System.out.println("Scenario #" + t + ":");
for (int rank = 0; rank < rankArr.size(); rank++) {
if (rankArr.get(rank).isEmpty()) {
continue;
}
Collections.sort(rankArr.get(rank));
for (int node : rankArr.get(rank)) {
System.out.println(rank + " " + node);
}
}
}
return;
}
}
|
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class JobServlet
*/
@WebServlet("/JobServlet")
public class JobServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JobServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String nextUrl="/Skills.jsp";
String post=request.getParameter("post");
String position=request.getParameter("position");
String employer=request.getParameter("employer");
String startDate=request.getParameter("startYear");
String endYear=request.getParameter("endYear");
String dutyOne=request.getParameter("dutyOne");
String dutyTwo=request.getParameter("dutyTwo");
Jobs job=new Jobs();
HttpSession session = request.getSession();
job= (Jobs)session.getAttribute("jobs");
job.addJob(position, employer, startDate, endYear, dutyOne, dutyTwo);
session.setAttribute("jobs", job);
String yesOrNo=request.getParameter("yesOrNo");
if( yesOrNo.equalsIgnoreCase("yes")){
nextUrl="/Jobs.jsp";
//eduNumber++;
//session.setAttribute("eduNumber",eduNumber);
}
else if ( yesOrNo.equalsIgnoreCase("no")){
nextUrl="/Skills.jsp";
}
getServletContext().getRequestDispatcher(nextUrl).forward(request,response);
}
}
|
package com.docker.storage.mongodb.daos;
import com.docker.data.DataObject;
import com.docker.data.DockerStatus;
import com.docker.data.Lan;
import com.docker.storage.mongodb.BaseDAO;
import org.bson.Document;
/**
* db.serverstatus.ensureIndex({"server" : 1}, {"unique" : true})
*
* @author aplombchen
*
*/
public class LansDAO extends BaseDAO {
public static final String COLLECTION = "lans";
public LansDAO(){
setCollectionName(COLLECTION);
}
@Override
public Document[] getIndexes() {
return new Document[] {};
}
@Override
public Class<? extends DataObject> getDataObjectClass(Document dbObj) {
return Lan.class;
}
@Override
public Document getShardKeys() {
return null;
}
}
|
/*
* Copyright 1999-2017 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.druid.sql.dialect.oracle.ast.clause;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLReplaceable;
import com.alibaba.druid.sql.dialect.oracle.ast.OracleSQLObjectImpl;
import com.alibaba.druid.sql.dialect.oracle.visitor.OracleASTVisitor;
import java.util.ArrayList;
import java.util.List;
public class SampleClause extends OracleSQLObjectImpl implements SQLReplaceable {
private boolean block;
private final List<SQLExpr> percent = new ArrayList<SQLExpr>();
private SQLExpr seedValue;
public boolean isBlock() {
return block;
}
public void setBlock(boolean block) {
this.block = block;
}
public List<SQLExpr> getPercent() {
return percent;
}
public void addPercent(SQLExpr x) {
if (x == null) {
return;
}
x.setParent(this);
this.percent.add(x);
}
public SQLExpr getSeedValue() {
return seedValue;
}
public void setSeedValue(SQLExpr seedValue) {
if (seedValue != null) {
seedValue.setParent(this);
}
this.seedValue = seedValue;
}
@Override
public void accept0(OracleASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, seedValue);
acceptChild(visitor, percent);
}
visitor.endVisit(this);
}
@Override
public SampleClause clone() {
SampleClause x = new SampleClause();
x.block = block;
for (SQLExpr item : percent) {
SQLExpr item1 = item.clone();
item1.setParent(x);
x.percent.add(item1);
}
if (seedValue != null) {
x.setSeedValue(seedValue.clone());
}
return x;
}
@Override
public boolean replace(SQLExpr expr, SQLExpr target) {
for (int i = percent.size() - 1; i >= 0; i--) {
if (percent.get(i) == expr) {
percent.set(i, target);
return true;
}
}
if (expr == seedValue) {
setSeedValue(target);
return true;
}
return false;
}
}
|
package com.esum.wp.ebms.sslsetup;
import com.esum.wp.ebms.sslsetup.base.BaseSSLInfo;
public class SSLInfo extends BaseSSLInfo {
}
|
package com.soyun.travel;
import java.util.List;
import javax.mail.Session;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class MemberDAO {
@Autowired
SqlSessionTemplate mymy;
public void insert(MemberDTO memberDTO) {
mymy.insert("memberDAO.insert",memberDTO);
}
public MemberDTO select(String inputId) {
return mymy.selectOne("memberDAO.select",inputId);
}
public List<MemberDTO> selectCompanion2(MemberDTO inputId) {
return mymy.selectList("memberDAO.select",inputId);
}
public int selectCnt(MemberDTO memberDTO) {
return mymy.selectOne("memberDAO.selectCnt",memberDTO);
}
public int selectCnt2(MemberDTO memberDTO) {
return mymy.selectOne("memberDAO.selectCnt2",memberDTO);
}
public int selectCnt3(String inputId) {
return mymy.selectOne("memberDAO.selectCnt3",inputId);
}
public MemberDTO selectId(MemberDTO memberDTO) {
return mymy.selectOne("memberDAO.selectId",memberDTO);
}
public MemberDTO selectPw(MemberDTO memberDTO) {
return mymy.selectOne("memberDAO.selectPw",memberDTO);
}
public void update(String id) {
mymy.update("memberDAO.update",id);
}
public void updatePw(MemberDTO memberDTO) {
mymy.update("memberDAO.updatePw",memberDTO);
}
public void updateAll(MemberDTO memberDTO) {
mymy.update("memberDAO.updateAll",memberDTO);
}
public void delete(String inputId) {
mymy.delete("memberDAO.delete",inputId);
}
public List<String> selectAll(){
return mymy.selectList("memberDAO.selectAll");
}
public void userAuth(String email) {
mymy.update("memberDAO.memberAuth", email);
}
}
|
package com.jgermaine.fyp.rest.model;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Transient;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "USER_TYPE")
@JsonIgnoreProperties(value={"password"})
public abstract class User {
@Id
@NotEmpty
@Email
@Length(max = 255)
@Column(name="email")
private String email;
@Transient
@Pattern(regexp="[A-Za-z0-9!?.$%]*")
@Length(max = 255, min = 6)
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Transient
private String type;
public void setType(String type) {
this.type = type;
}
public abstract String getType();
}
|
import java.util.HashMap;
public class sparseArrays {
static int[] matchingStrings(String[] strings, String[] queries) {
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
String key = strings[i];
if (!(map.containsKey(key))) {
map.put(key, 1);
} else {
map.put(key, map.get(key) + 1);
}
}
int[] result = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
String key = queries[i];
if (map.containsKey(key)) {
result[i] = map.get(key);
} else {
result[i] = 0;
}
}
return result;
}
}
|
package cn.gaoh.thread.pool;
/**
* @Description: 拒绝策略
* @Author: gaoh
* @Date: 2021/1/24 21:13
* @Version: 1.0
*/
@FunctionalInterface
public interface RejectPolicy<T> {
/**
* 对外提供策略
*
* @param queue 队列
* @param task 任务
*/
void reject(BlockingQueue<T> queue, T task);
}
|
package edu.mit.cci.simulation.excel.server;
import org.junit.Test;
import org.springframework.roo.addon.test.RooIntegrationTest;
@RooIntegrationTest(entity = ExcelSimulation.class)
public class ExcelSimulationIntegrationTest {
@Test
public void testMarkerMethod() {
}
}
|
package com.wipro.collection.list;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Vector;
public class Ex7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Employee> list=new Vector<>();
Employee emp1=new Employee();
emp1.empId=123456;
emp1.empName="Azim Premji";
emp1.email="azmprmji@wipro.in";
emp1.gender="Male";
emp1.salary=500000000;
list.add(emp1);
Employee emp2=new Employee();
emp2.empId=123457;
emp2.empName="Mrs.Premji";
emp2.email="mrsprmji@wipro.in";
emp2.gender="Female";
emp2.salary=400000000;
list.add(emp2);
Employee emp3=new Employee();
emp3.empId=123458;
emp3.empName="CEO";
emp3.email="wiproceo@wipro.in";
emp3.gender="Male";
emp3.salary=150000000;
list.add(emp3);
System.out.println("Printing using Iterator :");
Iterator<Employee> itr=list.iterator();
try
{
while(itr.hasNext())
{
Employee emp=itr.next();
System.out.println(emp);
emp.getEmployeeDetails();
}
System.out.println();
System.out.println("Printing using Enumeration :");
Enumeration<Employee> e=Collections.enumeration(list);
while(e.hasMoreElements())
{
Employee emp=e.nextElement();
System.out.println(emp);
emp.getEmployeeDetails();
}
}
catch(NoSuchElementException e)
{
e.printStackTrace();
System.out.println(e);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e);
}
}
}
|
/**
* Created by Xurxo on 20/06/2016.
*/
public class ChannelDay {
public String day;
public String channel;
public ChannelDay(String fecha, String nameChannel) {
day = fecha;
channel = nameChannel;
}
public String toString() {
return day + " -> " + channel;
}
}
|
package com.NewKindOfPower.NewKindOfPower.items;
import com.NewKindOfPower.NewKindOfPower.NewKindOfPower;
import com.NewKindOfPower.NewKindOfPower.Reference;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
public class ItemInsulation extends Item {
public ItemInsulation()
{
setUnlocalizedName(Reference.ModItems.INSULATION.getUnlocalizedName());
setRegistryName(Reference.ModItems.INSULATION.getRegistryName());
this.maxStackSize = 64;
setCreativeTab(NewKindOfPower.tabNewKindOfPower);
}
}
|
package com.gaoshin.cloud.web.job.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlTransient;
@Entity
@Table
public class RuntimeJobConfEntity {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(length=32)
private String ckey;
@Column(length=2047)
private String cvalue;
@Column
private boolean password = false;
@Column(nullable = false)
private Long jobExecutionId;
public RuntimeJobConfEntity() {
}
public RuntimeJobConfEntity(String key, String value) {
this.ckey = key;
this.cvalue = value;
}
public void setId(Long id) {
this.id = id;
}
@XmlTransient
public Long getId() {
return id;
}
public void setPassword(boolean isPassword) {
this.password = isPassword;
}
public boolean isPassword() {
return password;
}
public String getCkey() {
return ckey;
}
public void setCkey(String ckey) {
this.ckey = ckey;
}
public String getCvalue() {
return cvalue;
}
public void setCvalue(String cvalue) {
this.cvalue = cvalue;
}
public Long getJobExecutionId() {
return jobExecutionId;
}
public void setJobExecutionId(Long jobExecutionId) {
this.jobExecutionId = jobExecutionId;
}
}
|
package com.waylau.spring.boot.security.contrller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
/**
* Hello World 控制器测试类
* @author <a href="https://waylau.com">Way Lau</a>
* @date 2017年1月26日
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
//@Test
public void testList() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users"))
.andExpect(status().isOk());
}
@Test
@WithMockUser(username="waylau", password="123456", roles={"USER"}) // mock 了一个用户
public void testListWithUser() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/users"))
.andExpect(status().isOk());
}
}
|
package com.migu.spider.service;
import org.springframework.stereotype.Service;
import com.migu.spider.model.Compet;
@Service
public class MongoServiceImpl implements IMongoService{
@Override
public void save(Compet compet) {
System.out.println("--------------------------------mongo save--------------------------------");
if(compet.getType().equals("list")) {
System.out.println("存榜单数据库存储!");
}else if(compet.getType().equals("info")) {
System.out.println("存详细信息数据库存储!");
}
}
}
|
package IOLecture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class IO_Test {
void FileReadMethod(String filename)
{
File f = new File(filename);
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine())
{
String s = scan.nextLine();
System.out.println(s);
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println(" Error: "+e + " "+ filename);
e.printStackTrace();
}
}
void FileCopy(String filename, String outFile)
{
File f = new File(filename);
File fo = new File(outFile);
try {
Scanner scan = new Scanner(f);
PrintStream ps = new PrintStream(fo);
while (scan.hasNextLine())
{
String s = scan.nextLine();
ps.println(s);
}
scan.close();
ps.close();
} catch (FileNotFoundException e) {
System.out.println(" Error: "+e + " "+ filename);
e.printStackTrace();
}
}
public static void main(String[] args) {
IO_Test it = new IO_Test();
it.FileCopy("src/IOLecture/IO_Test.java", "junk.txt");
System.out.println("Copy finished: src/IOLecture/IO_Test.java --> junk.txt");
it.FileReadMethod("junk.txt");
}
} |
package uninsubria.cognitivecomplexity;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import uninsubria.cognitivecomplexity.core.ModuleAnalizer;
import uninsubria.cognitivecomplexity.dao.ModuleInfoDAO;
public class InputManager {
private static final Logger logger = LogManager.getLogger();
private final String FILE_EXTENSION = ".java";
public InputManager() {
//Default Constructor
}
public List<List<ModuleInfoDAO>> executeCognitiveComplexityCalculus(File directoryOrFile) throws FileNotFoundException{
List<List<ModuleInfoDAO>> calculusResults = new LinkedList<List<ModuleInfoDAO>>();
List<File> javaFiles = this.getAllDirectoryFiles(directoryOrFile);
printAllDetectedJavaFiles(javaFiles);
System.out.println();//Questa riga server solo per separare due blocchi di testo in console
for(File javaFile: javaFiles) {
logger.info("Analizing {}", javaFile.getName());
CompilationUnit compUnit = StaticJavaParser.parse(javaFile);
String absoluteFilePath = javaFile.getAbsolutePath();
List<ModuleInfoDAO> calculusResult = new ModuleAnalizer(absoluteFilePath).parseJavaFile(compUnit);
calculusResults.add(calculusResult);
}
return calculusResults;
}
/**
* Esegue una ricerca ricorsiva per trovare tutti i java file contenuti nella cartella e/o nelle cartelle sottostanti.
* @param directoryOrFile può essere una cartella o semplicemente un java file
* @return lista contenente tutti i fava file trovati
*/
private List<File> getAllDirectoryFiles(File directoryOrFile){
List<File> javaFiles = new LinkedList<>();
if(directoryOrFile.isDirectory()) {
File[] files = directoryOrFile.listFiles();
for(File file: files) {
List<File> subFiles = this.getAllDirectoryFiles(file);
javaFiles.addAll(subFiles);
}
}else if(directoryOrFile.isFile()) {
if(directoryOrFile.getName().endsWith(FILE_EXTENSION)) {
javaFiles.add(directoryOrFile);
}
}
return javaFiles;
}
/**
* Stampa in console i nomi di tutti i java file trovati nella cartella/sottocartella specificata
* @param javaFiles lista contenente i file trovti
*/
private void printAllDetectedJavaFiles(List<File> javaFiles) {
if(javaFiles != null && !javaFiles.isEmpty()) {
logger.info("FOUND JAVA FILES: ");
for(File file: javaFiles) {
logger.info(file.getName());
}
}else {
logger.info("No java files founded in specified directory!");
}
}
}
|
import java.io.IOException;
import jp.co.nakkspeed.spring.webapp.Routes;
public class Main {
public static void main(String[] args) {
// TODO 自動生成されたメソッド・スタブ
Routes routes = new Routes();
try {
routes.create("user", "{\"name\": \"太郎\", \"age\": 36}");
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
}
|
package swea_d2;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class Solution_1288_새로운불면증치료법 {
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
int N = Integer.parseInt(br.readLine());
int[] arr = new int[10];
int x = 1;
int tmp = 0;
int cnt =0;
while (true) {
tmp = N * x;
while (tmp != 0) {
arr[tmp % 10]++;
tmp /= 10;
}
cnt =0;
for(int i = 0 ; i<arr.length ; i++) {
if(arr[i] != 0) {
cnt++;
}
}
if(cnt == 10)break;
x++;
}
System.out.println("#"+tc+" "+N*x);
}
}
}
|
/**
*
*/
package com.intertec.listusername.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.intertec.listusername.repository.UserRepository;
import com.intertec.listusername.service.UtilService;
import com.intertec.listusername.service.WordRestrictService;
/**
* @author nandopc001
*
*/
@Service
public class UtilServiceImpl implements UtilService {
/*
* (non-Javadoc)
*
* @see
* com.intertec.listusername.service.Util#sugestUsername(java.lang.String)
*/
@Autowired
UserRepository userRepository;
@Autowired
WordRestrictService wordRestrictService;
@Override
public List<String> sugestUsername(String name, List<String> nameRestrict) {
// TODO Auto-generated method stub
Random generator = new Random();
int x = 0;
int a = 0;
List<String> resultUsernames = new ArrayList<>();
while (resultUsernames.size() < 14) {
x = generator.nextInt();
a = (x % 100);
StringBuffer nameAux = new StringBuffer();
nameAux.append(name);
nameAux.append(String.valueOf(Math.abs(a)));
if (!nameRestrict.contains(nameAux.toString())) {
resultUsernames.add(nameAux.toString());
nameRestrict.add(nameAux.toString());
}
}
return resultUsernames.stream().sorted().collect(Collectors.toList());
}
@Override
public List<String> getListSugestion(String name) {
List<String> nameRestrict = userRepository.findUserByNameLike(name);
nameRestrict.addAll(wordRestrictService.findAll());
return this.sugestUsername(name, nameRestrict);
}
}
|
/* Program displays anybody with the last name Smith in the database I created */
import java.util.*;
import java.sql.*;
public class Database {
public static void main(String[] args) throws Throwable{ // Main function
Class.forName("com.mysql.jdbc.Driver"); // Loads driver
System.out.println("Driver loaded");
Enumeration<Driver> ed = DriverManager.getDrivers(); //Gets driver
while(ed.hasMoreElements()){
System.out.println((Driver)ed.nextElement());
}
Connection my_connection = DriverManager.getConnection("jdbc:mysql://localhost/Java", "mlum", "swiftie13"); //Connects to database
System.out.println("Database connected");
Statement statement = my_connection.createStatement();
ResultSet my_results = statement.executeQuery("select * from my_table");
ResultSet resultSet = statement.executeQuery("Select firstname, mi, lastname from Student where lastname" + "= 'Smith'");
while (resultSet.next())
System.out.println(resultSet.getString(1) + "/t" + resultSet.getString(2) + "\t" + resultSet.getString(3));
my_connection.close();
}
}
|
package com.cbs.edu.eshop.dao;
import com.cbs.edu.eshop.entity.AbstractEntity;
import com.cbs.edu.eshop.entity.Role;
import com.cbs.edu.eshop.entity.User;
public interface IRoleDAO<T extends AbstractEntity> extends GenericDAO<Role> {
Role getRoleByName(String name);
}
|
package webuters.com.geet_uttarakhand20aprilpro.activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.danikula.videocache.HttpProxyCacheServer;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import webuters.com.geet_uttarakhand20aprilpro.GeetApplication;
import webuters.com.geet_uttarakhand20aprilpro.R;
import webuters.com.geet_uttarakhand20aprilpro.Utils.TagUtils;
import webuters.com.geet_uttarakhand20aprilpro.pojo.AlbumSongResultPOJO;
/**
* Created by sunil on 26-08-2016.
*/
public class BluredMediaPlayer2 extends AppCompatActivity {
ImageView suffel, repeat, next_song_button, previous_song_button,share;
public static ToggleButton play_pause_button;
public static ImageView image_singer, frame_background;
public static TextView remaining_songtime_left_text, total_song_time_text;
FrameLayout blur_frame;
public static SeekBar song_seekbar1;
private ConnectionDetector cd;
public static String songimagevalue;
// BroadcastReceiver broadcastReceiver;
public static MediaPlayer mediaPlayer;
Intent ii = null;
public static boolean broad= false;
public static double startTime = 0;
public static double finalTime = 0;
public static ArrayList<AlbumSongResultPOJO> albumSongsBeen= (ArrayList<AlbumSongResultPOJO>) Setting_event.albumSongResultPOJOS;
public static String song_pathvalue ;
String song_invalue ;
public static int currentsongindex=0;
private static final String TAG="sunil";
public static Handler myHandler = new Handler();
private boolean isShuffle = false;
private boolean isRepeat = false;
Notificationn2 nn;
public static LinearLayout blur_linear,pb_ll;
public static BluredMediaPlayer2 bm2;
public static TelephonyManager mgr;
boolean back_flag;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blur_media_player);
bm2=this;
SettingToolbar();
initViews();
gettingPrefValues();
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
back_flag=bundle.getBoolean("backup");
}
// Setting_Broadcast();
play_pause_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PlayPauseMethod();
}
});
previous_song_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("sunil","current:-"+currentsongindex);
Log.d("sunil","size:-"+Setting_event.albumSongResultPOJOS.size());
Log.d(TAG,"prev song");
previousSong();
}
});
next_song_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("sunil","current:-"+currentsongindex);
Log.d("sunil","size:-"+Setting_event.albumSongResultPOJOS.size());
Log.d(TAG,"next song");
nextSong();
}
});
if(!AppConstant.getFavMusicPref(this)) {
Log.d(TagUtils.getTag(),"starting fav music player");
startTime=0;
PlayMusic(song_pathvalue,songimagevalue);
}
song_seekbar1.setClickable(false);
song_seekbar1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
seekChange(view);
return false;
}
});
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent shareIntent =
new Intent(Intent.ACTION_SEND);
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/abc.mp3";
shareIntent.setType("audio/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///" + path));
startActivity(Intent.createChooser(shareIntent, "Share Sound File"));
shareIntent.setType("text/plain");
}
});
suffel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(BluredMediaPlayer2.this, "Shuffle is OFF", Toast.LENGTH_SHORT).show();
// btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Collections.shuffle(new AlbumeSongs().AlBUM_LIST_ARRAY);
for(int i=0;i<Setting_event.albumSongResultPOJOS.size();i++){
if(song_pathvalue.equals(Setting_event.albumSongResultPOJOS.get(i).getSongPath())){
currentsongindex=i;
Log.d("sunil","current_song_index:-"+currentsongindex);
}
}
Toast.makeText(BluredMediaPlayer2.this, "Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
}
}
});
mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
// @Override
// protected void onStop() {
// super.onStop();
// Log.d("sunil","stop");
// unregisterReceiver(broadcastReceiver);
// }
//
// @Override
// protected void onStart() {
// super.onStart();
// registerReceiver(broadcastReceiver,new IntentFilter("broadCastName"));
// }
public static void unregister_phonestate(){
Log.d("sunil","unregister_phonestate");
bm2.unregister();
}
public void unregister(){
Log.d("sunil","unregister");
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
if(AppConstant.getRecievingPref(getApplicationContext())&&AppConstant.getIsPlaying(getApplicationContext())) {
Log.d("sunil","ringing");
Log.d("sunil","bm2 ringing");
try {
AppConstant.setSavedCallStatus(getApplicationContext(), true);
AppConstant.setRecievePref(getApplicationContext(),false);
AppConstant.setIdlePref(getApplicationContext(),true);
AppConstant.setoffhookPref(getApplicationContext(),true);
PlayPauseMethod();
} catch (Exception e) {
Log.d("sunil", e.toString());
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play musics
try {
if(AppConstant.getIdlePref(getApplicationContext())) {
if (AppConstant.getSavedCallStatus(getApplicationContext())) {
Log.d("sunil","bm2 idle");
Log.d("sunil","idle");
AppConstant.setRecievePref(getApplicationContext(),true);
AppConstant.setIdlePref(getApplicationContext(),false);
AppConstant.setoffhookPref(getApplicationContext(),true);
AppConstant.setSavedCallStatus(getApplicationContext(), false);
PlayPauseMethod();
}
}
}
catch (Exception e){
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
if(AppConstant.getoffhookPref(getApplicationContext())&&AppConstant.getIsPlaying(getApplicationContext())) {
Log.d("sunil", "offhook");
Log.d("sunil","bm2 offhook");
try {
AppConstant.setRecievePref(getApplicationContext(),true);
AppConstant.setIdlePref(getApplicationContext(),true);
AppConstant.setoffhookPref(getApplicationContext(),false);
AppConstant.setSavedCallStatus(getApplicationContext(), true);
PlayPauseMethod();
} catch (Exception e) {
Log.d("sunil", e.toString());
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void PlayPauseMethod(){
if((mediaPlayer!=null)){
if(mediaPlayer.isPlaying()){
play_pause_button.setChecked(true);
mediaPlayer.pause();
AppConstant.setIsPlaying(getApplicationContext(),false);
Notificationn2.changeImageView2();
}
else{
play_pause_button.setChecked(false);
mediaPlayer.start();
AppConstant.setIsPlaying(getApplicationContext(),true);
Notificationn2.changeImageView1();
}
}else {
broad=false;
}
}
private void seekChange(View v){
// if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
mediaPlayer.seekTo(sb.getProgress());
}
public static Runnable UpdateSongTime = new Runnable()
{
public void run() {
startTime = mediaPlayer.getCurrentPosition();
song_seekbar1.setMax(mediaPlayer.getDuration());
song_seekbar1.setProgress(mediaPlayer.getCurrentPosition());
// seekHandler.postDelayed(run, 1000);
myHandler.postDelayed(this, 1000);
remaining_songtime_left_text.setText(String.format("%d: %d ",
TimeUnit.MILLISECONDS.toMinutes((long) startTime),
TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
toMinutes((long) startTime)))
);
}
};
public void nextSong(){
Log.d(TagUtils.getTag(),"saved song mp");
if((currentsongindex+1)!=Setting_event.albumSongResultPOJOS.size()){
song_pathvalue=Setting_event.albumSongResultPOJOS.get(currentsongindex+1).getSongPath();
songimagevalue=Setting_event.albumSongResultPOJOS.get(currentsongindex+1).getSongImg();
PlayMusic(song_pathvalue,songimagevalue);
BluredMediaPlayer2.startTime=0;
myHandler.postDelayed(UpdateSongTime, 1000);
}
}
public void previousSong(){
if(currentsongindex!=0){
BluredMediaPlayer2.startTime=0;
song_pathvalue=Setting_event.albumSongResultPOJOS.get(currentsongindex-1).getSongPath();
songimagevalue=Setting_event.albumSongResultPOJOS.get(currentsongindex-1).getSongImg();
PlayMusic(song_pathvalue,songimagevalue);
myHandler.postDelayed(UpdateSongTime, 1000);
}
}
// public void Setting_Broadcast(){
// broadcastReceiver = new BroadcastReceiver() {
// @Override
// public void onReceive(Context context, Intent intent) {
//
// try {
// String action = intent.getStringExtra("message");
// Toast.makeText(getApplication(),""+action,Toast.LENGTH_SHORT).show();
// broad = true;
// if (action.equals("pause")) {
//// PlayPauseMethod();
// } else if (action.equals("next")) {
// nextSong();
// } else if (action.equals("prev")) {
// previousSong();
// } else if (action.equals("apppp")) {
// //Your code
// Log.d(TAG,"appppp");
// } else if (action.equals("close")) {
// //Your code
// try{
// NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// nMgr.cancelAll();
// }
// catch (Exception e){
// Log.d(TAG,e.toString());
// }
// try{
// Notificationn.clearNotification();
// }
// catch (Exception e){
// Log.d(TAG,e.toString());
// }
// try{
// mediaPlayer.stop();
// finish();
//// PlayPauseMethod();
// }
// catch (Exception e){
// Log.d(TAG,"catched notification");
// }
// }
// }
// catch (Exception e){
//
// }
//
// }
// };
// }
public void gettingPrefValues(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
songimagevalue = prefs.getString("SongImage123", null);
song_pathvalue = prefs.getString("Sengaer_song_path", null);
song_invalue = prefs.getString("Index", null);
Picasso.with(BluredMediaPlayer2.this).load(String.valueOf(songimagevalue)).into(image_singer);
Picasso.with(BluredMediaPlayer2.this).load(String.valueOf(songimagevalue)).into(frame_background);
}
public void SettingToolbar(){
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_home);
setSupportActionBar(toolbar);
setTitle("BlurMediaPlayer");
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public void initViews(){
previous_song_button = (ImageView) findViewById(R.id.previous_song_button);
play_pause_button = (ToggleButton) findViewById(R.id.play_pause_button);
image_singer = (ImageView) findViewById(R.id.image_singer);
repeat = (ImageView) findViewById(R.id.repeat);
suffel = (ImageView) findViewById(R.id.suffel);
frame_background = (ImageView) findViewById(R.id.frame_background);
remaining_songtime_left_text = (TextView) findViewById(R.id.remaining_songtime_left_text);
total_song_time_text = (TextView) findViewById(R.id.total_song_time_text);
blur_frame = (FrameLayout) findViewById(R.id.blur_frame);
next_song_button = (ImageView) findViewById(R.id.next_song_button);
song_seekbar1 = (SeekBar) findViewById(R.id.song_seekbar);
share = (ImageView) findViewById(R.id.share);
blur_linear= (LinearLayout) findViewById(R.id.blur_linear);
pb_ll= (LinearLayout) findViewById(R.id.pb_ll);
}
public void PlayMusic(final String idUrl, final String song_image_value) {
blur_linear.setVisibility(View.VISIBLE);
// blur_linear.setBackgroundColor(Color.parseColor("#BDBDBD"));
pb_ll.setVisibility(View.VISIBLE);
new CountDownTimer(100, 100) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
}
public void onFinish() {
playMusic1(idUrl,song_image_value);
}
}.start();
}
public void showNotification(){
//Notificationn.ctx = BlurMediaPlayer.this;
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion>= Build.VERSION_CODES.JELLY_BEAN) {
if(AppConstant.getFavMusicPref(this)){
Log.d("sunil","bm2 if");
AppConstant.SetSaveMusicpref(this,false);
AppConstant.SetmainMusicpref(this,false);
AppConstant.SetfavMusicPref(this,true);
}
else {
Log.d("sunil","bm2 else");
AppConstant.SetSaveMusicpref(this, false);
AppConstant.SetmainMusicpref(this, false);
AppConstant.SetfavMusicPref(this, true);
AppConstant.setMainCallStatus(getApplicationContext(), false);
AppConstant.setCallStatus(getApplicationContext(), false);
AppConstant.setSavedCallStatus(getApplicationContext(), false);
AppConstant.setIdlePref(this, true);
AppConstant.setoffhookPref(this, true);
AppConstant.setRecievePref(this, true);
try{
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
}
catch (Exception e){
Log.d("sunil",e.toString());
}
try{
Notificationn.clearNotification();
}
catch (Exception e){
Log.d("sunil",e.toString());
}
try{
SavedSongNotification.clearNotification();
}
catch (Exception e){
}
try{
SavedSongsMusicPlayer.mediaPlayer.stop();
}
catch (Exception e){
}
try{
SavedSongsMusicPlayer.ssmp.finish();
}
catch (Exception e){
}
try{
BlurMediaPlayer1.mediaPlayer.stop();
}
catch (Exception e){
}
try{
BlurMediaPlayer1.bmp1.finish();
}
catch (Exception e){
}
}
nn = new Notificationn2(this);
}
else{
new AlertDialog.Builder(BluredMediaPlayer2.this)
.setTitle("Update your phone")
.setMessage("Your phone is outdated. You may not be able to use some features. Please update your phone.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
dialog.cancel();
}
})
.show();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if(back_flag){
}
else{
Intent intent=new Intent(BluredMediaPlayer2.this,MainActivity.class);
intent.putExtra("backup1",true);
startActivity(intent);
finish();
}
}
public void playMusic1(String idUrl,String songimagevalue){
try{
if(mediaPlayer!=null)
mediaPlayer.release();
}
catch (Exception e){
}
mediaPlayer = new MediaPlayer();
showNotification();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
//(Environment.getExternalStorageDirectory().getPath()+"/term.mp3")
Picasso.with(BluredMediaPlayer2.this).load(String.valueOf(songimagevalue)).into(image_singer);
Picasso.with(BluredMediaPlayer2.this).load(String.valueOf(songimagevalue)).into(frame_background);
Log.d(TagUtils.getTag(),"original url:-"+idUrl);
HttpProxyCacheServer proxy = GeetApplication.getProxy(this);
String proxyUrl = proxy.getProxyUrl(idUrl);
Log.d(TagUtils.getTag(),"proxy url:-"+proxyUrl);
mediaPlayer.setDataSource(proxyUrl);
} catch (IllegalArgumentException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
nextSong();
Log.d("sunil","song completed");
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
Log.d("khogenprep","prepared music");
// Toast.makeText(getApplicationContext(),"prepared",Toast.LENGTH_SHORT).show();
try{
SavedSongsMusicPlayer.ssmp.unregister();
}
catch (Exception e){
}
try{
BlurMediaPlayer1.bmp1.unregister();
}
catch (Exception e){
}
mediaPlayer.start();
blur_linear.setVisibility(View.VISIBLE);
AppConstant.setIsPlaying(getApplicationContext(),true);
pb_ll.setVisibility(View.GONE);
finalTime = mediaPlayer.getDuration();
play_pause_button.setChecked(false);
total_song_time_text.setText(String.format("%d : %d ",
TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime)))
);
for(int i = 0; i< Setting_event.albumSongResultPOJOS.size(); i++){
if(song_pathvalue.equals(Setting_event.albumSongResultPOJOS.get(i).getSongPath())){
currentsongindex=i;
Log.d("sunil","current_song_index:-"+currentsongindex);
}
}
myHandler.postDelayed(UpdateSongTime, 1000);
AppConstant.setsavedmusicplaying(BluredMediaPlayer2.this,false);
AppConstant.setmainmusicplaying(BluredMediaPlayer2.this,false);
AppConstant.setfavmusicplaying(BluredMediaPlayer2.this,true);
}
});
} catch (IllegalStateException e) {
Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}catch(IOException t){
}
}
}
|
package Actions;
import Database.StorageState;
import Frames.MainFrame;
import Frames.PopupDialog;
// this class represents the different button behaviours
public class HandleButton {
public boolean checkData(String dbName, String password) {
if (dbName.length() > 0 && password.length() > 0) {
MainFrame mainFrame = new MainFrame(dbName);
mainFrame.setVisible(true);
return true;
} else {
PopupDialog mydialog = new PopupDialog("Fill all fields!", 200, 200);
return false;
}
}
public boolean saveData(String dbName, String title, String user, String password, String url, String note) {
if(user.length() == 0 || password.length() == 0){
PopupDialog myDialog = new PopupDialog("Enter username and password at least!", 200, 400);
return false;
}
StorageState myDB = new StorageState();
myDB.setDatabaseToSQLite(dbName);
myDB.insert(title, user, password, url, note);
return true;
}
}
|
package org.vcssl.nano.plugin.math.xfci1;
public class RadXfci1Plugin extends Float64VectorizableOperationXfci1Plugin {
@Override
public final String getFunctionName() {
return "rad";
}
@Override
public final void operate(double[] outputData, double[] inputData, int outputDataOffset, int inputDataOffset, int dataSize) {
for (int i=0; i<dataSize; i++) {
double deg = inputData[ i + inputDataOffset ];
double rad = Math.PI * deg / 180.0;
outputData[ i + outputDataOffset ] = rad;
}
}
}
|
package vn.edu.poly.recycleview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private RecyclerView lvList;
private ItemAdapter itemAdapter;
private List<Item> items;
private LinearLayoutManager linearLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvList = findViewById(R.id.lvList);
items = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Item item = new Item();
item.title = " Huy Nguyen " + new Random().nextInt();
items.add(item);
}
linearLayoutManager = new LinearLayoutManager(this);
itemAdapter = new ItemAdapter(this, items);
lvList.setAdapter(itemAdapter);
lvList.setLayoutManager(linearLayoutManager);
}
}
|
package edu.neu.ccs.cs5010;
public class Duplexe extends CandyTree implements House {
public Duplexe(Object rootData) {
super(rootData);
}
Node duplexe = new Node<String>();
{
Node superSize = new Node();
Node kingSize = new Node();
Node funSize = new Node();
duplexe.children.add(superSize);
duplexe.children.add(kingSize);
duplexe.children.add(funSize);
superSize.children.add("Toblerone");
superSize.children.add("Baby Ruth");
superSize.children.add("Almond Joy");
kingSize.children.add("Twix");
kingSize.children.add("Snickers");
kingSize.children.add("Mars");
funSize.children.add("Kit Kat");
funSize.children.add("Whoopers");
funSize.children.add("Milky Way,");
funSize.children.add("Crunch");
}
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
|
package com.github.kemonoske.drophub.core;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
public class HubClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new ParcelDecoder());//TODO: Use AES decoder
pipeline.addLast(new ParcelEncoder());//TODO: Use AES encoder
// and then business logic.
pipeline.addLast(new HubClientHandler());
}
}
|
package com.jit.lembdaVsInnerclass;
public class Test2 {
int x = 888;
public void m2() {
Interf i = () -> {
int x = 999;
System.out.println(this.x);
};
i.m1();
}
public static void main(String[] args) {
Test2 t = new Test2();
t.m2();
}
}
|
package org.kaivos.racter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Stack;
import java.util.stream.Collectors;
public class RacterInterpreter {
public static final Random RANDOM = new Random(8947594l);
CodeSection[] sections = new CodeSection[255];
String[] slots = new String[255];
private class CodeSection {
private Map<String, List<Integer>> lineMap = new HashMap<>();
private List<String> lines = new ArrayList<>();
private String name;
private int size, type;
public CodeSection(String name, int type, int size) {
this.name = name;
this.type = type;
this.size = size;
}
public String getName() {
return name;
}
public int getSize() {
return size;
}
public void putLine(String name, String line) {
if (lineMap.get(name) == null) lineMap.put(name, new ArrayList<Integer>());
lineMap.get(name).add(lines.size());
lines.add(line);
}
public int getLine(String name) {
if (lineMap.get(name) != null) {
List<Integer> choices = lineMap.get(name);
return choices.get(RANDOM.nextInt(choices.size()));
}
for (String key : lineMap.keySet()) {
if (key.startsWith(name)) {
return getLine(key);
}
}
System.err.println("Unknown line " + name);
System.exit(1);
return -1;
}
public String getLine(int id) {
return lines.get(id);
}
public List<String> getLines(String name) {
if (lineMap.get(name) != null) {
List<Integer> choices = lineMap.get(name);
return choices.stream().map(this::getLine).collect(Collectors.toList());
}
for (String key : lineMap.keySet()) {
if (key.startsWith(name)) {
return getLines(key);
}
}
System.err.println("Unknown line " + name);
System.exit(1);
return null;
}
}
public static void runFile(String file) throws IOException {
RacterInterpreter racter = new RacterInterpreter();
racter.loadScript(file);
racter.start(1, "START");
System.out.println();
}
private void start(int secid, String linename) {
CodeSection currentSection = sections[secid];
int ip = linename.length() > 0 ? currentSection.getLine(linename) : 0;
while (true) {
String line = currentSection.getLine(ip);
if (runLine(line)) ip++;
else break;
}
System.out.print(out);
out = " ";
}
private boolean runLine(String string) {
String[] instructions = string.split(" ");
for (String instruction : instructions) {
switch (runInstruction(instruction)) {
case ESCAPE:
return false;
case NEXT_LINE:
return true;
case NEXT_COMMAND:
break;
}
}
return false;
}
private BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
private String readLine() {
try {
System.out.print(">");
return input.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private boolean accumulator = false;
private String out = "", in = "";
private int selWord = 0;
enum Escape { NEXT_LINE, NEXT_COMMAND, ESCAPE }
private Escape runInstruction(String code) {
if (false) {
System.err.print(code + " : " + in + " : " + selWord + "," + accumulator);
for (int i = 0; i < slots.length; i++) {
String s = slots[i];
if (s != null && !s.isEmpty())
System.err.print("," + i++ + "=" + s);
}
System.err.println();
}
if (code.equals("#")) {
return Escape.NEXT_LINE;
}
else if (code.startsWith("#*")) {
String addr = code.substring(2);
jump(addr);
return Escape.ESCAPE;
}
else if (code.startsWith("*")) { // TODO muuttujaviittaukset ja taivutusmuodot sekä mystiset huutomerkit
String addr = code.substring(1);
jump(addr);
}
else if (code.matches("'[0-9]+\\*[0-9]+")) {
// TODO
}
else if (code.equals("??")) {
System.out.println(out);
out = "";
in = readLine();
}
else if (code.equals(":ZAP")) {
slots = new String[255];
}
else if (code.equals(":F=0")) {
selWord=0;
}
else if (code.equals(":F+1")) {
selWord++;
}
else if (code.equals(":F-1")) {
selWord--;
}
else if (code.equals("D")) {
// ????
}
else if (code.startsWith(">")) {
int slot = Integer.parseInt(code.substring(1, code.indexOf('=')));
String[] values = code.substring(code.indexOf('=')+1).split(",");
String ans = "";
for (String value : values) {
ans += " ";
if (value.equals("F")) {
String[] words = in.split(" ");
ans += selWord >= 1 && words.length > selWord-1 ? words[selWord-1] : "";
}
else if (value.equals("R")) {
String[] words = in.split(" ");
for (int i = selWord; i < words.length; i++) {
if (i != selWord) ans += " ";
ans += words[i];
}
}
else if (value.equals("L")) {
String[] words = in.split(" ");
for (int i = 0; i < selWord-1; i++) {
if (i != 0) ans += " ";
ans += words[i];
}
}
else if (value.matches("[0-9]+")) {
int slotid = Integer.parseInt(value);
ans = slots[slotid] != null ? slots[slotid] : "";
}
else ans += value;
}
slots[slot] = ans.trim();
}
else if (code.startsWith("$")) {
int slot = Integer.parseInt(code.substring(1));
return runInstruction(slots[slot] != null ? slots[slot] : "");
}
else if (code.length() > 1 && code.startsWith("?")) {
String condition = code.substring(1);
boolean not = condition.startsWith("-:");
if (not) condition = condition.substring(2);
String[] words = in.split(" ");
boolean ans;
if (condition.equals("CAP")) {
ans = false;
for (int i = 0; i < words.length; i++) {
if (Character.isUpperCase(words[i].charAt(0))) {
if (!ans) selWord = i+1;
ans = true;
}
}
}
else if (condition.equals("CAP+1")) {
ans = in.length() > 0 ? Character.isUpperCase(in.charAt(0)) : false;
}
else if (condition.contains("=")) {
String[] operands = condition.split("=");
int slot = Integer.parseInt(operands[0]);
if (slots[slot] == null) slots[slot] = "";
if (operands.length == 1) {
ans = slots[slot].isEmpty();
}
else if (operands[1].matches("[0-9]+")) {
ans = slots[slot].equalsIgnoreCase(slots[Integer.parseInt(operands[1])]);
}
else {
ans = slots[slot].equalsIgnoreCase(operands[1].replaceAll(",", " ").trim());
}
}
else {
String[] matches = condition.split(",");
ans = false;
for (String match : matches) {
for (int i = 0; i < words.length; i++) {
if (match.equalsIgnoreCase(words[i])) {
selWord = i+1;
ans = true;
}
}
}
}
accumulator = not ^ ans;
}
else if (code.startsWith("/")) {
if (accumulator) {
return runInstruction(code.substring(1));
}
}
else if (code.startsWith("\\")) {
if (!accumulator) {
return runInstruction(code.substring(1));
}
}
else if (code.equals("")) {
// ei mitään
}
else if (code.startsWith("<")) {
out += code.substring(1);
}
else {
if (out.length() > 0) out += " ";
out += code;
}
return Escape.NEXT_COMMAND;
}
private void jump(String addr) {
String secidstr = "";
while (addr.length() > 0 && Character.isDigit(addr.charAt(0))) {
secidstr += addr.substring(0, 1); addr = addr.substring(1);
}
int secid = Integer.parseInt(secidstr);
start(secid, addr);
}
public void loadScript(String filename) throws IOException {
File file = new File(filename);
BufferedReader reader = new BufferedReader(new FileReader(file));
String name = reader.readLine();
int idcounter = Integer.parseInt(reader.readLine().trim());
int sections = Integer.parseInt(reader.readLine().trim());
int size = Integer.parseInt(reader.readLine().trim());
System.err.println("Reading " + name + " (" + size + " lines)");
List<CodeSection> seclist = new ArrayList<>();
{
for (int i = 0; i < sections; i++) {
String secname = reader.readLine();
int secid = idcounter++;
int sectype = Integer.parseInt(reader.readLine().trim());
int secsize = Integer.parseInt(reader.readLine().trim());
System.err.println("Registering *" + secid + " (" + secsize + " lines)");
CodeSection section = new CodeSection(secname, sectype, secsize);
seclist.add(RacterInterpreter.this.sections[secid] = section);
}
for (CodeSection sec : seclist) {
for (int i = 0; i < sec.getSize(); i++) {
String line = reader.readLine();
String linename = line.substring(0, line.indexOf(' '));
String linecode = line.substring(line.indexOf(' ')+1, line.length());
sec.putLine(linename, linecode);
System.err.println("" + sec.name + " : " + line);
}
}
}
reader.close();
}
}
|
package GUI;
import file_operations.ShowRecordDialog;
import object_type.Animal;
import object_type.Point;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import javax.swing.filechooser.*;
/*
主JFrame窗口类
*/
public class ChangeAnimalWindow extends JFrame implements ActionListener {
int amountOfAnimal = 6;
int distance = 80;
Animal[] animal;
object_type.Point[] point;
HandleMouse handleMouse;
File leftImageFile, rightImageFile;
File fileOneGrade, fileTwoGrade, fileThreeGrade;
JButton renew, quit;
JMenuBar bar;
JMenu menuGrade, menuImage, menuHero, menuabout;
JMenuItem oneGradeResult, twoGradeResult, threeGradeResult;
JMenuItem oneGradeItem, twoGradeItem, threeGradeItem;
JMenuItem leftIamge, rightIamge, defaultImage;
JMenuItem about, rules;
JPanel pCenter;
ShowRecordDialog showDiolag;
ChangeAnimalWindow() {
//定义英雄榜数据储存文件对象
fileOneGrade = new File("resource/初级英雄排行榜.txt");
fileTwoGrade = new File("resource/中级英雄排行榜.txt");
fileThreeGrade = new File("resource/高级英雄排行榜.txt");
//中间容器
pCenter = new JPanel();
pCenter.setBackground(Color.white);
pCenter.setLayout(null);
handleMouse = new HandleMouse();
//todo 指定默认动物图片目录
leftImageFile = new File("resource/cat.jpg");
rightImageFile = new File("resource/dog.jpg");
this.init();
//菜单栏
bar = new JMenuBar();
menuGrade = new JMenu("选择游戏难度");
menuImage = new JMenu("自定义择动物图像");
menuHero = new JMenu("英雄榜(排行榜)");
menuabout = new JMenu("关于");
oneGradeItem = new JMenuItem("初 级");
twoGradeItem = new JMenuItem("中 级");
threeGradeItem = new JMenuItem("高 级");
leftIamge = new JMenuItem("左面动物的图像");
rightIamge = new JMenuItem("右面动物的图像");
defaultImage = new JMenuItem("回恢复默认图像");
oneGradeResult = new JMenuItem("初级英雄榜");
twoGradeResult = new JMenuItem("中级英雄榜");
threeGradeResult = new JMenuItem("高级英雄榜");
rules = new JMenuItem("游戏规则");
about = new JMenuItem("制作说明");
menuGrade.add(oneGradeItem);
menuGrade.add(twoGradeItem);
menuGrade.add(threeGradeItem);
menuImage.add(leftIamge);
menuImage.add(rightIamge);
menuImage.add(defaultImage);
menuHero.add(oneGradeResult);
menuHero.add(twoGradeResult);
menuHero.add(threeGradeResult);
menuabout.add(rules);
menuabout.add(about);
bar.add(menuGrade);
bar.add(menuImage);
bar.add(menuHero);
bar.add(menuabout);
this.setJMenuBar(bar);
menuabout.addActionListener(this);
oneGradeItem.addActionListener(this);
twoGradeItem.addActionListener(this);
threeGradeItem.addActionListener(this);
leftIamge.addActionListener(this);
rightIamge.addActionListener(this);
defaultImage.addActionListener(this);
oneGradeResult.addActionListener(this);
twoGradeResult.addActionListener(this);
threeGradeResult.addActionListener(this);
rules.addActionListener(this);
about.addActionListener(this);
//JPanel容器中按钮
renew = new JButton("重新开始");
renew.addActionListener(this);
quit = new JButton("撤消");
quit.addActionListener(this);
JPanel north = new JPanel();
north.add(renew);
north.add(quit);
//在JFrame窗口底部添加按钮
this.add(north, BorderLayout.AFTER_LAST_LINE);
//动物图片
this.add(pCenter, BorderLayout.CENTER);
//将容纳计时器的窗口添加到顶部
JPanel south = new JPanel();
south.add(handleMouse);
this.add(south, BorderLayout.NORTH);
//todo Frame窗体属性设置
this.setVisible(true);
this.setTitle("AnimalJump");
this.setBackground(Color.white);
this.setBounds(600, 400, 710, 300);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (!fileOneGrade.exists()) {
try {
fileOneGrade.createNewFile();
} catch (IOException ignored) {
}
}
if (!fileTwoGrade.exists()) {
try {
fileTwoGrade.createNewFile();
} catch (IOException ignored) {
}
}
if (!fileThreeGrade.exists()) {
try {
fileThreeGrade.createNewFile();
} catch (IOException ignored) {
}
}
handleMouse.gradeFile = fileOneGrade;
showDiolag = new ShowRecordDialog();
}
//todo 游戏核心代码
public void init() {
animal = new Animal[amountOfAnimal];
point = new object_type.Point[amountOfAnimal + 1];
int space = distance;
for (int i = 0; i < point.length; i++) {
point[i] = new object_type.Point(space, 100);
space = space + distance;
}
for (int i = 0; i < animal.length; i++) {
animal[i] = new Animal();
animal[i].addMouseListener(handleMouse);
if (i < animal.length / 2) {
animal[i].setIsLeft(true);
} else {
animal[i].setIsLeft(false);
}
}
for (int i = 0; i < animal.length; i++) {
animal[i].setSize(distance * 6 / 7, distance * 3 / 4);
int w = animal[i].getBounds().width;
int h = animal[i].getBounds().height;
pCenter.add(animal[i]);
if (i < animal.length / 2) {
animal[i].setIsLeft(true);
animal[i].setLeftImage(leftImageFile);
animal[i].repaint();
animal[i].setLocation(point[i].getX() - w / 2, point[i].getY() - h);
animal[i].setAtPoint(point[i]);
point[i].setThisAnimal(animal[i]);
point[i].setIsHaveAnimal(true);
} else {
animal[i].setIsLeft(false);
animal[i].setRightImage(rightImageFile);
animal[i].repaint();
animal[i].setLocation(point[i + 1].getX() - w / 2, point[i + 1].getY() - h);
animal[i].setAtPoint(point[i + 1]);
point[i + 1].setThisAnimal(animal[i]);
point[i + 1].setIsHaveAnimal(true);
}
}
handleMouse.setPoint(point);
handleMouse.setCountTime(true);
}
public void setAmountOfAnimal(int m) {
if (m >= 2 && m % 2 == 0)
amountOfAnimal = m;
}
public void removeAnimal() {
for (Point value : point) {
if (value.getThisAnimal() != null)
pCenter.remove(value.getThisAnimal());
}
pCenter.validate();
pCenter.repaint();
}
//重开
public void needDoing() {
init();
handleMouse.initStep();
handleMouse.initSpendTime();
handleMouse.setCountTime(true);
}
//todo 鼠标监听事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == oneGradeItem) {
handleMouse.gradeFile = fileOneGrade;
distance = 80;
removeAnimal();
setAmountOfAnimal(6);
needDoing();
} else if (e.getSource() == twoGradeItem) {
handleMouse.gradeFile = fileTwoGrade;
distance = 70;
removeAnimal();
setAmountOfAnimal(8);
needDoing();
} else if (e.getSource() == threeGradeItem) {
handleMouse.gradeFile = fileThreeGrade;
distance = 60;
removeAnimal();
setAmountOfAnimal(10);
needDoing();
} else if (e.getSource() == about) {
JOptionPane.showMessageDialog(null, "这个动物移动小游戏来自银牌混子倾情制作");
} else if (e.getSource() == renew) {//重新开始
removeAnimal();
needDoing();
} else if (e.getSource() == rules) {//游戏规则
JOptionPane.showMessageDialog(null, "1.游戏目标:将所有左边的动物和右边的动物交换位置\n" +
"2.每次每个动物只能移动一格或者跳过一个动物,不能移动多个格子或者跳过空格和多个动物\n" +
"3.点击动物图片开始游戏并自动计时");
} else if (e.getSource() == quit) {//撤销
ArrayList<Integer> step = handleMouse.getStep();
int length = step.size();
int start = -1, end = -1;
if (length >= 2) {
end = step.get(length - 1);
start = step.get(length - 2);
step.remove(length - 1);
step.remove(length - 2);
Animal ani = point[end].getThisAnimal();
int w = ani.getBounds().width;
int h = ani.getBounds().height;
ani.setLocation(point[start].getX() - w / 2, point[start].getY() - h);
ani.setAtPoint(point[start]);
point[start].setThisAnimal(ani);
point[start].setIsHaveAnimal(true);
point[end].setIsHaveAnimal(false);
}
} else if (e.getSource() == leftIamge) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int state = chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
if (file != null && state == JFileChooser.APPROVE_OPTION) {
leftImageFile = file;
for (Animal value : animal) {
if (value.getIsLeft()) {
value.setLeftImage(leftImageFile);
value.repaint();
}
}
}
} else if (e.getSource() == rightIamge) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int state = chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
if (file != null && state == JFileChooser.APPROVE_OPTION) {
rightImageFile = file;
for (Animal value : animal) {
if (!value.getIsLeft()) {
value.setRightImage(rightImageFile);
value.repaint();
}
}
}
} else if (e.getSource() == defaultImage) {
leftImageFile = new File("resource/dog.jpg");
rightImageFile = new File("resource/cat.jpg");
for (Animal value : animal) {
if (value.getIsLeft())
value.setLeftImage(leftImageFile);
else
value.setRightImage(rightImageFile);
value.repaint();
}
} else if (e.getSource() == oneGradeResult) {
showDiolag.setGradeFile(fileOneGrade);
showDiolag.showRecord();
showDiolag.setVisible(true);
} else if (e.getSource() == twoGradeResult) {
showDiolag.setGradeFile(fileTwoGrade);
showDiolag.showRecord();
showDiolag.setVisible(true);
} else if (e.getSource() == threeGradeResult) {
showDiolag.setGradeFile(fileThreeGrade);
showDiolag.showRecord();
showDiolag.setVisible(true);
}
this.validate();
}
} |
package com.jpeng.demo.clock;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.githang.statusbar.StatusBarCompat;
import com.jpeng.demo.ActivityCollector;
import com.jpeng.demo.MyApplication;
import com.jpeng.demo.R;
import com.jpeng.demo.WheelView;
import java.util.ArrayList;
import java.util.List;
public class AddRemind extends AppCompatActivity implements View.OnClickListener {
RelativeLayout toolbarLin;
LinearLayout back;
TextView title,showType,showThing,inContent,showRingtone,showFrequency;
RelativeLayout remindThing,remindType,remindRingtone,remindFrequency;
ImageView play,save;
Dialog dialog;
WheelView morning,hour,minu;
Clock clock=new Clock();
AlarmManager manager;
boolean isType=false,isThing=false,isR=false,isF=false,isTime=false;
private LocalBroadcastManager localBroadcastManager;
private List<String> hours=new ArrayList<>();
private List<String> minus=new ArrayList<>();
private List<String> timetypes=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_remind);
ActivityCollector.addActivity(this);
localBroadcastManager=LocalBroadcastManager.getInstance(this);
manager=(AlarmManager)getSystemService(ALARM_SERVICE);
StatusBarCompat.setStatusBarColor(this, MyApplication.getPeople().getToolbarColor(), false);
toolbarLin=(RelativeLayout)findViewById(R.id.toolbar_lin);
toolbarLin.setBackgroundColor(MyApplication.getPeople().getToolbarColor());
title=(TextView)findViewById(R.id.title_tooolbar);
title.setText("新建提醒");
back=(LinearLayout) findViewById(R.id.back_toolbar);
back.setOnClickListener(this);
play=(ImageView)findViewById(R.id.play_toolbar);
save=(ImageView)findViewById(R.id.save_toolbar);
play.setVisibility(View.GONE);
save.setImageResource(R.drawable.save_white);
save.setOnClickListener(this);
morning=(WheelView)findViewById(R.id.wheel_morning);
hour=(WheelView)findViewById(R.id.wheel_hour);
minu=(WheelView)findViewById(R.id.wheel_minute);
remindThing=(RelativeLayout)findViewById(R.id.remind_rela);
remindType=(RelativeLayout)findViewById(R.id.remind_type);
remindRingtone=(RelativeLayout)findViewById(R.id.remind_ringtone);
remindFrequency=(RelativeLayout)findViewById(R.id.remind_frequency);
showThing=(TextView)findViewById(R.id.thing_text);
showType=(TextView)findViewById(R.id.Type_text);
showRingtone=(TextView)findViewById(R.id.ringtone_text) ;
showFrequency=(TextView)findViewById(R.id.frequency_text) ;
remindThing.setOnClickListener(this);
remindType.setOnClickListener(this);
remindRingtone.setOnClickListener(this);
remindFrequency.setOnClickListener(this);
remindThing.setVisibility(View.GONE);
remindRingtone.setVisibility(View.GONE);
remindFrequency.setVisibility(View.GONE);
setList();
morning.setData((ArrayList<String>) timetypes);
hour.setData((ArrayList<String>) hours);
minu.setData((ArrayList<String>) minus);
if (Integer.valueOf(Tool.getStrNow()[0])<13){
morning.setDefault(0);
}else {
morning.setDefault(1);
}
hour.setDefault(Integer.valueOf(Tool.getStrNow()[0]));
minu.setDefault(Integer.valueOf(Tool.getStrNow()[1]));
morning.setOnSelectListener(new WheelView.OnSelectListener() {
@Override
public void endSelect(int id, String text) {
}
@Override
public void selecting(int id, String text) {
}
});
hour.setOnSelectListener(new WheelView.OnSelectListener() {
@Override
public void endSelect(int id, String text) {
clock.setHour(text);
isTime=true;
}
@Override
public void selecting(int id, String text) {
if (id>=13){
morning.setDefault(1);
}else {
morning.setDefault(0);
}
}
});
minu.setOnSelectListener(new WheelView.OnSelectListener() {
@Override
public void endSelect(int id, String text) {
clock.setMinute(text);
isTime=true;
}
@Override
public void selecting(int id, String text) {
}
});
}
private void setList() {
timetypes.add("上午");
timetypes.add("下午");
for (int i=0;i<24;i++){
if (i<10){
hours.add("0"+String.valueOf(i));
}else {
hours.add(String.valueOf(i));
}
}
for (int i=0;i<60;i++){
if (i<10){
minus.add("0"+String.valueOf(i));
}else {
minus.add(String.valueOf(i));
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back_toolbar:
ActivityCollector.removeActivity(this);
finish();
break;
case R.id.save_toolbar:
setSave();
break;
case R.id.remind_rela:
setRemindThing();
break;
case R.id.determine_button:
showThing.setText(inContent.getText().toString());
clock.setRemindThing(inContent.getText().toString());
isThing=true;
dialog.dismiss();
break;
case R.id.remind_type:
setRemindType();
break;
case R.id.remind_frequency:
setRemindFrequency();
break;
case R.id.remind_ringtone:
setRemindRingtone();
break;
default: break;
}
}
private void setSave(){
if (isTime){
if (clock.getHour()==null){
clock.setHour(Tool.getStrNow()[0]);
}
if (clock.getMinute()==null){
clock.setMinute(Tool.getStrNow()[1]);
}
if (isType){
if (clock.isClock()){
if (isR&&isF)
{
successSet();
}else {
Toast.makeText(MyApplication.getContext(),"请完善闹钟信息!",Toast.LENGTH_SHORT).show();
}
}else {
if (isThing){
successSet();
}else {
Toast.makeText(MyApplication.getContext(),"请填写提醒事件!",Toast.LENGTH_SHORT).show();
}
}
}else {
Toast.makeText(MyApplication.getContext(),"请选择提醒类型!",Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(MyApplication.getContext(),"请确定提醒时间!",Toast.LENGTH_SHORT).show();
}
}
private void successSet(){
clock.setId(Tool.getAllNum());
Tool.setAllNum(Tool.getAllNum()+1);
Tool.getClocks().add(clock);
Tool.setRemindNum(Tool.getRemindNum()+1);
long time=0;
int clockHour=Integer.valueOf(clock.getHour());
int clockMinute=Integer.valueOf(clock.getMinute());
if (clockHour>=Integer.valueOf(Tool.getStrNow()[0])){
if (clockHour==Integer.valueOf(Tool.getStrNow()[0])){
time=SystemClock.elapsedRealtime()+(clockMinute-Integer.valueOf(Tool.getStrNow()[1])-1)*60*1000+(60-Integer.valueOf(Tool.getStrNow()[2]))*1000;
}else {
time=SystemClock.elapsedRealtime()+(clockHour-Integer.valueOf(Tool.getStrNow()[0])-1)*3600*1000+(clockMinute+60-Integer.valueOf(Tool.getStrNow()[1])-1)*60*1000+(60-Integer.valueOf(Tool.getStrNow()[2]))*1000;
}
}else {
time=SystemClock.elapsedRealtime()+(clockHour+24-Integer.valueOf(Tool.getStrNow()[0])-1)*3600*1000+(clockMinute+60-Integer.valueOf(Tool.getStrNow()[1])-1)*60*1000+(60-Integer.valueOf(Tool.getStrNow()[2]))*1000;
}
if (clock.isClock()){
setAlarm(time,clock.getId(),false);
}else {
setAlarm(time,clock.getId(),true);
}
Intent intent=new Intent("com.jpeng.demo.REMIND");
localBroadcastManager.sendBroadcast(intent);
ActivityCollector.removeActivity(this);
finish();
}
private void setAlarm(long time,int count,boolean isRemind){
if (isRemind){
Intent intent1=new Intent(this,NotificationService.class);
intent1.putExtra("count",count);
PendingIntent pi=PendingIntent.getService(this,count,intent1,0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,time,pi);
}
}else {
Intent intent1=new Intent(this,PlayRingtoneService.class);
intent1.putExtra("count",count);
PendingIntent pi=PendingIntent.getService(this,count,intent1,0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,time,pi);
}
}
}
private void setRemindThing() {
dialog = new Dialog(this,R.style.ActionSheetDialogStyle);
//填充对话框的布局
final View inflate = LayoutInflater.from(this).inflate(R.layout.in_content, null);
//初始化控件
final Button determineButton=(Button)inflate.findViewById(R.id.determine_button);
TextView titleContent=(TextView)inflate.findViewById(R.id.title_content);
inContent=(EditText)inflate.findViewById(R.id.in_content);
inContent.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) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length()>10){
determineButton.setEnabled(false);
Toast.makeText(MyApplication.getContext(),"不可超过十个字",Toast.LENGTH_SHORT).show();
}else {
determineButton.setEnabled(true);
}
}
});
titleContent.setText("提醒事件");
determineButton.setOnClickListener(this);
//将布局设置给Dialog
dialog.setContentView(inflate);
//获取当前Activity所在的窗体
Window dialogWindow = dialog.getWindow();
//设置Dialog从窗体底部弹出
dialogWindow.setGravity( Gravity.CENTER);
//获得窗体的属性
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.y = 20;//设置Dialog距离底部的距离
// 将属性设置给窗体
dialogWindow.setAttributes(lp);
dialog.show();//显示对话框
}
private void setRemindType(){
// 创建对话框构建器
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 设置参数
builder.setTitle("选择提醒类型")
.setSingleChoiceItems(Tool.items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MyApplication.getContext(), Tool.items[which],
Toast.LENGTH_SHORT).show();
showType.setText(Tool.items[which]);
if (which==0){
clock.setClock(false);
remindThing.setVisibility(View.VISIBLE);
remindRingtone.setVisibility(View.GONE);
remindFrequency.setVisibility(View.GONE);
}else {
clock.setClock(true);
remindRingtone.setVisibility(View.VISIBLE);
remindFrequency.setVisibility(View.VISIBLE);
remindThing.setVisibility(View.GONE);
}
dialog.dismiss();
isType=true;
}
});
builder.create().show();
}
private void setRemindRingtone(){
// 创建对话框构建器
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 设置参数
builder.setTitle("选择闹钟铃声")
.setSingleChoiceItems(Tool.itemsR, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MyApplication.getContext(), Tool.itemsR[which],
Toast.LENGTH_SHORT).show();
showRingtone.setText(Tool.itemsR[which]);
Tool.setClockR(which);
clock.setRmindR(which);
Ringtone ringtone=Tool.getRingtones().get(which);
clock.setRingtone(ringtone);
dialog.dismiss();
isR=true;
}
});
builder.create().show();
}
private void setRemindFrequency(){
// 创建对话框构建器
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 设置参数
builder.setTitle("选择闹钟频率")
.setSingleChoiceItems(Tool.itemsF, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(MyApplication.getContext(), Tool.itemsF[which],
Toast.LENGTH_SHORT).show();
showFrequency.setText(Tool.itemsF[which]);
Tool.setClockF(which);
clock.setRemindF(which);
dialog.dismiss();
isF=true;
}
});
builder.create().show();
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
|
package com.mecha.niko;
import java.util.Collection;
public class BattlePlatformOmega implements HeavyMecha, BattleMecha {
private MechaPilot pilot;
private Collection<Gun> manyGunz;
private EnergyShieldGenerator generator;
public BattlePlatformOmega(MechaPilot pilot, EnergyShieldGenerator generator) {
this.pilot = pilot;
this.generator = generator;
}
@Override
public void shoot() {
for (Gun gun : manyGunz) {
gun.shoot();
}
}
@Override
public void reload() {
for (Gun gun : manyGunz) {
gun.reload();
}
}
@Override
public void activateBarrier() {
generator.activateGenerator();
}
@Override
public void heavyStomp() {
System.out.println("Earth trembles as the Battle Platform Omega stomps.");
}
@Override
public void walk() {
System.out.println("Each step of Battle Platform Omega makes causes a little earthquake.");
}
@Override
public void turn() {
System.out.println("Battle Platform Omega turns.");
}
@Override
public void stop() {
System.out.println("Battle Platform Omega stops.");
}
@Override
public void honk() {
System.out.println("Battle Platform Omega makes a very loud sound.");
}
@Override
public void getPilotData() {
System.out.println(pilot.toString());
}
public void setManyGunz(Collection<Gun> manyGunz) {
this.manyGunz = manyGunz;
}
}
|
package com.cdgpacific.sellercatpal;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
static final String ACTION_SCAN = "com.google.zxing.client.android.SCAN";
private ProgressDialog pDialog;
public SQLiteDatabase sqlDB;
public MySqlLite mysql;
public String MESSAGE = null;
public View _VIEW;
TextView a, b, c, d, e, f;
String URL = ""; //http://cheappartsguy.com:8090/api/summary/seller_dashboard_mobile/795edd365fd0e371ceaaf1ddd559a85d/";
ScrollView scrollId;
Button btnBoxInformation, btnLogout, btnViewYard;
Button btnBoxInformation2, btnLogout2, btnViewYard2;
public int ScreenCheckSizeIfUsing10Inches;
public boolean isRefresh = false;
public SwipeRefreshLayout mySwipeRefreshLayout;
public SQLiteDatabase CreatedDB() {
sqlDB = openOrCreateDatabase(MySqlLite.DB_NAME, Context.MODE_PRIVATE, null);
mysql = new MySqlLite(sqlDB);
mysql.execute("DROP TABLE IF EXISTS list_of_boxes;");
return sqlDB;
}
public void InitService() {
CreatedDB();
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, BackgroundService.class);
startService(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
URL = Helpers.Host + "/api/summary/seller_dashboard_mobile/795edd365fd0e371ceaaf1ddd559a85d/";
if(JSONHelper.Seller_UID == null) {
Intent i = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(i);
finish();
return;
}
ScreenCheckSizeIfUsing10Inches = Helpers.getScreenOfTablet(getApplicationContext());
URL = URL + JSONHelper.Seller_UID;
reset_text(false);
btnBoxInformation = (Button) findViewById(R.id.btnBoxInformation);
btnBoxInformation2 = (Button) findViewById(R.id.btnBoxInformation2);
btnBoxInformation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// _VIEW = view;
// ShowBoxViewInformation("Position QR Code completely inside the scanner window. When QR code is recognized you will receive a confirmation screen.", "Scan QR Box Code");
_VIEW = view;
String message_ = "Position QR Code completely inside the scanner window. ";
message_ += "When QR code is recognized you will receive a confirmation screen.\n";
int resize_screen = 400;
if(ScreenCheckSizeIfUsing10Inches == 1) {
resize_screen = 870;
}
else if(ScreenCheckSizeIfUsing10Inches == 2) {
resize_screen = 1160;
}
Log.d("SCREEN_XX", resize_screen + "");
showDialogForDynamic(
MainActivity.this,
"Scan QR Box Code",
message_, resize_screen,
"YES, SCAN BOX QR CODE", "NO, BACK TO DASHBOARD", 2);
}
});
btnBoxInformation2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
_VIEW = view;
ShowBoxViewInformation("Position QR Code completely inside the scanner window. When QR code is recognized you will receive a confirmation screen.", "Scan QR Box Code");
}
});
btnViewYard = (Button) findViewById(R.id.btnViewYard);
btnViewYard2 = (Button) findViewById(R.id.btnViewYard2);
btnViewYard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
open_activity(new Intent(getApplicationContext(), ViewYardNameActivity.class));
}
});
btnViewYard2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
open_activity(new Intent(getApplicationContext(), ViewYardNameActivity.class));
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout2 = (Button) findViewById(R.id.btnLogout2);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JSONHelper.Seller_UID = null;
open_activity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
btnLogout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JSONHelper.Seller_UID = null;
open_activity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
scrollId = (ScrollView) findViewById(R.id.scrollId);
mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
Log.i("REFRESH", "onRefresh called from SwipeRefreshLayout");
new get_seller_dashboard().execute();
}
}
);
boolean IsTablet = Helpers.isTabletDevice(getApplicationContext());
if(IsTablet) {
scrollId.getLayoutParams().height = 450;
btnBoxInformation2.setVisibility(View.INVISIBLE);
btnViewYard2.setVisibility(View.INVISIBLE);
btnLogout2.setVisibility(View.INVISIBLE);
}
else {
btnBoxInformation.setVisibility(View.INVISIBLE);
btnViewYard.setVisibility(View.INVISIBLE);
btnLogout.setVisibility(View.INVISIBLE);
}
new get_seller_dashboard().execute();
}
public void open_activity(Intent intent) {
startActivity(intent);
finish();
}
private void ShowBoxViewInformation(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle(title)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
SCAN_QR_CODE(_VIEW,
"Confirm Box #"
);
}
});
AlertDialog alert = builder.create();
alert.show();
Button bq = alert.getButton(DialogInterface.BUTTON_POSITIVE);
bq.setTextColor(Color.BLACK);
bq.setBackgroundColor(Color.LTGRAY);
}
public void showDialogForQRScanned(Activity activity, String title, String message){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.activity_confirmation_dialog_catpal);
TextView title_dialog = (TextView) dialog.findViewById(R.id.title_dialog);
title_dialog.setText(title);
TextView text_dialog = (TextView) dialog.findViewById(R.id.text_dialog);
text_dialog.setText(message);
Button btn_dialog_YES = (Button) dialog.findViewById(R.id.btn_dialog_YES);
btn_dialog_YES.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
Button btn_dialog_NO = (Button) dialog.findViewById(R.id.btn_dialog_NO);
btn_dialog_NO.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
public void SCAN_QR_CODE(View v, String message) {
try {
_VIEW = v;
MESSAGE = message;
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
} catch (ActivityNotFoundException anfe) {
showDialog(MainActivity.this, "No Scanner Found", "Download a scanner code activity?", "Yes", "No").show();
}
}
public String SCAN_RESULT = null;
public String SCAN_RESULT_FORMAT = null;
public String SCAN_URL = ""; //http://cheappartsguy.com:8090/api/box_information_mobile_v2/795edd365fd0e371ceaaf1ddd559a85d/";
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
SCAN_URL = Helpers.Host + "/api/box_information_mobile_v2/795edd365fd0e371ceaaf1ddd559a85d/";
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
SCAN_RESULT = intent.getStringExtra("SCAN_RESULT");
SCAN_RESULT_FORMAT = intent.getStringExtra("SCAN_RESULT_FORMAT");
int box_uid = 0;
String[] results = null;
try {
results = SCAN_RESULT.split("-");
Helpers.QR_BOX_ID = results[0];
Helpers.QR_BOX_SHOW_ID = results[1];
// box_uid = mysql.findListOfBoxes(Helpers.QR_BOX_ID);
SCAN_URL = SCAN_URL + Helpers.QR_BOX_ID;
Log.d("TYPE: ", SCAN_URL);
new get_box_info().execute();
}
catch (Exception ex) {
Log.d("TYPE: ", ">on " + ex);
}
}
}
}
public class get_box_info extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
loaderShow("Please wait...");
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String json = null;
try {
Thread.sleep(100);
JSONHelper json_help = new JSONHelper();
json = json_help.makeServiceCall(SCAN_URL, JSONHelper.GET);
Log.d("Response: ", "> " + json);
return json;
} catch (InterruptedException e) {
}
// TODO: register the new account here.
return null;
}
@Override
protected void onPostExecute(final String json) {
box_validate(json);
}
}
private void box_validate(String json) {
loaderHide();
if (json != null) {
try
{
JSONObject job = new JSONObject(json);
String member_id = job.getString("seller_name");
Log.d("seller_name: ", member_id);
int uid = Integer.parseInt(member_id);
if(uid > 0) {
if(uid != Integer.parseInt(JSONHelper.Seller_UID)) {
messageAlertMessage("You are not able to view this box#: "+ Helpers.QR_BOX_SHOW_ID + " information.", "INFORMATION");
return;
}
view_box_info(Helpers.QR_BOX_ID);
}
else {
messageAlertMessage("Oops, Invalid QR Code information.", "INFORMATION");
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}
public void view_box_info(String box_uid) {
Log.d("BOX_UID: ", "> " + box_uid);
BoxViewActivity.BOX_UID = box_uid;
Intent intent = new Intent(getApplicationContext(), BoxViewActivity.class);
startActivity(intent);
}
private static AlertDialog showDialog(final Activity act, CharSequence title, CharSequence message, CharSequence buttonYes, CharSequence buttonNo) {
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try {
act.startActivity(intent);
} catch (ActivityNotFoundException anfe) {
}
}
});
downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return downloadDialog.show();
}
public void reset_text(boolean IsTrue) {
if(!IsTrue) {
a = (TextView) findViewById(R.id.numberA);
b = (TextView) findViewById(R.id.numberB);
c = (TextView) findViewById(R.id.numberC);
d = (TextView) findViewById(R.id.numberD);
e = (TextView) findViewById(R.id.numberE);
f = (TextView) findViewById(R.id.numberF);
}
a.setText("***");
b.setText("***");
c.setText("***");
d.setText("***");
e.setText("***");
f.setText("***");
}
public void set_value(String a_, String b_, String c_, String d_, String e_, String f_) {
a.setText(a_);
b.setText(b_);
c.setText(c_);
DecimalFormat formatter = new DecimalFormat("#,###,###.##");
Double x_a = Double.parseDouble(d_);
d.setText("$" + formatter.format(x_a));
Double x_b = Double.parseDouble(e_);
e.setText("$" + formatter.format(x_b));
Double x_c = Double.parseDouble(f_);
f.setText("$" + formatter.format(x_c));
}
public class get_seller_dashboard extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
reset_text(true);
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
String json = null;
try {
Thread.sleep(100);
JSONHelper json_help = new JSONHelper();
json = json_help.makeServiceCall(URL, JSONHelper.GET);
Log.d("Response: ", "> " + json);
Log.d("Response: ", "> " + URL);
return json;
} catch (InterruptedException e) {
}
// TODO: register the new account here.
return null;
}
@Override
protected void onPostExecute(final String json) {
populate_seller_dashboard(json);
}
}
private void populate_seller_dashboard(String json) {
if (json != null) {
try
{
JSONObject job = new JSONObject(json);
String member_id = job.getString("member_id");
Log.d("member_id: ", member_id);
String total_number_of_units = "N/A";
String total_number_of_units_appraised = "N/A";
String total_number_of_units_need_to_appraised = "N/A";
String avg_price_per_unit_of_appraised_units = "0";
String total_appraisal_value = "0";
int IsPassed = Integer.parseInt(member_id);
if(IsPassed > 0) {
total_number_of_units = job.getString("total_number_of_units");
total_number_of_units_appraised = job.getString("total_number_of_units_appraised");
total_number_of_units_need_to_appraised = job.getString("total_number_of_units_need_to_appraised");
avg_price_per_unit_of_appraised_units = job.getString("avg_price_per_unit_of_appraised_units");
total_appraisal_value = job.getString("total_appraisal_value");
}
set_value(
total_number_of_units,
total_number_of_units_appraised,
total_number_of_units_need_to_appraised,
avg_price_per_unit_of_appraised_units,
total_appraisal_value,
total_appraisal_value
);
}catch(Exception e)
{
e.printStackTrace();
}
}
mySwipeRefreshLayout.setRefreshing(false);
}
private void messageAlert(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle(title)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void messageAlertMessage(String message, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle(title)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void showDialogForDynamic(Activity activity, String caption, String message, int height, String yes_button, String no_button, final int number){
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.activity_custom_dialog);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.height = height;
TextView title_dialog = (TextView) dialog.findViewById(R.id.title_dialog);
TextView title_message = (TextView) dialog.findViewById(R.id.title_message);
TextView screen_code = (TextView) dialog.findViewById(R.id.screen_code);
Button btn_dialog_YES = (Button) dialog.findViewById(R.id.btn_dialog_YES);
Button btn_dialog_NO = (Button) dialog.findViewById(R.id.btn_dialog_NO);
title_dialog.setText(caption);
title_message.setText(message);
screen_code.setText("MS-" + number);
btn_dialog_YES.setText(yes_button);
btn_dialog_NO.setText(no_button);
btn_dialog_YES.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
if(number == 2) {
SCAN_QR_CODE(_VIEW,
"Confirm Box #"
);
}
}
});
btn_dialog_NO.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
}
private void loaderShow(String Message)
{
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Message);
pDialog.setCancelable(false);
pDialog.show();
}
private void loaderHide(){
if (pDialog.isShowing())
pDialog.dismiss();
}
}
|
package com.example.shouhei.mlkitdemo.runs;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.example.shouhei.mlkitdemo.SingleFragmentActivity;
public class RunsActivity extends SingleFragmentActivity {
private static final String TAG = "RunsActivity";
@Override
protected Fragment createFragment() {
return new RunsFragment();
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
|
package com.itsoul.lab.generalledger.entities;
import com.it.soul.lab.sql.entity.Entity;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Map;
/**
* @author towhid
* @since 19-Aug-19
*/
public class LedgerEntity extends Entity implements Externalizable {
@Override
public void writeExternal(ObjectOutput out) throws IOException {
Map<String, Object> data = marshallingToMap(true);
out.writeObject(data);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
Object data = in.readObject();
if (data instanceof Map){
Map<String, Object> rdData = (Map) data;
unmarshallingFromMap(rdData, true);
}
}
}
|
package com.example.tabviewtest2;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
//使用fragment方法实现
//但是不能左右移动
public class MainActivity extends FragmentActivity implements OnClickListener {
private LinearLayout mlayout1;
private LinearLayout mlayout2;
private LinearLayout mlayout3;
private LinearLayout mlayout4;
private Fragment mTab01, mTab02, mTab03, mTab04;
private ImageButton mbtn1, mbtn2, mbtn3, mbtn4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initView();
initEvent();
// 默认显示第一个
setSelect(0);
}
private void initEvent() {
// TODO Auto-generated method stub
mbtn1.setOnClickListener(this);
mbtn2.setOnClickListener(this);
mbtn3.setOnClickListener(this);
mbtn4.setOnClickListener(this);
}
private void initView() {
// TODO Auto-generated method stub
mlayout1 = (LinearLayout) findViewById(R.id.layout_1);
mlayout2 = (LinearLayout) findViewById(R.id.layout_2);
mlayout3 = (LinearLayout) findViewById(R.id.layout_3);
mlayout4 = (LinearLayout) findViewById(R.id.layout_4);
mbtn1 = (ImageButton) findViewById(R.id.btn_1);
mbtn2 = (ImageButton) findViewById(R.id.btn_2);
mbtn3 = (ImageButton) findViewById(R.id.btn_3);
mbtn4 = (ImageButton) findViewById(R.id.btn_4);
}
private void setSelect(int i) {
// 图片设置为亮,设置内容区域
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
hideFragment(transaction);
switch (i) {
case 0:
if (mTab01 == null) {
mTab01 = new lauout1Fragment();
transaction.add(R.id.id_content, mTab01);
} else {
transaction.show(mTab01);
}
mbtn1.setImageResource(R.drawable.tab_address_pressed);
break;
case 1:
if (mTab02 == null) {
mTab02 = new lauout2Fragment();
transaction.add(R.id.id_content, mTab02);
} else {
transaction.show(mTab02);
}
mbtn2.setImageResource(R.drawable.tab_find_frd_pressed);
break;
case 2:
if (mTab03 == null) {
mTab03 = new lauout3Fragment();
transaction.add(R.id.id_content, mTab03);
} else {
transaction.show(mTab03);
}
mbtn3.setImageResource(R.drawable.tab_settings_pressed);
break;
case 3:
if (mTab04 == null) {
mTab04 = new lauout4Fragment();
transaction.add(R.id.id_content, mTab04);
} else {
transaction.show(mTab04);
}
mbtn4.setImageResource(R.drawable.tab_weixin_pressed);
break;
default:
break;
}
transaction.commit();
}
private void hideFragment(FragmentTransaction transaction) {
// TODO Auto-generated method stub
if (mTab01 != null) {
transaction.hide(mTab01);
}
if (mTab02 != null) {
transaction.hide(mTab02);
}
if (mTab03 != null) {
transaction.hide(mTab03);
}
if (mTab04 != null) {
transaction.hide(mTab04);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
resetImg();
switch (v.getId()) {
case R.id.btn_1:
setSelect(0);
break;
case R.id.btn_2:
setSelect(1);
break;
case R.id.btn_3:
setSelect(2);
break;
case R.id.btn_4:
setSelect(3);
break;
default:
break;
}
}
private void resetImg() {
// TODO Auto-generated method stub
mbtn1.setImageResource(R.drawable.tab_address_normal);
mbtn2.setImageResource(R.drawable.tab_find_frd_normal);
mbtn3.setImageResource(R.drawable.tab_settings_normal);
mbtn4.setImageResource(R.drawable.tab_weixin_normal);
}
}
|
package com.yunwa.aggregationmall.pojo.pdd.po;
public class PddOptId {
private Integer id; //主键
private Long opt_id; //类目id
private Integer total_goods_count; //商品总数量
private Integer total_page_count; //总页数
private Integer current_page; //当前页
private Integer is_going; //该是否在爬取商品中,1是,0不是
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Long getOpt_id() {
return opt_id;
}
public void setOpt_id(Long opt_id) {
this.opt_id = opt_id;
}
public Integer getTotal_goods_count() {
return total_goods_count;
}
public void setTotal_goods_count(Integer total_goods_count) {
this.total_goods_count = total_goods_count;
}
public Integer getTotal_page_count() {
return total_page_count;
}
public void setTotal_page_count(Integer total_page_count) {
this.total_page_count = total_page_count;
}
public Integer getCurrent_page() {
return current_page;
}
public void setCurrent_page(Integer current_page) {
this.current_page = current_page;
}
public Integer getIs_going() {
return is_going;
}
public void setIs_going(Integer is_going) {
this.is_going = is_going;
}
} |
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.servlet.result;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.StubMvcResult;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
*/
class ContentResultMatchersTests {
@Test
void typeMatches() throws Exception {
new ContentResultMatchers().contentType(APPLICATION_JSON_VALUE).match(getStubMvcResult(CONTENT));
}
@Test
void typeNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().contentType("text/plain").match(getStubMvcResult(CONTENT)));
}
@Test
void string() throws Exception {
new ContentResultMatchers().string(new String(CONTENT.getBytes(UTF_8))).match(getStubMvcResult(CONTENT));
}
@Test
void stringNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().encoding("bogus").match(getStubMvcResult(CONTENT)));
}
@Test
void stringMatcher() throws Exception {
String content = new String(CONTENT.getBytes(UTF_8));
new ContentResultMatchers().string(Matchers.equalTo(content)).match(getStubMvcResult(CONTENT));
}
@Test
void stringMatcherNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().string(Matchers.equalTo("bogus")).match(getStubMvcResult(CONTENT)));
}
@Test
void bytes() throws Exception {
new ContentResultMatchers().bytes(CONTENT.getBytes(UTF_8)).match(getStubMvcResult(CONTENT));
}
@Test
void bytesNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().bytes("bogus".getBytes()).match(getStubMvcResult(CONTENT)));
}
@Test
void jsonLenientMatch() throws Exception {
new ContentResultMatchers().json("{\n \"foo\" : \"bar\" \n}").match(getStubMvcResult(CONTENT));
new ContentResultMatchers().json("{\n \"foo\" : \"bar\" \n}", false).match(getStubMvcResult(CONTENT));
}
@Test
void jsonStrictMatch() throws Exception {
new ContentResultMatchers().json("{\n \"foo\":\"bar\", \"foo array\":[\"foo\",\"bar\"] \n}", true).match(getStubMvcResult(CONTENT));
new ContentResultMatchers().json("{\n \"foo array\":[\"foo\",\"bar\"], \"foo\":\"bar\" \n}", true).match(getStubMvcResult(CONTENT));
}
@Test
void jsonLenientNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\n\"fooo\":\"bar\"\n}").match(getStubMvcResult(CONTENT)));
}
@Test
void jsonStrictNoMatch() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
new ContentResultMatchers().json("{\"foo\":\"bar\", \"foo array\":[\"bar\",\"foo\"]}", true).match(getStubMvcResult(CONTENT)));
}
@Test // gh-23622
void jsonUtf8Match() throws Exception {
new ContentResultMatchers().json("{\"name\":\"Jürgen\"}").match(getStubMvcResult(UTF8_CONTENT));
}
private static final String CONTENT = "{\"foo\":\"bar\",\"foo array\":[\"foo\",\"bar\"]}";
private static final String UTF8_CONTENT = "{\"name\":\"Jürgen\"}";
private StubMvcResult getStubMvcResult(String content) throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", APPLICATION_JSON_VALUE);
response.getOutputStream().write(content.getBytes(UTF_8));
return new StubMvcResult(null, null, null, null, null, null, response);
}
}
|
package com.nikita.recipiesapp.common.models;
public final class Ingredient {
public final int quantity;
public final String measure;
public final String ingredient;
public final String description;
public Ingredient(int quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
this.description = ingredient + ", " + quantity + " " + measure;
}
}
|
import java.awt.Rectangle;
import java.awt.Graphics;
public class PlayerBullet extends Rectangle {
Screen screen;
int speed = 3;
public PlayerBullet(int xCor, int yCor, Screen screen) {
this.screen = screen;
setBounds(xCor,yCor,5,10);
}
public void render(Graphics graphics) {
graphics.fillRect(x, y, width, height);
}
public void update() {
this.y -= 1 * speed;
}
public Rectangle receiveBounds() {
return new Rectangle(x,y,width,height);
}
} |
package app.datacollect.twitchdata.feed.events;
import org.json.JSONObject;
public abstract class EventData {
public abstract EventType getEventType();
public abstract ObjectType getObjectType();
public abstract Version getVersion();
public abstract JSONObject toJson();
}
|
package com.everis.person.entity;
import lombok.Builder;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;
@Data
@Document
@Builder
public class Payment {
@Id
private UUID id;
private Person personRec;
private Date createDate;
private BigDecimal amountPayment;
}
|
import java.util.Scanner;
public class Homework035 {
public static void main(String[] args) {
// even and odd
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int number = input.nextInt();
int remainder;
remainder=number%2;
if (remainder==0) {
System.out.println("Value is even");
if(number > 1000) {
System.out.println("Even value is large");
} if (remainder !=0) {
System.out.println("Value is odd");
}if (number < 1000){
System.out.println("Even value is just right");
}
}
}
}
/*
If the number if even then check if it is greater than 1000 or not.
If the number is greater than 1000, then print "Even value is large", else print "Even value is just right".*/ |
package com.infoworks.lab.simulator;
import com.it.soul.lab.sql.entity.Entity;
import org.junit.Test;
public class JsonLogWriterTest {
@Test
public void test(){
JsonLogWriter writer = new JsonLogWriter(JsonLogWriterTest.class);
Inner in = new Inner().setFname("Sohana Islam").setLname("Khan").setAge(27);
writer.write(in);
}
private static class Inner extends Entity{
private String fname;
private String lname;
private Integer age;
public String getFname() {
return fname;
}
public Inner setFname(String fname) {
this.fname = fname;
return this;
}
public String getLname() {
return lname;
}
public Inner setLname(String lname) {
this.lname = lname;
return this;
}
public Integer getAge() {
return age;
}
public Inner setAge(Integer age) {
this.age = age;
return this;
}
}
} |
package com.xuechuan.mymodel.建造;
/**
* @version V 1.0 xxxxxxxx
* @Title: MyModel
* @Package com.xuechuan.mymodel.inter
* @Description: todo
* @author: L-BackPacker
* @date: 2018/8/11 16:18
* @verdescript 版本号 修改时间 修改人 修改的概要说明
* @Copyright: 2018
*/
public interface Item {
public String name();
public float price();
public Packing packing();
}
|
package com.jhfactory.aospimagepick.sample;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.Group;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatCheckBox;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import com.bumptech.glide.Glide;
import com.jhfactory.aospimagepick.CropAfterImagePicked;
import com.jhfactory.aospimagepick.PickImage;
import com.jhfactory.aospimagepick.request.CropRequest;
import java.util.Objects;
public class SampleFragmentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_fragment);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(R.string.activity_name_fragment);
setSupportActionBar(toolbar);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class SampleFragmentActivityFragment extends Fragment implements View.OnClickListener,
PickImage.OnPickedPhotoUriCallback {
private static final String TAG = SampleFragmentActivityFragment.class.getSimpleName();
private AppCompatImageView mPickedPhotoView;
private AppCompatCheckBox mCropCheckBox;
private TextInputEditText mAspectRatioEditText;
private TextInputEditText mOutputSizeEditText;
private Group mCropGroup;
private Uri currentPhotoUri;
public SampleFragmentActivityFragment() {
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View root = inflater.inflate(R.layout.fragment_sample_fragment, container, false);
root.findViewById(R.id.abtn_run_capture_intent).setOnClickListener(this);
root.findViewById(R.id.abtn_run_gallery_intent).setOnClickListener(this);
mPickedPhotoView = root.findViewById(R.id.aiv_picked_image);
mCropGroup = root.findViewById(R.id.group_crop);
mCropCheckBox = root.findViewById(R.id.acb_do_crop);
mCropCheckBox.setChecked(false);
mCropGroup.setVisibility(View.GONE);
mCropCheckBox.setOnCheckedChangeListener((buttonView, isChecked) ->
mCropGroup.setVisibility(isChecked ? View.VISIBLE : View.GONE));
mAspectRatioEditText = root.findViewById(R.id.tie_aspect_ratio);
mOutputSizeEditText = root.findViewById(R.id.tie_output_size);
return root;
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
currentPhotoUri = savedInstanceState.getParcelable("uri");
if (currentPhotoUri != null) {
Log.i(TAG, "onRestoreInstanceState::CurrentUri: " + currentPhotoUri);
showPickedPhoto(currentPhotoUri);
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.abtn_run_capture_intent: // Capture button has been clicked
if (mCropCheckBox.isChecked()) {
PickImage.cameraWithCrop(this);
} else {
PickImage.camera(this);
}
break;
case R.id.abtn_run_gallery_intent: // Gallery button has been clicked
if (mCropCheckBox.isChecked()) {
PickImage.galleryWithCrop(this);
} else {
PickImage.gallery(this);
}
break;
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
if (currentPhotoUri != null) {
outState.putParcelable("uri", currentPhotoUri);
}
super.onSaveInstanceState(outState);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PickImage.REQ_CODE_PICK_IMAGE_FROM_CAMERA:
case PickImage.REQ_CODE_PICK_IMAGE_FROM_GALLERY:
case PickImage.REQ_CODE_CROP_IMAGE:
case PickImage.REQ_CODE_PICK_IMAGE_FROM_GALLERY_WITH_CROP:
case PickImage.REQ_CODE_PICK_IMAGE_FROM_CAMERA_WITH_CROP:
PickImage.onActivityResult(requestCode, resultCode, data, this);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
@CropAfterImagePicked(requestCodes = {
PickImage.REQ_CODE_PICK_IMAGE_FROM_GALLERY_WITH_CROP,
PickImage.REQ_CODE_PICK_IMAGE_FROM_CAMERA_WITH_CROP})
public void startCropAfterImagePicked() {
String aspectRatio = Objects.requireNonNull(mAspectRatioEditText.getText()).toString();
String outputSize = Objects.requireNonNull(mOutputSizeEditText.getText()).toString();
if (TextUtils.isEmpty(aspectRatio) && TextUtils.isEmpty(outputSize)) {
PickImage.crop(this);
return;
}
CropRequest.Builder builder = new CropRequest.Builder(this);
if (!TextUtils.isEmpty(aspectRatio)) {
builder.aspectRatio(aspectRatio);
}
if (!TextUtils.isEmpty(outputSize)) {
builder.outputSize(outputSize);
}
builder.scale(true);
CropRequest request = builder.build();
PickImage.crop(request);
}
@Override
public void onReceivePickedPhotoUri(int resultCode, @Nullable Uri contentUri) {
Log.i(TAG, "[onReceivePickedPhotoUri] resultCode: " + resultCode);
Log.i(TAG, "[onReceivePickedPhotoUri] onReceiveImageUri: " + contentUri);
if (contentUri == null) {
Log.e(TAG, "content uri is null.");
return;
}
currentPhotoUri = contentUri;
showPickedPhotoInfo(contentUri);
showPickedPhoto(contentUri);
}
private void showPickedPhotoInfo(@NonNull Uri contentUri) {
if (getContext() == null) {
Log.e(TAG, "Context is null. Cannot show a picked photo information.");
return;
}
Log.i(TAG, "[showPickedPhotoInfo] Uri scheme: " + contentUri.getScheme());
Log.i(TAG, "[showPickedPhotoInfo] getLastPathSegment: " + contentUri.getLastPathSegment());
byte[] bytes = PickImage.getBytes(getContext(), contentUri);
if (bytes != null) {
String readableFileSize;
readableFileSize = Formatter.formatFileSize(getContext(), bytes.length);
Log.i(TAG, "[showPickedPhotoInfo] Size: " + readableFileSize);
}
}
private void showPickedPhoto(@NonNull Uri contentUri) {
if (getContext() == null) {
Log.e(TAG, "Context is null. Cannot show a picked photo on view.");
return;
}
String fileName = PickImage.getFileName(getContext(), contentUri);
Log.i(TAG, "-- [showPickedPhoto] Image file name: " + fileName);
byte[] bytes = PickImage.getBytes(getContext(), contentUri);
if (bytes != null) {
Glide.with(this)
.load(bytes)
.into(mPickedPhotoView);
} else {
throw new RuntimeException("Failed to get picked image bytes.");
}
}
}
}
|
package nl.tue.win.dbt.tests;
import nl.tue.win.dbt.Configuration;
import nl.tue.win.dbt.algorithms.TimeIndices.Tila;
import nl.tue.win.dbt.data.DblpLabel;
import nl.tue.win.dbt.data.Edge;
import nl.tue.win.dbt.data.LabeledGraph;
import nl.tue.win.dbt.parsers.DblpParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Main {
private final List<LabeledGraph<Integer, Edge, DblpLabel>> patterns;
private final ReadTime<Integer, Edge, DblpLabel> readTime;
private final LvgTime<Integer, Edge, DblpLabel> lvgTime;
private final BaseSetupTime<Integer, Edge, DblpLabel> baseTime;
private final QueryTime<Integer, Edge, DblpLabel> baseQueryTime;
private final DurableSetupTime<Integer, Edge, DblpLabel> tilaTime;
private final QueryTime<Integer, Edge, DblpLabel> tilaQueryTime;
private final DurableSetupTime<Integer, Edge, DblpLabel> ctinlaTime;
private final QueryTime<Integer, Edge, DblpLabel> ctinlaQueryTime;
private Main(String filename, boolean base, boolean tila, boolean ctinla, int maxClique, DblpLabel label) {
Objects.requireNonNull(filename);
Objects.requireNonNull(label);
System.out.println("Creating patterns");
this.patterns = this.createCliquePatterns(maxClique, label);
System.out.println("Creating history graph");
this.readTime = new ReadTime<>(filename, new DblpParser());
System.out.println("Creating LVG");
this.lvgTime = new LvgTime<>(this.readTime.getLhg());
if(base) {
System.out.println("Creating baseline algorithm");
this.baseTime = this.createBaseTime();
System.out.println("Executing baseline queries");
this.baseQueryTime = new QueryTime<>(this.baseTime.getFilename(), this.patterns);
} else {
this.baseTime = null;
this.baseQueryTime = null;
}
if(tila) {
System.out.println("Creating TiLa algorithm");
this.tilaTime = this.createTilaTime();
System.out.println("Executing TiLa queries");
this.tilaQueryTime = new QueryTime<>(this.tilaTime.getFilename(), this.patterns);
} else {
this.tilaTime = null;
this.tilaQueryTime = null;
}
if(ctinla) {
System.out.println("Creating CTiNLa algorithm");
this.ctinlaTime = this.createCtinlaTime();
System.out.println("Executing CTiNLa queries");
this.ctinlaQueryTime = new QueryTime<>(this.ctinlaTime.getFilename(), this.patterns);
} else {
this.ctinlaTime = null;
this.ctinlaQueryTime = null;
}
}
private BaseSetupTime<Integer, Edge, DblpLabel> createBaseTime() {
return new BaseSetupTime<>(
"data/base.ser", this.readTime.getLhg());
}
private DurableSetupTime<Integer, Edge, DblpLabel> createTilaTime() {
Configuration config = new Configuration();
config.setTi(new Tila());
return new DurableSetupTime<>(
"data/tila.ser",
this.lvgTime.getLvg(),
this.lvgTime.getLhg().getGraphCreator(),
config);
}
private DurableSetupTime<Integer, Edge, DblpLabel> createCtinlaTime() {
Configuration config = new Configuration();
config.setTi(new Tila());
return new DurableSetupTime<>(
"data/ctinla.ser",
this.lvgTime.getLvg(),
this.lvgTime.getLhg().getGraphCreator(),
config);
}
private List<LabeledGraph<Integer, Edge, DblpLabel>> createCliquePatterns(int max) {
List<LabeledGraph<Integer, Edge, DblpLabel>> patterns = new ArrayList<>();
for(int i = 1; i <= max; i++) {
for(DblpLabel label: DblpLabel.values()) {
patterns.add(createCliquePattern(i, label));
}
}
return patterns;
}
private List<LabeledGraph<Integer, Edge, DblpLabel>> createCliquePatterns(int max, DblpLabel label) {
List<LabeledGraph<Integer, Edge, DblpLabel>> patterns = new ArrayList<>();
for(int i = 1; i <= max; i++) {
patterns.add(createCliquePattern(i, label));
}
return patterns;
}
private LabeledGraph<Integer, Edge, DblpLabel> createCliquePattern(int nodes, DblpLabel label) {
Objects.requireNonNull(label);
if(nodes <= 0) {
throw new IllegalArgumentException("Expected positive integer");
}
LabeledGraph<Integer, Edge, DblpLabel> graph = DblpParser.createGraph();
for(int i = 0; i < nodes; i++) {
graph.addVertex(i);
graph.addLabel(i, label);
for(int j = 0; j < i; j++) {
graph.addEdge(i, j);
}
}
return graph;
}
public static void main(String[] args) {
String filename = "out.dblp_coauthor.001";
boolean base = true;
boolean tila = true;
boolean ctinla = true;
int maxClique = 5;
DblpLabel label = DblpLabel.JUNIOR;
Main m = new Main(filename, base, tila, ctinla, maxClique, label);
// TODO: query the info.
System.out.println("-------------------------------------------------------------------");
System.out.println("Results");
System.out.println("-------------------------------------------------------------------");
System.out.println("Reading data took " + m.readTime.calculateReadDelta());
System.out.println("Creating LVG took " + m.lvgTime.calculateLvgDelta());
if(base) {
System.out.println("Creating base took " + m.baseTime.calculateBaseDelta());
System.out.println("Writing base took " + m.baseTime.calculateWriteDelta());
printQueryTime(m.baseQueryTime, "base");
}
if(tila) {
System.out.println("Creating tila took " + m.tilaTime.calculateDurableDelta());
System.out.println("Writing tila took " + m.tilaTime.calculateWriteDelta());
printQueryTime(m.tilaQueryTime, "TiLa");
}
if(ctinla) {
System.out.println("Creating ctinla took " + m.ctinlaTime.calculateDurableDelta());
System.out.println("Writing ctinla took " + m.ctinlaTime.calculateWriteDelta());
printQueryTime(m.ctinlaQueryTime, "CTiNLa");
}
}
private static void printQueryTime(QueryTime<?, ?, ?> qt, String description) {
List<Long> col = qt.calculateCollectiveTimeDeltas();
printList(col, "Collective " + description);
List<Long> con = qt.calculateContinuousTimeDeltas();
printList(con, "Continuous " + description);
}
private static void printList(List<Long> list, String description) {
for(int i = 0; i < list.size(); i++) {
System.out.println(description + ' ' + (i+1) + "-clique query took " + list.get(i));
}
}
}
|
/**
*
*/
package com.pisen.ott.launcher.widget;
/**
*
* @author Liuhc
* @version 1.0 2015年5月6日 下午5:35:49
*/
public interface OnBorderListener {
/**
* Called when scroll to bottom
*/
public void onBottom();
/**
* Called when scroll to top
*/
public void onTop();
}
|
/*
* Created on 2004-06-01
*
*/
package com.esum.ebms.v2.packages.container.element;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.ebms.v2.packages.EbXMLMessage;
import com.esum.ebms.v2.packages.util.MessageUtil;
public class ErrorList extends HeaderElement implements java.io.Serializable
{
private static Logger log = LoggerFactory.getLogger(ErrorList.class.getName());
/** Service Element Value */
public static final String ELEMENT_ERROR_LIST_SERVICE_VALUE = "urn:oasis:names:tc:ebxml-msg:service";
/** Action Element Value */
public static final String ELEMENT_ERROR_LIST_ACTION_VALUE = "MessageError";
private static final String ATTRIBUTE_ERROR_LIST_VERSION_VALUE = EbXMLMessage.EBXML_MS_VERSION;
private static final String ATTRIBUTE_ERROR_LIST_HIGHEST_SEVERITY = "highestSeverity";
private static final String ATTRIBUTE_ERROR_LIST_ERROR_CODE_CONTEXT = "codeContext";
private static final String ATTRIBUTE_ERROR_LIST_ERROR_CODE_CONTEXT_VALUE = "urn:oasis:names:tc:ebxml-msg:service:errors";
private static final String ATTRIBUTE_ERROR_ERROR_CODE = "errorCode";
private static final String ATTRIBUTE_ERROR_SEVERITY = "severity";
private static final String ATTRIBUTE_ERROR_LOCATION = "location";
/** Error Element */
private static final String ELEMENT_ERROR = "Error";
/** Severity: Warning */
public static final String SEVERITY_WARNING = "Warning";
/** Severity: Error */
public static final String SEVERITY_ERROR = "Error";
/** Reporting Errors in the ebXML Elements */
/** Error Code: ValueNotRecognized */
public static final String ERROR_CODE_VALUE_NOT_RECOGNIZED = "ValueNotRecognized";
/** Error Code: NotSupported */
public static final String ERROR_CODE_NOT_SUPPORTED = "NotSupported";
/** Error Code: Inconsistent */
public static final String ERROR_CODE_INCONSISTENT = "Inconsistent";
/** Error Code: OtherXml */
public static final String ERROR_CODE_OTHER_XML = "OtherXml";
/** Non-XML Document Errors */
/** Error Code: DeliveryFailure */
public static final String ERROR_CODE_DELIVERY_FAILURE = "DeliveryFailure";
/** Error Code: TimeToLiveExpired */
public static final String ERROR_CODE_TIME_TO_LIVE_EXPIRED = "TimeToLiveExpired";
/** Error Code: SecurityFailure */
public static final String ERROR_CODE_SECURITY_FAILURE = "SecurityFailure";
/** Error Code: MimeProblem */
public static final String ERROR_CODE_MIME_PROBLEM = "MimeProblem";
/** Error Code: Unknown */
public static final String ERROR_CODE_UNKNOWN = "Unknown";
/** Class for Error Element*/
public static final class Error
{
private String mId = null;
private String mCodeContext = null;
private String mErrorCode = null;
private String mSeverity = null;
private String mLocation = null;
private Description mDescription = null;
public Error(String errorCode, String severity)
{
this(errorCode, severity, null, null);
}
public Error(String errorCode, String severity, String descriptionText)
{
this(errorCode, severity, descriptionText, null);
}
public Error(String errorCode, String severity, String descriptionText, String location)
{
this(errorCode, severity, descriptionText, location, false);
}
public Error(String errorCode, String severity, String descriptionText, String location, boolean useErrorId)
{
this(errorCode, severity, descriptionText, ATTRIBUTE_LANG_VALUE, location, useErrorId);
}
public Error(String errorCode, String severity, String descriptionText, String descriptionLang, String location, boolean useErrorId)
{
if (useErrorId)
mId = MessageUtil.generateId();
mErrorCode = errorCode;
mSeverity = severity;
mLocation = location;
mDescription = new Description(descriptionText, descriptionLang);
}
/** Is ErrorId */
public boolean isErrorId()
{
return mId != null ? true : false;
}
/** Get Error ID */
public String getErrorId()
{
return mId;
}
/** Is Error Code Context */
public boolean isErrorCodeContext()
{
return mCodeContext != null ? true : false;
}
/** Set Error ID */
public void setErrorId(String errorId)
{
mId = errorId;
}
/** Set Error Code Context */
public void setErrorCodeContext(String codeContext)
{
if (codeContext == null)
codeContext = ErrorList.ATTRIBUTE_ERROR_LIST_ERROR_CODE_CONTEXT_VALUE;
mCodeContext = codeContext;
}
/** Set Error Location */
public void setErrorLocation(String location)
{
mLocation = location;
}
/** Set Error Description */
public void setErrorDescription(Description description)
{
mDescription = description;
}
/** Get Error Code Context */
public String getErrorCodeContext()
{
return mCodeContext;
}
/** Get Error Code */
public String getErrorCode()
{
return mErrorCode;
}
/** Get Error Severity */
public String getErrorSeverity()
{
return mSeverity;
}
/** Get Error Location */
public String getErrorLocation()
{
return mLocation;
}
/** Get Error Description */
public Description getErrorDescription()
{
return mDescription;
}
/** Has Error Description */
public boolean hasErrorDescription()
{
return mDescription != null ? true : false;
}
}
private SOAPEnvelope mSoapEnvelope = null;
private String mId = null;
private String mHighestSeverity = null;
private List<Error> mErrorList = new ArrayList<Error>();
public ErrorList(SOAPEnvelope soapEnvelope, boolean useErrorListId) throws SOAPException
{
super(soapEnvelope, ELEMENT_ERROR_LIST);
mSoapEnvelope = soapEnvelope;
if (useErrorListId)
{
mId = MessageUtil.generateId();
}
log.debug("=> build()");
build();
log.debug("<= build()");
}
public ErrorList(SOAPEnvelope soapEnvelope, SOAPElement soapElement) throws SOAPException
{
super(soapEnvelope, soapElement);
mSoapEnvelope = soapEnvelope;
log.debug("=> extract()");
extract();
log.debug("<= extract()");
}
private void build() throws SOAPException
{
if (mId != null)
{
addAttribute(ATTRIBUTE_ELEMENT_ID, mId);
}
/** Version 속성 추가 */
addAttribute(ATTRIBUTE_ELEMENT_VERSION, ATTRIBUTE_ERROR_LIST_VERSION_VALUE);
/** SOAP mustUnderstand 속성 추가 */
addAttribute(ATTRIBUTE_SOAP_MUST_UNDERSTAND, NAMESPACE_PREFIX_SOAP, NAMESPACE_URI_SOAP, ATTRIBUTE_MUST_UNDERSTAND_VALUE);
}
private void extract() throws SOAPException
{
mId = getAttribute(ATTRIBUTE_ELEMENT_ID);
mHighestSeverity = getAttribute(ATTRIBUTE_ERROR_LIST_HIGHEST_SEVERITY);
log.debug("== ErrorList Element- id: " + (mId == null ? "" : mId) + ", highestSeverity: " + mHighestSeverity);
Iterator i = getChildElements(ELEMENT_ERROR);
while(i.hasNext())
{
ExtensionElement errorElement = new ExtensionElement(mSoapEnvelope, (SOAPElement)i.next());
String errorId = errorElement.getAttribute(ATTRIBUTE_ELEMENT_ID);
String errorCodeContext = errorElement.getAttribute(ATTRIBUTE_ERROR_LIST_ERROR_CODE_CONTEXT);
String errorCode = errorElement.getAttribute(ATTRIBUTE_ERROR_ERROR_CODE);
String errorSeverity = errorElement.getAttribute(ATTRIBUTE_ERROR_SEVERITY);
String errorLocation = errorElement.getAttribute(ATTRIBUTE_ERROR_LOCATION);
Iterator j = getChildElements(ELEMENT_DESCRIPTION);
Description description = null;
log.debug("== Error Element- "
+ "id: " + (errorId == null ? "" : errorId)
+ ", codeContext: " + (errorCodeContext == null ? "" : errorCodeContext)
+ ", errorCode: " + (errorCode == null ? "" : errorCode)
+ ", severity: " + (errorSeverity == null ? "" : errorSeverity)
+ ", location: " + (errorLocation == null ? "" : errorLocation)
);
if (j.hasNext())
{
description = new Description(mSoapEnvelope, (SOAPElement)j.next());
log.debug("== Description Element- "
+ "Text: " + description.getText()
+ ", Lang: " + description.getLang());
}
Error error = new Error(errorCode, errorSeverity);
error.setErrorId(errorId);
error.setErrorCodeContext(errorCodeContext);
error.setErrorDescription(description);
mErrorList.add(error);
}
}
/** Highest Severity 속성 추가 */
public void addHighestSeverity() throws SOAPException
{
addAttribute(ATTRIBUTE_ERROR_LIST_HIGHEST_SEVERITY, mHighestSeverity);
}
/** Error Element에서 발생한 에러중 Severity값이 최고 값으로 셋팅 */
private void setHighestSeverity(String severity)
{
if (mHighestSeverity != null)
{
if (mHighestSeverity.equals(SEVERITY_WARNING))
{
if (severity.equals(SEVERITY_ERROR))
mHighestSeverity = SEVERITY_ERROR;
}
}
else
mHighestSeverity = severity;
}
/** Error Element 추가 */
public void addError(Error error) throws SOAPException
{
ExtensionElement errorElement = addChildElement(ELEMENT_ERROR);
if (error.isErrorId())
{
errorElement.addAttribute(ATTRIBUTE_ELEMENT_ID, error.getErrorId());
}
if (error.isErrorCodeContext())
errorElement.addAttribute(ATTRIBUTE_ERROR_LIST_ERROR_CODE_CONTEXT, error.getErrorCodeContext());
errorElement.addAttribute(ATTRIBUTE_ERROR_ERROR_CODE, error.getErrorCode());
errorElement.addAttribute(ATTRIBUTE_ERROR_SEVERITY, error.getErrorSeverity());
/**
* ErrorLocation 에 "" 으로 되는 현상 방지 by kwang yoel park 200808
*/
if (error.getErrorLocation() != null && error.getErrorLocation().trim().length() > 0) {
errorElement.addAttribute(ATTRIBUTE_ERROR_LOCATION, error.getErrorLocation());
}
if (error.hasErrorDescription())
{
errorElement.addChildElement(new Description(mSoapEnvelope
, error.getErrorDescription().getText()
, error.getErrorDescription().getLang())
);
}
mErrorList.add(error);
setHighestSeverity(error.getErrorSeverity());
}
/** Get highestSeverity */
public String getHighestSeverity()
{
return mHighestSeverity;
}
/** Get Error List */
public Iterator<Error> getErrorList()
{
return mErrorList.iterator();
}
}
|
abstract class AbstractItem {
protected String name;
protected String action_name;
protected int price;
protected int id;
protected static int items_count;
public AbstractItem(String name, int price) {
this.name = name;
this.price = price;
this.id = items_count++;
}
public String getName() {
return name;
}
} |
package edu.cnm.deepdive.model;
import com.google.gson.annotations.Expose;
import java.util.Date;
public class Game {
@Expose
private String id;
@Expose
private Date created;
@Expose
private String pool;
@Expose
private int length;
@Expose
private int guessCount;
@Expose
private boolean solved;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getPool() {
return pool;
}
public void setPool(String pool) {
this.pool = pool;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getGuessCount() {
return guessCount;
}
public void setGuessCount(int guessCount) {
this.guessCount = guessCount;
}
public boolean isSolved() {
return solved;
}
public void setSolved(boolean solved) {
this.solved = solved;
}
}
|
package sampleproject.gui;
import java.io.*;
import java.util.*;
/**
* Provides read/write access to the user's saved configuration parameters on
* disk, so that next time they connect, we can offer the same configuration
* parameters as a default.
*
* @author Denny's DVDs
*/
public class SavedConfiguration {
/**
* key in Properties indicating that the value will be the database
* location.
*/
public static final String DATABASE_LOCATION = "DatabaseLocation";
/**
* key in Properties indicating that the value will be the RMI Registry
* server address.
*/
public static final String SERVER_ADDRESS = "ServerAddress";
/**
* key in Properties indicating that the value will be the port the RMI
* Registry or the Socket Server listens on.
*/
public static final String SERVER_PORT = "ServerPort";
/**
* key in Properties indicating that the what type of network connectivity
* will be used between the client and server.
*/
public static final String NETWORK_TYPE = "NetworkType";
/**
* the Properties for this application.
*/
private Properties parameters = null;
/**
* The location where our configuration file will be saved.
*/
private static final String BASE_DIRECTORY = System.getProperty("user.dir");
/**
* the name of our properties file.
*/
private static final String OPTIONS_FILENAME = "dennys.properties";
/**
* The file containing our saved configuration.
*/
private static File savedOptionsFile
= new File(BASE_DIRECTORY, OPTIONS_FILENAME);
/**
* Placeholder for our singleton version of OptionsModel. Since we know
* that we will want at least one of these, we are creating our instance as
* soon as we possibly can. If we were unsure whether we would ever need
* this or not we would probably perform a lazy instantiation.
*/
private static SavedConfiguration savedConfiguration
= new SavedConfiguration();
/**
* Creates a new instance of SavedConfiguration. There should only ever be
* one instance of this class (a Singleton), so we have made it private.
*/
private SavedConfiguration() {
parameters = loadParametersFromFile();
if (parameters == null) {
parameters = new Properties();
parameters.setProperty(SERVER_ADDRESS, "localhost");
parameters.setProperty(SERVER_PORT,
"" + java.rmi.registry.Registry.REGISTRY_PORT);
}
}
/**
* return the single instance of the SavedConfiguration.
*
* @return the single instance of the SavedConfiguration.
*/
public static SavedConfiguration getSavedConfiguration() {
return savedConfiguration;
}
/**
* returns the value of the named parameter.<p>
*
* @param parameterName the name of the parameter for which the user
* is requesting the value.
* @return the value of the named parameter.
*/
public String getParameter(String parameterName) {
return parameters.getProperty(parameterName);
}
/**
* Updates the saved parameters with the new values. Always saves the new
* values immediately - this means we will be saving the properties file
* far more often than we need when we enter our first set of values,
* however once the initial set of values have been entered, they should
* rarely (if ever) be changed. So this will not be a problem most of the
* time. Doing it this way means that the user of this class need not
* explictly save the parameters.
*
* @param parameterName the name of the parameter.
* @param parameterValue the value to be stored for the parameter
*/
public void setParameter(String parameterName, String parameterValue) {
parameters.setProperty(parameterName, parameterValue);
saveParametersToFile();
}
/**
* saves the parameters to a file so that they can be used again next time
* the application starts.
*/
private void saveParametersToFile() {
try {
synchronized (savedOptionsFile) {
if (savedOptionsFile.exists()) {
savedOptionsFile.delete();
}
savedOptionsFile.createNewFile();
FileOutputStream fos = new FileOutputStream(savedOptionsFile);
parameters.store(fos, "Denny's DVDs configuration");
fos.close();
}
} catch (IOException e) {
ApplicationRunner.handleException(
"Unable to save user parameters to file. "
+ "They wont be remembered next time you start.");
}
}
/**
* attempts to load the saved parameters from the file so that the user does
* not have to reenter all the information.
*
* @return Properties loaded from file or null.
*/
private Properties loadParametersFromFile() {
Properties loadedProperties = null;
if (savedOptionsFile.exists() && savedOptionsFile.canRead()) {
synchronized (savedOptionsFile) {
try {
FileInputStream fis = new FileInputStream(savedOptionsFile);
loadedProperties = new Properties();
loadedProperties.load(fis);
fis.close();
} catch (FileNotFoundException e) {
assert false : "File not found after existance verified";
ApplicationRunner.handleException("Unable to load user "
+ "parameters. Default values will be used.\n"
+ e);
} catch (IOException e) {
assert false : "Bad data in parameters file";
ApplicationRunner.handleException("Unable to load user "
+ "parameters. Default values will be used.\n"
+ e);
}
}
}
return loadedProperties;
}
}
|
package com.cloudaping.cloudaping;
import com.cloudaping.cloudaping.dao.ProductRepository;
import com.cloudaping.cloudaping.entity.Product;
import com.cloudaping.cloudaping.entity.productType.Laptop;
import com.cloudaping.cloudaping.entity.productType.ProductType;
import com.cloudaping.cloudaping.mapper.ProductTypeMapper;
import com.cloudaping.cloudaping.utils.KeyUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@SpringBootTest
public class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private ProductTypeMapper productTypeMapper;
@Test
public void select(){
// List<ProductType> list2=productTypeMapper.selectLaptop();
// System.out.println(productTypeMapper.selectAudioVideo());
// List<ProductType> list3=productTypeMapper.selectCamera();
// System.out.println(productTypeMapper.selectCamera());
// System.out.println(productTypeMapper.selectComputer());
// List<ProductType> list1=productTypeMapper.selectMobile();
// System.out.println(productTypeMapper.selectMobile());
Map<String,Object> map=new LinkedHashMap<>();
map.put("type","laptop");
map.put("laptopBrand","dell");
List<Product> list=productTypeMapper.selectByTypeParams(map);
System.out.println(list.toString());
System.out.println(list.size());
}
@Test
public void user(){
System.out.println(KeyUtil.getOrderKey());
}
}
|
package tj.teacherjournal;
/**
* Created by risatgajsin on 24.04.2018.
*/
public class Student {
private int id;
private String name;
private String gender;
private String age;
private String groupid; // Надо бы сделать здесь конструкцию привязки из User -> groupid
private String registration;
private String studnumber;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
//
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGroupid() {
return groupid;
}
public void setGroupid(String groupid) {
this.groupid = groupid;
}
public String getRegistration() {
return registration;
}
public void setRegistration(String registration) {
this.registration = registration;
}
public String getStudnumber() {
return studnumber;
}
public void setStudnumber(String studnumber) {
this.studnumber = studnumber;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
|
package com.amhable.logicaNegocio;
import com.amhable.dominio.UsuarioDto;
import com.amhable.exception.MyException;
/**
* Interface que contiene la logica del negocio que se va a implementar sobre la tabla Usuario
* en la Base de Datos
* @author Luisa
*18/06/2015
*/
public interface UsuarioLN {
/**
* Firma del metodo obtenerUsuario
*
*@param identificador del usuario que se va a obtener
* @return UsuarioDto
* @throws MyException
*/
public UsuarioDto obtenerUsuario(String idUsuario) throws MyException;
/**
* Firma del metodo guardar
*
* @param identificador del usuario que se va a guardar
* @param contraseņa del usuario que se va a guardar
* @throws MyException
*/
public void guardar(String idUsuario, String contrasena) throws MyException;
/**
* Firma del metodo actualizar
*
* @param identificador del usuario que se va a actualizar
* @param contraseņa del usuario que se va a actualizar
* @throws MyException
*/
public void actualizar(String idUsuario, String contrasena) throws MyException;
} |
package everyday;
import java.util.Stack;
/**
* 1006. 笨阶乘
*/
public class Clumsy {
public int clumsy(int N) {
Stack<Integer> stack = new Stack<>();
stack.push(N);
int sign = 1;
for (int i = N - 1; i >= 1; i--) {
switch (sign) {
case 1: {
stack.push(stack.pop() * i);
break;
}
case 2: {
stack.push(stack.pop() / i);
break;
}
case 3: {
stack.push(i);
break;
}
case 4: {
stack.push(-i);
break;
}
}
sign++;
if (sign == 5) {
sign = 1;
}
}
int res = 0;
while (!stack.empty()) {
res += stack.pop();
}
return res;
}
public static void main(String[] args) {
new Clumsy().clumsy(10);
}
}
|
package com.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
/**
* Entity implementation class for Entity: Product
*
*/
@Entity
public class Product implements Serializable {
static EntityManagerFactory ENTITY_MANAGER_FACTORY = Persistence.createEntityManagerFactory("stockmicroservice-jpa");
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
private static final long serialVersionUID = 1L;
@Id
private int id;
private String location;
private String name;
private String image;
private String description;
private String keywords;
private float price;
private int threshold;
private int amount;
public Product() {
super();
}
public boolean save() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
boolean succesfulltransaction = false;
try {
et = em.getTransaction();
et.begin();
if(Product.getProduct(this.id)==null)
em.persist(this);
et.commit();
succesfulltransaction = true;
} catch (Exception e) {
if (et != null) {
et.rollback();
}
}
finally {
em.close();
}
return succesfulltransaction;
}
public boolean removeProduct() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
boolean succesfulltransaction = false;
try {
et = em.getTransaction();
et.begin();
Product product = em.find( Product.class , this.id);
em.remove(product);
et.commit();
succesfulltransaction = true;
} catch (Exception e) {
if (et != null) {
et.rollback();
}
}
finally {
em.close();
}
return succesfulltransaction;
}
public static List<Product> getProducts() {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
String query = "SELECT c FROM Product c WHERE c.id IS NOT NULL";
TypedQuery<Product> tq = em.createQuery(query, Product.class);
List<Product> products = null;
try {
products = tq.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
finally {
em.close();
}
return products;
}
public static Product getProduct( int id) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
EntityTransaction et = null;
Product product = null;
try {
et = em.getTransaction();
et.begin();
product = em.find( Product.class , id);
} catch (Exception e) {
e.printStackTrace();
}
finally {
em.close();
}
return product;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public static boolean UpdateProductById(int id, String name2, String description2, String location2, String image2,
Float price2, Integer threshold2, Integer amount2, String keyword) {
EntityManager em = ENTITY_MANAGER_FACTORY.createEntityManager();
try {
Product product=em.find(Product.class, id);
em.getTransaction().begin();
if(amount2!=null)product.setAmount(amount2);
if(description2!=null)product.setDescription(description2);
if(image2!=null)product.setImage(image2);
if(keyword!=null)product.setKeywords(keyword);
if(location2!=null)product.setLocation(location2);
if(name2!=null)product.setName(name2);
if(price2!=null)product.setPrice(price2);
if(threshold2!=null)product.setThreshold(threshold2);
em.getTransaction().commit();
return true;
}catch(Exception ignore) {
}
return false;
}
}
|
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.titus.master.jobmanager.service.integration;
import com.netflix.titus.api.jobmanager.model.job.JobDescriptor;
import com.netflix.titus.api.jobmanager.model.job.TaskState;
import com.netflix.titus.master.jobmanager.service.integration.scenario.JobsScenarioBuilder;
import com.netflix.titus.testkit.model.job.JobDescriptorGenerator;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class KubeSchedulerMasterBootstrapTest {
private final JobsScenarioBuilder jobsScenarioBuilder = new JobsScenarioBuilder(true);
@Test
public void testRestartWithBasicTaskAcceptedWithoutPod() {
testRestartWithTaskAcceptedWithoutPod(JobDescriptorGenerator.oneTaskBatchJobDescriptor());
}
@Test
public void testRestartWithServiceTaskAcceptedWithoutPod() {
testRestartWithTaskAcceptedWithoutPod(JobDescriptorGenerator.oneTaskServiceJobDescriptor());
}
private void testRestartWithTaskAcceptedWithoutPod(JobDescriptor<?> jobDescriptor) {
jobsScenarioBuilder.scheduleJob(jobDescriptor, jobScenario -> jobScenario
.expectJobEvent()
.expectTaskAddedToStore(0, 0, task -> assertThat(task.getStatus().getState()).isEqualTo(TaskState.Accepted))
).reboot()
.inJob(0, jobScenario -> jobScenario
.expectTaskInActiveState(0, 0, TaskState.Accepted)
.advance()
.expectScheduleRequest(0, 0)
);
}
}
|
package cz.metacentrum.perun.spRegistration.persistence.managers.impl;
import cz.metacentrum.perun.spRegistration.common.configs.AppBeansContainer;
import cz.metacentrum.perun.spRegistration.common.enums.RequestAction;
import cz.metacentrum.perun.spRegistration.common.enums.RequestStatus;
import cz.metacentrum.perun.spRegistration.common.exceptions.ActiveRequestExistsException;
import cz.metacentrum.perun.spRegistration.common.exceptions.InternalErrorException;
import cz.metacentrum.perun.spRegistration.common.models.RequestDTO;
import cz.metacentrum.perun.spRegistration.persistence.managers.RequestManager;
import cz.metacentrum.perun.spRegistration.persistence.mappers.RequestMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
/**
* Implementation of Request Manager. Works with DB and Request objects.
*
* @author Dominik Frantisek Bucik <bucik@ics.muni.cz>;
*/
@Component("requestManager")
@EnableTransactionManagement
@Slf4j
public class RequestManagerImpl implements RequestManager {
public static final String PARAM_ID = "id";
public static final String PARAM_REQ_ID = "req_id";
public static final String PARAM_FAC_ID = "fac_id";
public static final String PARAM_STATUS = "status";
public static final String PARAM_ACTION = "action";
public static final String PARAM_REQ_USER_ID = "req_user_id";
public static final String PARAM_ATTRIBUTES = "attributes";
public static final String PARAM_MODIFIED_BY = "modified_by";
public static final String PARAM_IDS = "ids";
public static final String PARAM_STATUS_WFA = "status_wfa";
public static final String PARAM_STATUS_WFC = "status_wfc";
private static final String REQUESTS_TABLE = "requests";
private final RequestMapper REQUEST_MAPPER;
private final NamedParameterJdbcTemplate jdbcTemplate;
private final AppBeansContainer appBeansContainer;
@Autowired
public RequestManagerImpl(@NonNull NamedParameterJdbcTemplate jdbcTemplate,
@NonNull AppBeansContainer appBeansContainer)
{
REQUEST_MAPPER = new RequestMapper(appBeansContainer);
this.jdbcTemplate = jdbcTemplate;
this.appBeansContainer = appBeansContainer;
}
@Override
@Transactional
public Long createRequest(@NonNull RequestDTO request)
throws InternalErrorException, ActiveRequestExistsException
{
if (request.getFacilityId() != null) {
Long activeRequestId = getActiveRequestIdByFacilityId(request.getFacilityId());
if (activeRequestId != null) {
log.error("Active requests already exist for facilityId: {}", request.getFacilityId());
throw new ActiveRequestExistsException();
}
}
String query = new StringJoiner(" ")
.add("INSERT INTO").add(REQUESTS_TABLE)
.add("(facility_id, status, action, requesting_user_id, attributes, modified_by)")
.add("VALUES (:fac_id, :status, :action, :req_user_id, :attributes, :modified_by)")
.toString();
KeyHolder key = new GeneratedKeyHolder();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_FAC_ID, request.getFacilityId());
params.addValue(PARAM_STATUS, request.getStatus().getAsInt());
params.addValue(PARAM_ACTION, request.getAction().getAsInt());
params.addValue(PARAM_REQ_USER_ID, request.getReqUserId());
params.addValue(PARAM_ATTRIBUTES, request.getAttributesAsJsonForDb(appBeansContainer));
params.addValue(PARAM_MODIFIED_BY, request.getModifiedBy());
int updatedCount = jdbcTemplate.update(query, params, key, new String[] {PARAM_ID});
if (updatedCount == 0) {
log.error("Zero requests have been inserted");
throw new InternalErrorException("Zero requests have been inserted");
} else if (updatedCount > 1) {
log.error("Only one request should have been inserted");
throw new InternalErrorException("Only one request should have been inserted");
}
Number generatedKey = key.getKey();
if (generatedKey == null) {
throw new InternalErrorException("Did not generate key");
}
return generatedKey.longValue();
}
@Override
@Transactional
public boolean updateRequest(@NonNull RequestDTO request) throws InternalErrorException {
String query = new StringJoiner(" ")
.add("UPDATE").add(REQUESTS_TABLE)
.add("SET facility_id = :fac_id, status = :status, action = :action, requesting_user_id = :req_user_id,")
.add("attributes = :attributes, modified_by = :modified_by, modified_at = NOW()")
.add("WHERE id = :req_id")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_FAC_ID, request.getFacilityId());
params.addValue(PARAM_STATUS, request.getStatus().getAsInt());
params.addValue(PARAM_ACTION, request.getAction().getAsInt());
params.addValue(PARAM_REQ_USER_ID, request.getReqUserId());
params.addValue(PARAM_ATTRIBUTES, request.getAttributesAsJsonForDb(appBeansContainer));
params.addValue(PARAM_MODIFIED_BY, request.getModifiedBy());
params.addValue(PARAM_REQ_ID, request.getReqId());
int updatedCount = jdbcTemplate.update(query, params);
if (updatedCount == 0) {
log.error("Zero requests have been updated");
throw new InternalErrorException("Zero requests have been updated");
} else if (updatedCount > 1) {
log.error("Only one request should have been updated");
throw new InternalErrorException("Only one request should have been updated");
}
return true;
}
@Override
@Transactional
public boolean deleteRequest(@NonNull Long reqId) throws InternalErrorException {
String query = new StringJoiner(" ")
.add("DELETE FROM").add(REQUESTS_TABLE)
.add("WHERE id = :req_id")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_REQ_ID, reqId);
int updatedCount = jdbcTemplate.update(query, params);
if (updatedCount == 0) {
log.error("Zero requests have been deleted");
throw new InternalErrorException("Zero requests have been deleted");
} else if (updatedCount > 1) {
log.error("Only one request should have been deleted");
throw new InternalErrorException("Only one request should have been deleted");
}
return true;
}
@Override
@Transactional
public RequestDTO getRequestById(@NonNull Long reqId) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE id = :req_id")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_REQ_ID, reqId);
try {
return jdbcTemplate.queryForObject(query, params, REQUEST_MAPPER);
} catch (EmptyResultDataAccessException e) {
return null;
}
}
@Override
@Transactional
public List<RequestDTO> getAllRequests() {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.toString();
return jdbcTemplate.query(query, REQUEST_MAPPER);
}
@Override
@Transactional
public List<RequestDTO> getAllRequestsByUserId(@NonNull Long userId) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE requesting_user_id = :req_user_id")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_REQ_USER_ID, userId);
return jdbcTemplate.query(query, params, REQUEST_MAPPER);
}
@Override
@Transactional
public List<RequestDTO> getAllRequestsByStatus(@NonNull RequestStatus status) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE status = :status")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_STATUS, status.getAsInt());
return jdbcTemplate.query(query, params, REQUEST_MAPPER);
}
@Override
@Transactional
public List<RequestDTO> getAllRequestsByAction(@NonNull RequestAction action) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE action = :action")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_ACTION, action.getAsInt());
return jdbcTemplate.query(query, params, REQUEST_MAPPER);
}
@Override
@Transactional
public List<RequestDTO> getAllRequestsByFacilityId(@NonNull Long facilityId) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE facility_id = :fac_id")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_FAC_ID, facilityId);
return jdbcTemplate.query(query, params, REQUEST_MAPPER);
}
@Override
@Transactional
public List<RequestDTO> getAllRequestsByFacilityIds(@NonNull Set<Long> facilityIds) {
String query = new StringJoiner(" ")
.add("SELECT * FROM").add(REQUESTS_TABLE)
.add("WHERE facility_id IN (:ids)")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_IDS, new ArrayList<>(facilityIds));
return jdbcTemplate.query(query, params, REQUEST_MAPPER);
}
@Override
@Transactional
public Long getActiveRequestIdByFacilityId(@NonNull Long facilityId) throws InternalErrorException {
String query = new StringJoiner(" ")
.add("SELECT id FROM").add(REQUESTS_TABLE)
.add("WHERE facility_id = :fac_id AND (status = :status_wfc OR status = :status_wfa)")
.toString();
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue(PARAM_FAC_ID, facilityId);
params.addValue(PARAM_STATUS_WFA, RequestStatus.WAITING_FOR_CHANGES.getAsInt());
params.addValue(PARAM_STATUS_WFC, RequestStatus.WAITING_FOR_APPROVAL.getAsInt());
Long activeRequestId;
try {
activeRequestId = jdbcTemplate.queryForObject(query, params, Long.class);
} catch (EmptyResultDataAccessException e) {
activeRequestId = null;
} catch (IncorrectResultSizeDataAccessException e) {
log.error("Two active requests for facility {} found", facilityId);
throw new InternalErrorException("Two active requests for facility #" + facilityId + " found", e);
}
return activeRequestId;
}
}
|
package ru.job4j.models;
import java.util.Objects;
/**
* Класс Brand реализует сущность Брэнд.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 2018-05-14
* @since 2018-05-14
*/
public class Brand implements IModel {
/**
* Основатель брэнда.
*/
private Founder founder;
/**
* Идентификатор брэнда.
*/
private int id;
/**
* Название брэнда.
*/
private String name;
/**
* Конструктор без параметров.
*/
public Brand() {
}
/**
* Конструктор.
* @param founder основатель брэнда.
* @param id идентификатор брэнда.
* @param name название брэнда.
*/
public Brand(int id, String name, Founder founder) {
this.founder = founder;
this.id = id;
this.name = name;
}
/**
* Переопределяет метод equals().
* @return true если объекты равны. Иначе false.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || this.getClass() != o.getClass()) {
return false;
}
Brand brand = (Brand) o;
return this.id == brand.getId() && this.name.equals(brand.getName()) && this.founder.equals(brand.getFounder());
}
/**
* Получет основателя брэнда.
* @return основателя брэнда.
*/
public Founder getFounder() {
return this.founder;
}
/**
* Получет идентификатор брэнда.
* @return нидентификатор брэнда.
*/
public int getId() {
return this.id;
}
/**
* Получет название брэнда.
* @return название брэнда.
*/
public String getName() {
return this.name;
}
/**
* Переопределяет метод hashCode().
* @return хэш-сумма объекта.
*/
@Override
public int hashCode() {
return Objects.hash(this.founder, this.id, this.name);
}
/**
* Устанавливает основателя брэнда.
* @param founder основатель брэнда.
*/
public void setFounder(Founder founder) {
this.founder = founder;
}
/**
* Устанавливает идентификатор брэнда.
* @param id идентификатор брэнда.
*/
public void setId(final int id) {
this.id = id;
}
/**
* Устанавливает название брэнда.
* @param name название брэнда.
*/
public void setName(String name) {
this.name = name;
}
/**
* Переопределяет метод toString().
* @return строковое представление объекта.
*/
@Override
public String toString() {
return String.format("Brand[id: %d, name: %s, founder: %s]", this.id, this.name, this.founder);
}
} |
package com.kopo.jaemin;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.sqlite.SQLiteConfig;
public class UserDB {
// ◆◆◆테이블생성◆◆◆
public void createTable( ) {
//open
try {
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
//use
//sqllite = 정수는 INTEGER, 실수는 REAL, 문자열은 TEXT
String query = "CREATE TABLE student(idx INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, middleScore REAL, finalScore REAL, created TEXT)";
Statement statement = connection.createStatement();
int result = statement.executeUpdate(query);
statement.close();
//close
connection.close();
} catch (Exception e) {
}
}
// ◆◆◆데이터삽입◆◆◆
public void insertData(String name, double middleScore, double finalScore) {
//open
try {
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
//use
String query = "INSERT INTO student (name, middleScore, finalScore, created) VALUES ('" + name + "'," + middleScore + ", " + finalScore + ", date('now'))";
Statement statement = connection.createStatement();
int result = statement.executeUpdate(query);
//close
connection.close();
} catch (Exception e) {
}
}
// ◆◆◆목록보기화면◆◆◆
public String selectData() {
String resultString = "";
try {
//open
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
//use
String query = "SELECT * FROM student";
PreparedStatement preparedStatement = connection.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
while(resultSet.next()) {
int idx = resultSet.getInt("idx");
String name = resultSet.getString("name");
double middleScore = resultSet.getDouble("middleScore");
double finalScore = resultSet.getDouble("finalScore");
String created = resultSet.getString("created");
resultString = resultString + "<tr>";
resultString = resultString + "<td>" + idx + "</td><td>" + name + "</td><td>" + middleScore
+ "</td><td>" + finalScore + "</td><td>" + created
+ "</td><td><a href='update?idx=" + idx + "'>수정하기</a></td>"
+ "</td><td><a href='delete?idx=" + idx + "'>삭제하기</a></td>";
resultString = resultString + "</tr>";
}
preparedStatement.close();
//close
connection.close();
} catch (Exception e) {
}
return resultString;
}
// ◆◆◆목록확인◆◆◆
public Student detailsData (int idx) {
Student resultData = new Student();
try {
//open
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
//use
String query = "SELECT * FROM student WHERE idx=?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, idx);
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
resultData.idx = resultSet.getInt("idx");
resultData.name = resultSet.getString("name");
resultData.middleScore = resultSet.getDouble("middleScore");
resultData.finalScore = resultSet.getDouble("finalScore");
resultData.created = resultSet.getString("created");
}
preparedStatement.close();
//close
connection.close();
} catch (Exception e) {
}
return resultData;
}
// ◆◆◆데이터수정◆◆◆
public void updateData (int idx, String name, double middleScore, double finalScore) {
try {
// open
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
String query = "UPDATE student SET name=?, middleScore=?, finalScore=?, created=datetime('now') WHERE idx=?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setDouble(2, middleScore);
preparedStatement.setDouble(3, finalScore);
preparedStatement.setInt(4, idx);
int result = preparedStatement.executeUpdate();
preparedStatement.close();
// close
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// ◆◆◆데이터삭제◆◆◆
public void deleteData (int idx) {
try {
// open
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
Connection connection = DriverManager.getConnection("jdbc:sqlite:/" + "c:/tomcat/user.db", config.toProperties());
String query1 = "DELETE FROM student WHERE idx=?";
// String query2 = "ALTER TABLE student AUTO_INCREMENT=1";
PreparedStatement preparedStatement1 = connection.prepareStatement(query1);
// PreparedStatement preparedStatement2 = connection.prepareStatement(query2);
preparedStatement1.setInt(1, idx);
int result1 = preparedStatement1.executeUpdate();
// int result2 = preparedStatement2.executeUpdate();
preparedStatement1.close();
// preparedStatement2.close();
// close
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
/**
*
*/
package net.imagej.domains;
import net.imglib2.Interval;
import net.imglib2.RandomAccess;
import net.imglib2.RandomAccessible;
/**
* @author Stephan Saalfeld <saalfelds@janelia.hhmi.org>
*
*/
public class TerminalDiscreteDomain<T> implements DiscreteDomain<T, T> {
final protected RandomAccessible<T> source;
public TerminalDiscreteDomain(final RandomAccessible<T> source) {
this.source = source;
}
@Override
public RandomAccessible<T> flatAccessible() {
return source;
}
@Override
public int numDimensions() {
return source.numDimensions();
}
@Override
public RandomAccess<T> randomAccess() {
return source.randomAccess();
}
@Override
public RandomAccess<T> randomAccess(Interval interval) {
return source.randomAccess(interval);
}
}
|
package lang;
public class BooleanDemo {
public static void main(String args[]) {
Boolean a = null;
System.out.println(Boolean.FALSE.equals(a));
}
}
|
package tests.scenario_tests.user_session;
import board.blockingobject.Player;
import board.grid.Grid;
import board.square.Square;
import items.ForceField;
import items.ForceFieldGenerator;
import items.Item;
import org.junit.Before;
import org.junit.Test;
import util.Coordinate;
import util.Direction;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ForceFieldSessionTest {
private Grid grid;
private Player player;
private Square north;
private Square south;
private Square west;
private Square center;
@Before
public void setUp() {
grid = new Grid(10, 10);
center = grid.getSquareFrom(new Coordinate(5, 5));
north = center.getNeighbour(Direction.NORTH);
west = center.getNeighbour(Direction.WEST);
south = center.getNeighbour(Direction.SOUTH);
}
/**
* Test that checks if a force field generator in the inventory
* of a player is always inactive and does not influence other force field
* generators.
*/
@Test
public void forceFieldGeneratorInInventoryInactiveTest(){
player = new Player(0, west);
ForceFieldGenerator ffg = new ForceFieldGenerator(west);
new ForceFieldGenerator(south);
player.addToInventory(ffg);
west.removeItem(ffg);
ffg.onPickup(player);
assertFalse(gridHasForceFields());
player.move(Direction.EAST);
assertFalse(gridHasForceFields());
player.move(Direction.NORTH);
assertFalse(gridHasForceFields());
}
private boolean gridHasForceFields(){
for(Square square : grid.getSquares())
for(Item item : square.getItems())
if(item.getClass() == ForceField.class)
return true;
return false;
}
/**
* Test that checks if a player loses when in a force field that was closed,
* has opened and is now closed again.
*/
@Test
public void forceFieldPlayerLostTest(){
player = new Player(0, west);
new ForceFieldGenerator(north);
new ForceFieldGenerator(south);
player.move(Direction.EAST);
ForceField ff = (ForceField)center.getItems()[0];
ff.switchState();
ff.switchState();
ff.switchState();
ff.actionPerformed();
assertTrue(player.hasDied());
}
}
|
/*
* Created by SixKeyStudios
* Added in project Technicalities
* File world.objects.creatures / Creature
* created on 20.5.2019 , 21:33:23
*/
package technicalities.world.objects.creatures;
import technicalities.variables.globals.GlobalVariables;
import technicalities.variables.idls.OIDL;
import technicalities.world.World;
import technicalities.world.objects.TObject;
/**
* Creature
* - abstract class inherited by all living things
* @author filip
*/
public abstract class Creature extends TObject{
////// VARIABLES //////
protected World world;
////// CONSTRUCTORS //////
public Creature(float centerX, float centerY, OIDL id, World world) {
super(centerX, centerY, id);
this.world = world;
}
}
|
package projecteuler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PrimePairSets {
public static void main(String args[]) throws IOException {
Set<Integer> primeSet = new TreeSet<Integer>();
for (int i = 2; i < 1000; i++) {
if (isPrime(i)) {
getPair(i, primeSet);
}
}
System.out.println(primeSet);
}
public static void getPair(int n, Set<Integer> primeSet) {
for (int i = n; i < 1000; i++) {
if (isPrime(i) && isPrime(Integer.parseInt(i + "" + n))
&& isPrime(Integer.parseInt(n + "" + i))) {
primeSet.add(n);
primeSet.add(i);
if (!allPrimePair(primeSet)) {
primeSet.remove(i);
}
}
}
}
public static boolean allPrimePair(Set<Integer> primeSet) {
List<Integer> primeList = new ArrayList<Integer>(primeSet);
for (int i = 0; i < primeList.size(); i++) {
for (int j = i + 1; j < primeList.size(); j++) {
if(isPrime(Integer.parseInt(primeList.get(i) + "" + primeList.get(j)))
&& isPrime(Integer.parseInt(primeList.get(j) + "" + primeList.get(i)))) {
return true;
}
}
}
return false;
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
|
package com.manager.model;
public class ManagerVO implements java.io.Serializable{
private String mg_no;
private String mg_name;
private String mg_title;
private String mg_spec;
private String mg_account;
private String mg_password;
private Integer status;
private byte[] mg_profile_pic;
public String getMg_no() {
return mg_no;
}
public void setMg_no(String mg_no) {
this.mg_no = mg_no;
}
public String getMg_name() {
return mg_name;
}
public void setMg_name(String mg_name) {
this.mg_name = mg_name;
}
public String getMg_title() {
return mg_title;
}
public void setMg_title(String mg_title) {
this.mg_title = mg_title;
}
public String getMg_spec() {
return mg_spec;
}
public void setMg_spec(String mg_spec) {
this.mg_spec = mg_spec;
}
public String getMg_account() {
return mg_account;
}
public void setMg_account(String mg_account) {
this.mg_account = mg_account;
}
public String getMg_password() {
return mg_password;
}
public void setMg_password(String mg_password) {
this.mg_password = mg_password;
}
public byte[] getMg_profile_pic() {
return mg_profile_pic;
}
public void setMg_profile_pic(byte[] mg_profile_pic) {
this.mg_profile_pic = mg_profile_pic;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/* URL
http://www.jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=1360&sca=50&sfl=wr_hit&stx=2097&sop=and
*/
public class Main2097_지하철_dijkstra {
public static void main(String[] args) throws IOException {
PriorityQueue<Station> que = new PriorityQueue<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken())-1;
int[][] distance = new int[n][n];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++)
distance[i][j] = Integer.parseInt(st.nextToken());
}
// 배열 준비
int[] path = new int[n];
int[] dist = new int[n];
Arrays.fill(dist, 99999);
boolean[] visit = new boolean[n];
// 시작점 지정
dist[0] = 0;
que.offer(new Station(0, dist[0]));
// 처리
int from = 0;
int viaCost = 0;
Station temp = null;
while (!que.isEmpty()) {
temp = que.poll();
from = temp.num;
if (visit[from]) continue;
if (from == end) break;
viaCost = temp.cost;
visit[from] = true;
for (int to = 0; to < n; to++) {
if (!visit[to]) {
if (viaCost + distance[from][to] < dist[to]) {
dist[to] = viaCost + distance[from][to];
path[to] = from; // 내 자리에 직전에 누구를 거쳐왔는지 기억, 나를 최적화시킨 직전의 노드
que.offer(new Station(to, dist[to]));
}
}
}
}
// 출력
ArrayList<Integer> print = new ArrayList<>();
print.add(end+1);
int num = end;
do {
num = path[num];
print.add(0, num+1);
} while (num != 0);
System.out.println(dist[end]);
for (Integer su : print) {
System.out.print(su + " ");
}
}
}
class Station implements Comparable<Station> {
int num;
int cost;
public Station(int num, int dist) {
this.num = num;
this.cost = dist;
}
public int compareTo(Station other) {
return this.cost - other.cost;
}
}
|
package com.tpg.brks.ms.expenses.persistence.integration;
import com.tpg.brks.ms.expenses.domain.ExpenseReport;
import com.tpg.brks.ms.expenses.persistence.PersistenceGiven;
import com.tpg.brks.ms.expenses.persistence.entities.AssignmentEntity;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseEntity;
import com.tpg.brks.ms.expenses.persistence.entities.ExpenseReportEntity;
import com.tpg.brks.ms.expenses.persistence.repositories.ExpenseLifecycleRepository;
import com.tpg.brks.ms.expenses.persistence.repositories.ExpenseReportLifecycleRepository;
import com.tpg.brks.ms.expenses.service.converters.ExpenseReportConverter;
import com.tpg.brks.ms.expenses.utils.DateGeneration;
import lombok.Data;
import lombok.Value;
import org.junit.Before;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.Date;
import static com.tpg.brks.ms.expenses.domain.ExpenseType.SUBSISTENCE;
import static java.util.Collections.singletonList;
@Data
public class ExpenseReportIntegrationGiven implements DateGeneration, PersistenceGiven {
private ExpenseReportConverter expenseReportConverter = new ExpenseReportConverter();
@Autowired
private ExpenseReportLifecycleRepository expenseReportLifecycleRepository;
@Autowired
private ExpenseLifecycleRepository expenseLifecycleRepository;
public Pair<ExpenseReportEntity, ExpenseReport> givenAnExpenseReport(AssignmentEntity assignment, Date periodStart, Date periodEnd) {
ExpenseReportEntity expenseReportEntity = anOpenExpenseReport(assignment, "report 1", periodStart, periodEnd);
expenseReportEntity = expenseReportLifecycleRepository.save(expenseReportEntity);
ExpenseEntity expenseEntity = aPendingExpense(expenseReportEntity,"expense 1", generateDate(15, 4, 2017),
generateDate(13, 4, 2017), SUBSISTENCE, new BigDecimal("250.00"));
expenseEntity = expenseLifecycleRepository.save(expenseEntity);
expenseReportEntity.setExpenses(singletonList(expenseEntity));
expenseReportEntity = expenseReportLifecycleRepository.save(expenseReportEntity);
ExpenseReport expenseReport = expenseReportConverter.convert(expenseReportEntity);
return new Pair<>(expenseReportEntity, expenseReport);
}
}
|
import java.util.LinkedList;
import java.util.List;
/*
* @lc app=leetcode.cn id=77 lang=java
*
* [77] 组合
*/
// @lc code=start
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> current = new LinkedList<>();
dfs(res, current, n, k);
return res;
}
public void dfs(List<List<Integer>> res, LinkedList<Integer> current, int n, int k) {
int len = current.size();
int last = current.isEmpty() ? 0 : current.getLast();
if ((n - last) < (k - len))
return;
if (len == k) {
res.add(new LinkedList<>(current));
return;
}
for (int i = last + 1; i <= n; i++) {
current.add(i);
dfs(res, current, n, k);
current.removeLast();
}
}
}
// @lc code=end
|
package java0709;
import java.util.Scanner;
public class Ex03_ArrayEx {
public static void main(String[] args) {
// 크기가 5인 정수형 배열을 선언하여
// 값을 알아서 입력하고
// 입력된 값들의 총합과 평균을 구하시오.
Scanner scan = new Scanner(System.in);
int[] num = new int[5];
int sum = 0;
int ave = 0;
for(int i=0;i<num.length;i++) {
System.out.println("수를 입력하세요:");
num[i] = scan.nextInt();
sum = num[i] +sum;
ave = sum / num.length;
}System.out.println("합계는"+sum+"입니다");
System.out.println("평균은"+ave+"입니다.");
scan.close();
}
}
|
package com.lemonread.base.application;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import java.util.LinkedList;
import java.util.List;
/**
* @desc
* @author zhao
* @time 2019/3/5 10:09
*/
public class BaseApplication extends Application {
private static Context mContext;
private static List<Activity> mActivities = new LinkedList<Activity>();
@Override
public void onCreate() {
super.onCreate();
mContext = this;
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mActivities.add(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
mActivities.remove(activity);
}
});
}
public static Context getContext() {
return mContext;
}
public static synchronized void clearAllActivities() {
for (int i = mActivities.size() - 1; i > -1; i--) {
Activity activity = mActivities.get(i);
activity.finish();
i = mActivities.size();
}
mActivities.clear();
}
//清除除MainActivity以外的所有activity
public static synchronized void clearToMainActivity() {
for (int i = mActivities.size() - 1; i > 0; ) {
Activity activity = mActivities.get(i);
removeActivity(activity);
activity.finish();
i = mActivities.size() - 1;
}
}
public static int getAllActivitiesCount() {
return mActivities.size();
}
public static synchronized void removeActivity(Activity activity) {
if (mActivities.contains(activity)) {
mActivities.remove(activity);
}
}
}
|
package org.davidmoten.io.extras;
import java.io.IOException;
@FunctionalInterface
public interface IOFunction<S, T> {
T apply(S s) throws IOException;
}
|
package exercicio07;
public class SomadorExistente
{
public int somaLista(int [] Lista)
{
int resultado = 0;
for(int i : Lista) resultado +=i;
return resultado;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.