text stringlengths 10 2.72M |
|---|
package com.dbs.portal.database.to.common;
import java.util.HashMap;
import java.util.Map;
public class GlobalPortletDataTransfer {
private Map<String, Object> portletSession = new HashMap<String, Object>();
private static GlobalPortletDataTransfer instance = null;
private GlobalPortletDataTransfer(){}
public static GlobalPortletDataTransfer getInstance(){
synchronized (GlobalPortletDataTransfer.class) {
if (instance == null)
instance = new GlobalPortletDataTransfer();
}
return instance;
}
public void setAttribute(String key, Object value){
portletSession.put(key, value);
}
public Object getAttribute(String key){
return portletSession.get(key);
}
public void removeAttribute(String key){
portletSession.remove(key);
}
}
|
package com.li.sort;
public class SimpleSort {
/**
* 并归排序 思想两段已经排好序的子序列合并
* 注意 子序列合并的细节
*
* @param a
* @param left
* @param rigth
* @param end
*/
private static void merge(int a[], int left, int rigth, int end) {
int n1 = rigth - left + 1;
int n2 = end - rigth;
int[] le = new int[n1];
int[] re = new int[n2];
for (int i = 0; i < n1; i++) {
le[i] = a[left + i];
}
for (int i = 0; i < n2; i++) {
re[i] = a[rigth + 1 + i];
}
int i = 0, j = 0;
int p = left;
while (i < n1 && j < n2) {
if (le[i] >= re[j]) {
a[p++] = re[j++];
} else {
a[p++] = le[i++];
}
}
if (i >= n1) {
for (; j < n2; j++) {
a[p++] = re[j];
}
} else {
for (; i < n1; i++) {
a[p++] = le[i];
}
}
}
private static void mergeSort(int[] a, int start, int end) {
if (end > start) {
int q = (end + start) / 2;
mergeSort(a, start, q);
mergeSort(a, q + 1, end);
merge(a, start, q, end);
}
}
/**
* 快速排序 思想是找出一个参照值将小于的放一旁
* 注意参照值的放回
*
* @param args
*/
public static void quickSort(int[] a, int start, int end) {
if (end > start) {
int i = sort(a, start, end);
quickSort(a, start, i-1);
quickSort(a, i+1, end);
}
}
public static void swap(int[] a, int start, int end) {
int flag = a[start];
a[start] = a[end];
a[end] = flag;
}
public static int sort(int[] a, int start, int end) {
int flag = a[start];
int k = start;
for (int i = start + 1; i <= end; i++) {
if (flag > a[i]) {
if (++k != i) {
swap(a, k, i);
}
}
}
swap(a, start, k);
return k;
}
/**
*最大堆
*/
public static int left(int i) {
return 2 * i;
}
public static int rigth(int i) {
return 2 * i + 1;
}
public static int parent(int i) {
return i / 2;
}
public static void shiftdown(int[] a, int i, int n) {
int l = left(i);
int r = rigth(i);
int flag = l;
if (r < n && a[l] < a[r]) {
flag = r;
}
if (flag < n && a[i] < a[flag]) {
swap(a, i, flag);
shiftdown(a, flag, n);
}
}
public static void maxHeap(int[] a, int n) {
for (int i = n / 2; i > 0; i--) {
shiftdown(a, i, n);
}
}
public static void heapSort(int[] a,int n){
maxHeap(a,n);
for(int i=n-1;i>1;i--){
swap(a,1,i);
shiftdown(a,1,i);
}
}
public static void main(String[] args) {
int[] a = {-1, 2, 4, 6, 8, 1, 3, 5, 7};
/* shiftdown(a, 1, a.length);
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + ",");*/
heapSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + ",");
}
}
|
package org.base.utils;
import org.reststackteam.reststack.exception.RuntimeExceptionWarning;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 时间相关的工具类.
*/
public class TimeUtil {
public static SimpleDateFormat YYYY_MM_DD = new SimpleDateFormat("yyyy-MM-dd");
public static SimpleDateFormat YYYY_MM_DD_HH_mm_ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final Integer[] WEEK_NUMBER = {7,1,2,3,4,5,6};
public static Date getIntervalTime(Integer days){
if(days == null){
days = 0;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DATE,days);
return calendar.getTime();
}
public static long[] differTimes(Date start,Date end){
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
long time1 = start.getTime();
long time2 = end.getTime();
long diff ;
if(time1<time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = diff / (60 * 60 * 1000);
min = diff / (60 * 1000);
sec = diff/1000;
long[] times = {day, hour, min, sec};
return times;
}
/**
* 获取起始时间
* @param time
* @return
*/
public static Date getTimeStart(String time){
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(YYYY_MM_DD.parse(time));
calendar.set(Calendar.HOUR_OF_DAY,0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MINUTE,0);
return calendar.getTime();
} catch (Exception e) {
throw new RuntimeExceptionWarning(ServerStatus.PARAM_IS_FAIL,"时间格式有误");
}
}
/**
* 获取结束时间
* @param time
* @return
*/
public static Date getTimeEnd(String time){
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(YYYY_MM_DD.parse(time));
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.SECOND,59);
calendar.set(Calendar.MINUTE,59);
return calendar.getTime();
} catch (Exception e) {
throw new RuntimeExceptionWarning(ServerStatus.PARAM_IS_FAIL,"时间格式有误");
}
}
/**
* 校验时间段是否合法
* @param start
* @param end
* @return 起始时间>结束时间返回true 否则返回false
*/
public static boolean validDatePeriod(Date start,Date end){
if(StrUtil.isNull(start) || StrUtil.isNull(end)){
throw new RuntimeExceptionWarning(ServerStatus.PARAM_IS_NULL,"时间信息不能为空");
}
return start.getTime()>end.getTime();
}
/**
* 获取一天的开始时间 如2013-12-11 02:23 返回2013-12-11 00:00:00
* @param date 处理的时间
* @return
*/
public static Date dateToStartTime(Date date){
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE,0);
gc.set(Calendar.SECOND,0);
return gc.getTime();
}
/**
* 计算日期往后推几天的日期
* @param afterDays 后推
* @param date 计算的日期
* @return Date
*/
public static Date afterDate(int afterDays,Date date){
GregorianCalendar gc = new GregorianCalendar();
gc.setTimeInMillis(date.getTime());
gc.add(Calendar.DATE, afterDays);
return gc.getTime();
}
/**
* 格式化时间为标准的格式串
* @param date 日期时间
* @return yyyy-MM-dd HH:mm:ss
*/
public static String formatDate(Date date){
return YYYY_MM_DD_HH_mm_ss.format(date);
}
/**
* 格式化时间为标准的格式串
* @param date 日期时间
* @return yyyy-MM-dd
*/
public static String formatDate1(Date date){
return YYYY_MM_DD.format(date);
}
/**
* 获取周以及对应的年份
* @param date
* @param preWeeks
* @return
*/
public static Integer[] yearAndWeek(Date date,int preWeeks){
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(7);
calendar.setTime(date);
calendar.add(Calendar.WEEK_OF_YEAR,-preWeeks);
Integer week = calendar.get(Calendar.WEEK_OF_YEAR);
Integer month = calendar.get(Calendar.MONTH)+1;
if(week!=1 && month==1){
//跨年周自动归并去年
return new Integer[]{calendar.get(Calendar.YEAR)-1,week};
}
return new Integer[]{calendar.get(Calendar.YEAR),week};
}
public static Date afterMoth(Date date,int moths){
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(7);
calendar.setTime(date);
calendar.add(Calendar.MONTH,moths);
return calendar.getTime();
}
/**
* 周几
* @param date
* @return
*/
public static Integer dayOfWeek(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
@Deprecated
public static Integer totalDayOfYear(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(7);
calendar.setTime(date);
return calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
}
/**
* 一年的第几周时间段
* @param year
* @param week
* @return
*/
public static Date[] dateWeekSegment(Integer year,Integer week){
Date first = getTimeStart(year + "-" + "01-01 00:00:00");
Integer dayOfWeek = dayOfWeek(first);
int w = WEEK_NUMBER[dayOfWeek-1];
if(w==1){
//1月1号就是周一的时候
w = 8;
}
int diff = 7-w;
Date firstMonday = afterDate(diff + 1, first);
Date weekStart = afterDate((week-1)*7,firstMonday);
Date weekEnd = afterDate(7,weekStart);
return new Date[]{weekStart,weekEnd};
}
/**
* 获取当前日期年份
* @param date
* @return
*/
public static Integer year(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static Date getIntervalDay(Date date,int intervalDay){
if(date==null){
return date;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, intervalDay);
return c.getTime();
}
public static void main(String[] args){
Date old=getTimeStart("2012-10-31 00:00:00");
System.out.println(formatDate(afterMoth(old,1)));
}
}
|
package com.ff.factoryimage;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.ff.factoryimage.utils.LogUtil;
import com.ff.factoryimage.utils.ImageUtil;
import com.ff.factoryimage.utils.FileUtil;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private static final String IMAGE_PATH = "imagePath";
private static final String SHOW_BUTTON = "showButton";
private static final String COMPRESS = "compress";
private static final int REQUEST_CODE = 200;
private static final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
, Manifest.permission.READ_EXTERNAL_STORAGE};
private Button btnShowQRcode;
private ImageView mImageViewContent;
private String mImagePath;
private boolean isShowButton = false;//default not show
private boolean needCompress = true;//default need
private Bitmap mBitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowQRcode = findViewById(R.id.btn_show_qrcode);
btnShowQRcode.setOnClickListener(this);
mImageViewContent = findViewById(R.id.iv_content);
checkPermission();
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED) {
LogUtil.d("lack permission");
ActivityCompat.requestPermissions(this,
permissions, REQUEST_CODE);
} else {
dealIntent();
}
} else {
dealIntent();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
LogUtil.d("onRequestPermissionsResult " + permissions[i] + " does not grant");
Toast.makeText(this, R.string.need_permission_tips, Toast.LENGTH_LONG).show();
break;
} else if (i == grantResults[grantResults.length - 1]) {
//last permission
LogUtil.d("onRequestPermissionsResult get all permission");
dealIntent();
}
}
}
}
}
private void dealIntent() {
LogUtil.d(TAG, "deal intent");
Intent intent = getIntent();
LogUtil.d(TAG, "intent = " + intent);
if (intent.hasExtra(IMAGE_PATH)) {
mImagePath = intent.getStringExtra(IMAGE_PATH);
}
if (intent.hasExtra(SHOW_BUTTON)) {
isShowButton = intent.getBooleanExtra(SHOW_BUTTON, false);
}
if (intent.hasExtra(COMPRESS)) {
needCompress = intent.getBooleanExtra(COMPRESS, true);
}
LogUtil.d(TAG, "mImagePath = " + mImagePath + " isShowButton = " + isShowButton + " needCompress = " + needCompress);
if (!TextUtils.isEmpty(mImagePath)) {
if (FileUtil.pathExist(mImagePath)) {
if (needCompress) {
mBitmap = ImageUtil.getBitmapFromPath(this, mImagePath);
} else {
mBitmap = ImageUtil.getBitmapFromPath(this, mImagePath, false);
}
LogUtil.d(TAG, "mBitmap = " + mBitmap);
} else {
// file does not exsist
LogUtil.d(mImagePath + " does not exist");
Toast.makeText(this, R.string.file_does_not_exist, Toast.LENGTH_LONG).show();
}
} else {
//no file
LogUtil.d(" The value of imagePath is null");
Toast.makeText(this, R.string.file_does_not_exist, Toast.LENGTH_LONG).show();
}
if (isShowButton) {
mImageViewContent.setVisibility(View.GONE);
} else {
mImageViewContent.setImageBitmap(mBitmap);
mImageViewContent.setBackgroundColor(Color.WHITE);
}
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_show_qrcode) {
mImageViewContent.setVisibility(View.VISIBLE);
mImageViewContent.setBackgroundColor(Color.WHITE);
mImageViewContent.setImageBitmap(mBitmap);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mBitmap != null && !mBitmap.isRecycled()){
LogUtil.d("recycle mBitmap");
mBitmap.recycle();
}
}
}
|
package codesquad.web;
import codesquad.support.test.AcceptanceTest;
import codesquad.support.test.HtmlFormDataBuilder;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class RedirectControllerTest extends AcceptanceTest {
HtmlFormDataBuilder builder;
@Before
public void setUp() throws Exception {
builder = HtmlFormDataBuilder.urlEncodedForm();
}
@Test
public void login(){
requestToRedirectController(UserControllerAcceptanceTest.LOGIN_URL,HttpStatus.OK,"로그인");
}
@Test
public void signup(){
requestToRedirectController(UserControllerAcceptanceTest.SIGNUP_URL,HttpStatus.OK,"가입 완료");
}
@Test
public void home(){
requestToRedirectController("/",HttpStatus.OK,"메인반찬 전체보기");
}
private void requestToRedirectController(String url, HttpStatus status, String confirm){
HttpEntity<MultiValueMap<String,Object>> request = builder.build();
ResponseEntity<String> responseEntity = template().getForEntity(url,String.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(status);
assertThat(responseEntity.getBody().contains(confirm)).isEqualTo(true);
}
} |
/*
* Copyright 2020 WeBank
*
* 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.webank.wedatasphere.schedulis.common.log;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
public enum LogCodeType {
INFO(1),
ERROR(2),
OTHER(999);
private final int codeNum;
LogCodeType(final int codeNum) {
this.codeNum = codeNum;
}
public int getCodeNum() {
return this.codeNum;
}
private static final ImmutableMap<Integer, LogCodeType> codeTypeNumMap = Arrays.stream(LogCodeType.values())
.collect(ImmutableMap.toImmutableMap(codeType -> codeType.getCodeNum(), codeType -> codeType));
public static LogCodeType fromInteger(final int x) {
return codeTypeNumMap.getOrDefault(x, OTHER);
}
}
|
package com.animation.app.view;
/**
* Created by sukenda on 15/08/16.
*/
public class App {
}
|
package rs2.net.packet.impl;
import rs2.model.game.entity.character.player.Player;
import rs2.net.packet.Packet;
import rs2.net.packet.PacketManager.PacketHandler;
/**
*
* @author Jake Bellotti
* @since 1.0
*/
public class FlashingSideIconHandler implements PacketHandler {
public static final int FLASH_ICON = 152;
@Override
public void handlePacket(Player player, Packet packet) {
}
}
|
package pojo.valueObject.assist;
import pojo.valueObject.domain.StudentVO;
import pojo.valueObject.domain.TeamVO;
import javax.persistence.*;
/**
* Created by geyao on 2017/2/19.
*/
@Entity
@Table(name = "student_team")
public class StudentTeamVO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@ManyToOne(targetEntity = StudentVO.class)
@JoinColumn(name = "studentId", referencedColumnName = "id")
private StudentVO studentVO;
@ManyToOne(targetEntity = TeamVO.class)
@JoinColumn(name = "teamId", referencedColumnName = "id")
private TeamVO teamVO;
private Boolean leaderFlag;
public StudentTeamVO() {
super();
}
@Override
public String toString() {
return "StudentTeamVO{" +
"id=" + id +
", studentVO=" + studentVO.getId() +
", teamVO=" + teamVO.getId() +
", leaderFlag=" + leaderFlag +
'}';
}
public StudentVO getStudentVO() {
return studentVO;
}
public void setStudentVO(StudentVO studentVO) {
this.studentVO = studentVO;
}
public TeamVO getTeamVO() {
return teamVO;
}
public void setTeamVO(TeamVO teamVO) {
this.teamVO = teamVO;
}
public Boolean getLeaderFlag() {
return leaderFlag;
}
public void setLeaderFlag(Boolean leaderFlag) {
this.leaderFlag = leaderFlag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
package application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.swing.JSpinner.ListEditor;
import enums.Orientation;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import models.Mur;
public class ControlleurNiveaux implements Initializable{
String home = System.getProperty("user.home");
File settings_file = new File(home, "shapesinthemazes_niveaux.txt");
public AnchorPane init(AnchorPane root, Main_Exercice_03 main) {
final Scene scene = root.getScene();
FileReader fr = null;
root.getChildren().clear();
ScrollPane sc = new ScrollPane();
sc.setHbarPolicy(ScrollBarPolicy.NEVER);
sc.setVbarPolicy(ScrollBarPolicy.ALWAYS);
sc.setPrefHeight(435);
VBox vb = new VBox();
vb.setPrefSize(580, 435);
HBox hb = null;
Label l = null;
AnchorPane preview = null;
AnchorPane fullGame = null;
final Map<Node, AnchorPane> tableauDesNiveaux = new HashMap<>();
try {
fr = new FileReader(settings_file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while(s != null){
if (s.startsWith("#") || s.trim().equals("")){
}
else if(s.startsWith("[")){
if (hb != null){
hb.getChildren().add(preview);
vb.getChildren().add(hb);
tableauDesNiveaux.put(preview, fullGame);
preview.setOnMouseClicked(a -> {
Controlleur ct = new Controlleur();
ct.init();
final Rectangle r0 = ct.getR0();
AnchorPane root_ = tableauDesNiveaux.get(a.getSource());
root_.getChildren().add(0, r0);
scene.setRoot(root_);
Stage stagePrincipal = (Stage) scene.getWindow();
stagePrincipal.setWidth(1000);
stagePrincipal.setHeight(600);
root.setOnMouseClicked(e -> main.gerer_clicks(r0, e));
scene.setOnKeyPressed(e1 -> main.gerer_keys(r0, e1, root_, stagePrincipal));
});
}
hb = new HBox();
hb.setPadding(new Insets(20));
preview = new AnchorPane();
preview.setPrefWidth(200);
preview.setPrefHeight(120);
preview.getChildren().add(new Rectangle(200,120, Color.WHITE));
fullGame = new AnchorPane();
fullGame.setPrefWidth(1000);
fullGame.setPrefHeight(600);
l = new Label(s.split("\\[")[1].split("\\]")[0] + " : ");
hb.getChildren().add(l);
}
else {
String ligne = s.split("=")[1];
Orientation or = Orientation.valueOf(ligne.split(",")[0].trim());
int epais = Integer.parseInt(ligne.split(",")[1].trim());
int dist = Integer.parseInt(ligne.split(",")[2].trim());
int debut = Integer.parseInt(ligne.split(",")[3].trim());
int fin = Integer.parseInt(ligne.split(",")[4].trim());
fullGame.getChildren().add(new Mur(or, epais, dist, debut, fin, null));
epais = epais / 5;
dist = dist / 5;
debut = debut / 5;
fin = fin / 5;
preview.getChildren().add(new Mur(or, epais, dist, debut, fin, null));
}
s = br.readLine();
}
hb.getChildren().add(preview);
vb.getChildren().add(hb);
tableauDesNiveaux.put(preview, fullGame);
preview.setOnMouseClicked(a -> {
Controlleur ct = new Controlleur();
ct.init();
final Rectangle r0 = ct.getR0();
AnchorPane root_ = tableauDesNiveaux.get(a.getSource());
root_.getChildren().add(0, r0);
scene.setRoot(root_);
Stage stagePrincipal = (Stage) scene.getWindow();
stagePrincipal.setWidth(1000);
stagePrincipal.setHeight(600);
root.setOnMouseClicked(e -> main.gerer_clicks(r0, e));
scene.setOnKeyPressed(e1 -> main.gerer_keys(r0, e1, root_, stagePrincipal));
});
} catch (IOException e) {
// TODO Bloc catch généré automatiquement
e.printStackTrace();
}
sc.setContent(vb);
root.getChildren().add(sc);
return root;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
} |
package com.example.kamil.ebookyourchildshealth.activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.example.kamil.ebookyourchildshealth.R;
/**
* Created by kamil on 2016-10-31.
*/
public class MyActivityOnlyMenuImplemented extends AppCompatActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_about) {
return true;
}
else if (id == R.id.action_main_panel) {
openMainActivity();
return true;
}
else if (id == R.id.action_author) {
openActivityUrlAddress();
return true;
}
else if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void openMainActivity() {
Intent intent = new Intent(this,ChooseChildMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void openActivityUrlAddress() {
Uri url = Uri.parse("https://www.facebook.com/kamilosdzialek");
Intent intent = new Intent(Intent.ACTION_VIEW, url);
startActivity(intent);
}
} |
import java.util.Scanner;
public class Task02_BeerAndChips {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
double budget = Double.parseDouble(scan.nextLine());
int bottles = Integer.parseInt(scan.nextLine());
int packetChips = Integer.parseInt(scan.nextLine());
double beerTotalPrice = 1.20 * bottles;
double priceChipsPacket = beerTotalPrice * 0.45;
double chipsPrice = Math.ceil(priceChipsPacket * packetChips);
double totalPrice = beerTotalPrice + chipsPrice;
if (totalPrice <= budget) {
System.out.printf("%s bought a snack and has %.2f leva left.", name, budget-totalPrice);
} else {
System.out.printf("%s needs %.2f more leva!", name, totalPrice-budget);
}
}
} |
package com.lmz.selenilum;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.JavascriptExecutor;
public class video {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver() ;
Thread.sleep(4000);
driver.get("https://videojs.com");
Thread.sleep(4000);
WebElement video =driver.findElement(By.xpath("//*[@id=\"preview-player_html5_api\"]"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
//获得视频的URL
jse.executeScript("return arguments[0].currentSrc;",video);
Thread.sleep(6000);
//播放视频,播放15秒
jse.executeScript("return arguments[0].play();",video);
Thread.sleep(15000);
jse.executeScript("arguments[0].pause()",video);
driver.quit();
}
}
|
package com.mercadolibre.bootcampmelifrescos.repository;
import com.mercadolibre.bootcampmelifrescos.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByUserName(final String userName);
@Override
void delete(User user);
}
|
package co.id.datascrip.mo_sam_div4_dts1.process.interfaces;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface IC_Customer {
String URL_FIND_CUSTOMER = "customer_find",
URL_GET_NO_CUSTOMER = "customer_get_no",
URL_SAVE_CUSTOMER = "customer_save";
@FormUrlEncoded
@POST(URL_FIND_CUSTOMER)
Call<ResponseBody> Find(@Field("sistem") String sistem, @Field("json") String json);
@FormUrlEncoded
@POST(URL_GET_NO_CUSTOMER)
Call<ResponseBody> Get_No(@Field("json") String json);
@FormUrlEncoded
@POST(URL_SAVE_CUSTOMER)
Call<ResponseBody> Post(@Field("json") String json);
}
|
package com.quaspecsystems.payspec.persistence.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "privilege")
@Entity(name = "privilege")
public class Privilege {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
protected Long id;
@Column(name = "version", nullable = false)
protected int version;
@Column(name = "name", nullable = false, unique=true)
protected String name;
@Column(name = "description")
protected String description;
public Privilege() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object object) {
if(object instanceof Privilege && ((Privilege)object).getId().equals(this.id)){
return true;
}
return false;
}
@Override
public String toString() {
return "Privilege [name=" + name + ", description=" + description + "]";
}
}
|
package com.news.demo.Utils.Result;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class ResultMap {
public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
return obj;
}
public static Object mapToObjectV2(Map<String, String> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;
Object obj = beanClass.newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}
return obj;
}
public static Map<String, Object> objectToMap(Object obj) throws Exception {
Map<String, Object> map = new HashMap();
for (Field field : obj.getClass().getDeclaredFields()) {
try {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object o = field.get(obj);
map.put(field.getName(), o);
field.setAccessible(flag);
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}
}
|
package pw.react.backend;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import pw.react.backend.service.HttpClient;
import pw.react.backend.web.Quote;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
@ActiveProfiles(profiles = {"mysql-dev"})
class SampleBackendApplicationTests {
@Autowired
private HttpClient httpService;
@Test
void contextLoads() {
}
@Test
void whenConsume_thenReturnQuote() {
final Quote quote = httpService.consume("");
assertThat(quote).isNotNull();
}
}
|
package com.example.edvisor;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Customer_login extends AppCompatActivity {
Customer customer;
ArrayList<Edvisor> worker=new ArrayList<>();
ArrayList<Edvisor> workerdb=new ArrayList<>();
Intent intentpast ;
ArrayList<Edvisor>[] a2 ;
Intent intent;
FirebaseDatabase database=FirebaseDatabase.getInstance();
DatabaseReference myRef=database.getReference().child("worker");
DatabaseReference myRef2=database.getReference().child("customer");
DatabaseReference myRef3=database.getReference().child("booking");
ArrayList<Booking> bookingdb=new ArrayList<>();
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
workerdb = (ArrayList<Edvisor>) intent.getSerializableExtra("worker");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
Intent intent = getIntent();
//customer = (Customer) intent.getSerializableExtra("customer");
//worker = (ArrayList<Edvisor>) intent.getSerializableExtra("worker");
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("service"));
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("worker db ");
System.out.println((ArrayList<Edvisor>) dataSnapshot.getValue());
for(DataSnapshot snap:dataSnapshot.getChildren())
{
workerdb.add(snap.getValue(Edvisor.class));
}
System.out.println("children"+workerdb);
System.out.println(workerdb.getClass());
Intent intent2 = new Intent("service");
intent2.putExtra("worker",workerdb);
}
@Override
public void onCancelled(DatabaseError error) {
System.out.println("failed to connect");
}
});
///////////////////////////////////////////////////// current booking
}
public void Book_Appointment(View v) {
Intent intent = new Intent(this,BookAppointment.class);
intent.putExtra("customer",customer);
intent.putExtra("worker",workerdb);
startActivity(intent);
}
public void Show_Booking_Appointments(View v) {
intent = new Intent(this,Show_current_Booking.class);
intent.putExtra("customer",customer);
intent.putExtra("worker",worker);
myRef3.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snap:dataSnapshot.getChildren())
{
bookingdb.add(snap.getValue(Booking.class));
}
System.out.println("children"+bookingdb);
intent.putExtra("booking",bookingdb);
startActivity(intent);
}
@Override
public void onCancelled(DatabaseError error) {
System.out.println("failed to connect");
}
});
}
public void chat(View v)
{
Intent intent = new Intent(this,Send_chat.class);
startActivity(intent);
}
public void Show_Booking_Past(View v) {
intentpast = new Intent(this,Past_Appointments.class);
intentpast.putExtra("customer",customer);
intentpast.putExtra("worker",worker);
startActivity(intentpast);
}
public void Connect(View v)
{
Intent intent = new Intent(this,SiteWebView.class);
startActivity(intent);
}
} |
package com.redis.SpringBootRedis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
//@Component
public class RedisRun implements CommandLineRunner {
@Autowired
private RedisTemplate<String, String> redis;
@Override
public void run(String... args) throws Exception {
redis.opsForValue().set("key123", "value123");
String string = redis.opsForValue().get("key123");
System.out.println(string);
System.out.println("assasa");
}
}
|
package com.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.dao.CategoryDao;
import com.model.Category;
import com.model.Customer;
@Controller
public class HomeController {
@Autowired
CategoryDao category;
@ModelAttribute("catg")
public Category grtcatg()
{
return new Category();
}
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView home()
{
ModelAndView model=new ModelAndView("home");
List<Category> c=category.getAllCategory();
model.addObject("catg", c);
return model;
}
@RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView h() {
ModelAndView model=new ModelAndView("home");
List<Category> c=category.getAllCategory();
model.addObject("catg", c);
return model;
}
@RequestMapping("/about")
public String about()
{
return "about";
}
public String doProcess(){
return "success";
}
public ModelAndView doCancel(){
ModelAndView model=new ModelAndView("home");
List<Category> c=category.getAllCategory();
model.addObject("catg", c);
return model;
}
}
|
package com.dollarsbank.servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.dollarsbank.controller.AccountController;
import com.dollarsbank.controller.TransactionController;
import com.dollarsbank.model.Account;
import com.dollarsbank.model.Customer;
import com.dollarsbank.model.Transaction;
/**
* Servlet implementation class AccountServlet
*/
public class AccountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
HttpSession session;
/**
* @see HttpServlet#HttpServlet()
*/
public AccountServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
session = request.getSession(true);
ArrayList<Customer> customers = (ArrayList<Customer>) session.getAttribute("allCustomers");
ArrayList<Account> accounts = (ArrayList<Account>) session.getAttribute("allAccounts");
ArrayList<Transaction> transactions = (ArrayList<Transaction>) session.getAttribute("allTransactions");
session.setAttribute("allCustomers",customers);
session.setAttribute("allAccounts",accounts);
session.setAttribute("allTransactions",transactions);
Customer customer = (Customer) session.getAttribute("currentCustomer");
Account account = (Account) session.getAttribute("currentAccount");
ArrayList<Transaction> trans = (ArrayList<Transaction>) session.getAttribute("currentTransactions");
session.setAttribute("currentCustomer", customer);
session.setAttribute("currentAccount", account);
session.setAttribute("currentTransactions", trans);
String selection = request.getParameter("selection");
switch(selection) {
case "deposit":
deposit(request,response,accounts,transactions,account);
break;
case "withdraw":
withdraw(request,response,accounts,transactions,account);
break;
case "transfer":
transfer(request,response,accounts,transactions,account);
break;
case "customertransactions":
customerTransactions(request,response,accounts,transactions,account);
break;
case "info":
info(request,response);
break;
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
private void deposit(HttpServletRequest request, HttpServletResponse response, ArrayList<Account> accounts1,
ArrayList<Transaction> transactions, Account account1) throws ServletException, IOException {
Account account = account1;
ArrayList<Account> accounts = accounts1;
AccountController acc = new AccountController(accounts);
double balance = acc.findAccountByAccountId(account.getAccountId()).getBalance();
double deposit = Double.parseDouble(request.getParameter("deposit"));
acc.findAccountByAccountId(account.getAccountId()).setBalance(balance + deposit);
session.setAttribute("currentAccount", acc.findAccountByAccountId(account.getAccountId()));
accounts = acc.getAccounts();
session.setAttribute("allAccounts",accounts);
RequestDispatcher dispatcher = request.getRequestDispatcher("account.jsp");
dispatcher.forward(request, response);
}
private void withdraw(HttpServletRequest request, HttpServletResponse response, ArrayList<Account> accounts1,
ArrayList<Transaction> transactions, Account account1) throws ServletException, IOException {
Account account = account1;
double balance = account.getBalance();
double withdraw = Double.parseDouble(request.getParameter("withdraw"));
account.setBalance(balance - withdraw);
session.setAttribute("currentAccount", account);
RequestDispatcher dispatcher = request.getRequestDispatcher("account.jsp");
dispatcher.forward(request, response);
}
private void transfer(HttpServletRequest request, HttpServletResponse response, ArrayList<Account> accounts1,
ArrayList<Transaction> transactions, Account account1) throws ServletException, IOException {
Account account = (Account) session.getAttribute("currentAccount");
double balance = account.getBalance();
double transfer = Double.parseDouble(request.getParameter("transfer"));
account.setBalance(balance - transfer);
session.setAttribute("currentAccount", account);
int accountId = Integer.parseInt(request.getParameter("accountId"));
@SuppressWarnings("unchecked")
ArrayList<Account> accounts = accounts1;
AccountController acc = new AccountController(accounts);
Account transferAccount = acc.findAccountByAccountId(accountId);
double tbalance = transferAccount.getBalance();
transferAccount.setBalance(tbalance + transfer);
RequestDispatcher dispatcher = request.getRequestDispatcher("account.jsp");
dispatcher.forward(request, response);
}
private void customerTransactions(HttpServletRequest request, HttpServletResponse response, ArrayList<Account> accounts,
ArrayList<Transaction> transactions1, Account account1) throws ServletException, IOException {
Account account = (Account) session.getAttribute("currentAccount");
ArrayList<Transaction> transactions = transactions1;
TransactionController tran = new TransactionController(transactions);
ArrayList<Transaction> lastFive = tran.findLastFiveTransactionsByAccountId(account.getAccountId());
System.out.println(lastFive.toString());
session.setAttribute("lastfive", lastFive);
RequestDispatcher dispatcher = request.getRequestDispatcher("account.jsp");
dispatcher.forward(request, response);
}
private void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
Customer customer = (Customer) session.getAttribute("currentCustomer");
request.setAttribute("customerInfo", customer);
RequestDispatcher dispatcher = request.getRequestDispatcher("account.jsp");
dispatcher.forward(request, response);
}
}
|
//jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team support@jdownloader.org
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
package jd.plugins.decrypter;
import java.util.ArrayList;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.parser.html.Form;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterException;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "kyc.pm" }, urls = { "http://(www\\.)?kyc\\.pm/[A-Za-z0-9]+" })
public class KycPm extends PluginForDecrypt {
public KycPm(PluginWrapper wrapper) {
super(wrapper);
}
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
final String parameter = param.toString();
this.br.setFollowRedirects(false);
br.getPage(parameter);
if (br.getHttpConnection().getResponseCode() == 404 || br.toString().length() < 30) {
try {
decryptedLinks.add(this.createOfflinelink(parameter));
} catch (final Throwable e) {
/* Not available in old 0.9.581 Stable */
}
return decryptedLinks;
}
String dllink = this.br.getRedirectLocation();
if (dllink != null && dllink.contains("kyc.pm/")) {
/* Should never happen */
br.getPage(dllink);
dllink = null;
}
if (dllink == null) {
boolean failed = true;
for (int i = 0; i <= 2; i++) {
final Form dlform = br.getForm(0);
final String captchaurl = br.getRegex("(/captcha\\.php\\?[^<>\"]*?)\"").getMatch(0);
if (dlform == null || captchaurl == null) {
return null;
}
final String code = getCaptchaCode(captchaurl, param);
dlform.put("ent_code", code);
br.submitForm(dlform);
if (br.containsHTML("/captcha\\.php")) {
continue;
}
failed = false;
break;
}
if (failed) {
throw new DecrypterException(DecrypterException.CAPTCHA);
}
dllink = br.getRegex("name=\"next\" action=\"(http[^<>\"]*?)\"").getMatch(0);
}
if (dllink == null) {
return null;
}
decryptedLinks.add(createDownloadlink(dllink));
return decryptedLinks;
}
}
|
/*
* LcmsScormSequenceService.java 1.00 2011-09-05
*
* Copyright (c) 2011 ???? Co. All Rights Reserved.
*
* This software is the confidential and proprietary information
* of um2m. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the license agreement
* you entered into with um2m.
*/
package egovframework.adm.lcms.cts.service;
import java.util.List;
import java.util.Map;
import egovframework.adm.lcms.cts.domain.LcmsScormSequence;
/**
* <pre>
* system :
* menu :
* source : LcmsScormSequenceService.java
* description :
* </pre>
* @version
* <pre>
* 1.0 2011-09-05 created by ?
* 1.1
* </pre>
*/
public interface LcmsScormSequenceService {
List selectLcmsScormSequencePageList(Map<String, Object> commandMap) throws Exception;
int selectLcmsScormSequencePageListTotCnt(Map<String, Object> commandMap) throws Exception;
List selectLcmsScormSequenceList(Map<String, Object> commandMap) throws Exception;
Object selectLcmsScormSequence( Map<String, Object> commandMap) throws Exception;
Object insertLcmsScormSequence( Map<String, Object> commandMap) throws Exception;
int updateLcmsScormSequence( Map<String, Object> commandMap) throws Exception;
int updateFieldLcmsScormSequence( Map<String, Object> commandMap) throws Exception;
int deleteLcmsScormSequence( Map<String, Object> commandMap) throws Exception;
int deleteLcmsScormSequenceAll(Map<String, Object> commandMap) throws Exception;
Object existLcmsScormSequence( LcmsScormSequence lcmsScormSequence) throws Exception;
Map selectLcmsScormSequenceSeqIdxNum( Map<String, Object> commandMap) throws Exception;
}
|
package gov.usgs.earthquake.nshmp.site.www.basin;
/**
* Container class for basin term values:
* - z1p0
* - z2p5
*
* @author Brandon Clayton
*/
public class BasinValues {
final BasinValue z1p0;
final BasinValue z2p5;
public BasinValues(BasinValue z1p0, BasinValue z2p5) {
this.z1p0 = z1p0;
this.z2p5 = z2p5;
}
/**
* Container class for a single basin term.
*/
public static class BasinValue {
final String model;
final Double value;
public BasinValue(String model, Double value) {
this.model = model;
this.value = value;
}
}
}
|
package com.ideaheap.lemkeHowson;
import java.util.ArrayList;
import java.util.List;
/**
* User: nwertzberger
* Date: 2/6/13
* Time: 8:41 PM
*/
public class PayoffPair {
public List<List<Double>> p1Payoffs = new ArrayList<List<Double>>();
public List<List<Double>> p2Payoffs = new ArrayList<List<Double>>();
public PayoffPair() {
}
public PayoffPair(List<List<Double>> p1Payoffs, List<List<Double>> p2Payoffs) {
if (p1Payoffs != null) this.p1Payoffs = p1Payoffs;
if (p2Payoffs != null) this.p2Payoffs = p2Payoffs;
}
/* Begin Auto-generated code */
@Override
public String toString() {
return "{" +
"p1Payoffs=" + p1Payoffs +
", p2Payoffs=" + p2Payoffs +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PayoffPair that = (PayoffPair) o;
if (p1Payoffs != null ? !p1Payoffs.equals(that.p1Payoffs) : that.p1Payoffs != null) return false;
if (p2Payoffs != null ? !p2Payoffs.equals(that.p2Payoffs) : that.p2Payoffs != null) return false;
return true;
}
@Override
public int hashCode() {
int result = p1Payoffs != null ? p1Payoffs.hashCode() : 0;
result = 31 * result + (p2Payoffs != null ? p2Payoffs.hashCode() : 0);
return result;
}
public boolean isEmpty() {
return p1Payoffs.size() == 0 || p2Payoffs.size() == 0;
}
}
|
package uebung1;
import java.time.LocalDate;
public interface IDate {
LocalDate getCurrentDate();
}
|
package cn.itcast.core.service;
import cn.itcast.core.pojo.entity.BuyerCart;
import cn.itcast.core.pojo.entity.BuyerCollect;
import cn.itcast.core.pojo.entity.Result;
import cn.itcast.core.pojo.item.Item;
import java.util.List;
public interface CollectService {
/**
* 将购买的商品加入到用户当前所拥有的收藏列表中
* @param collectList 用户现在拥有的收藏列表
* @param itemId 用户购买的商品库存id
* @return
*/
public List<Item> addItemToCollectList(List<Item> collectList, Long itemId);
/**
* 将收藏列表根据用户名存入redis
* @param collectList 存入的收藏列表
* @param userName 用户名
*/
public void setCollectListToRedis(List<Item> collectList, String userName);
/**
* 根据用户名到redis中获取收藏列表
* @param userName 用户名
* @return
*/
public List<Item> getCollectListFromRedis(String userName);
Item createitem(Long itemId);
}
|
package com.hkpj.jcw.utils;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
public final class DateUtil {
public static final String FORMATDATETIME = "yyyy-MM-dd HH:mm:ss";
public static final String FORMATDATE = "yyyy-MM-dd";
private DateUtil() {
}
public static Date getSQLDate(java.util.Date date) {
if (date == null)
return null;
else
return new Date(date.getTime());
}
public static Date getSQLToday() {
Calendar cal = Calendar.getInstance();
return new Date(cal.getTimeInMillis());
}
public static java.util.Date getToday() {
Calendar cal = Calendar.getInstance();
return cal.getTime();
}
public static Timestamp getTimestamp(java.util.Date date) {
if (date == null)
return null;
else
return new Timestamp(date.getTime());
}
public static java.util.Date toDate(String sDD, String sMM, String sYYYY, String sHHmm, int iFromTZOffset, int iToTZOffset) {
GregorianCalendar gc = new GregorianCalendar();
int iDD;
int iMM;
int iYYYY;
try {
gc.setTime((new SimpleDateFormat("ddMMyyyyHHmm", Locale.US)).parse((new StringBuilder()).append(sDD).append(sMM).append(sYYYY).append(sHHmm).toString()));
} catch (ParseException e1) {
e1.printStackTrace();
}
iDD = Integer.parseInt(sDD);
iMM = Integer.parseInt(sMM);
iYYYY = Integer.parseInt(sYYYY);
if (iDD != gc.get(5) || iMM != gc.get(2) + 1 || iYYYY != gc.get(1))
return null;
try {
gc.add(10, -iFromTZOffset + iToTZOffset);
} catch (Exception e) {
return null;
}
return gc.getTime();
}
public static java.util.Date toDate(String sDD, String sMMM, String sYYYY) {
return toDate(sDD, sMMM, sYYYY, "0000");
}
public static java.util.Date toDate(String sDD, String sMMM, String sYYYY, String sHHmm) {
return toDate(sDD, sMMM, sYYYY, sHHmm, 0, 0);
}
public static int getDateDiff(Calendar d1, Calendar d2) {
if (d1.after(d2)) {
Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(6) - d1.get(6);
int y2 = d2.get(1);
if (d1.get(1) != y2) {
d1 = (Calendar) d1.clone();
do {
days += d1.getActualMaximum(6);
d1.add(1, 1);
} while (d1.get(1) != y2);
}
return days;
}
public static int getDateDiff(java.util.Date firstDate, java.util.Date secondDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(secondDate);
long differenceInMillis = firstDate.getTime() - secondDate.getTime();
double differenceInDays = (double) differenceInMillis / 86400000D;
int intDay = (int) Math.round(differenceInDays);
return intDay;
}
public int getDateDiff(String startDate, String endDate) {
DateFormat df = DateFormat.getDateInstance(3, Locale.US);
java.util.Date sDate = new java.util.Date();
java.util.Date eDate = new java.util.Date();
try {
sDate = df.parse(startDate);
eDate = df.parse(endDate);
} catch (Exception e) {
e.printStackTrace();
}
Integer diff = new Integer((int) ((eDate.getTime() - sDate.getTime()) / 0x5265c00L) + 1);
return diff.intValue();
}
public static java.util.Date addDate(java.util.Date d, int dayOffset) {
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(d);
gc.add(5, dayOffset);
return gc.getTime();
}
public static java.util.Date addDate(String strDate, String strfmt, int numDay) {
java.util.Date bdate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat(strfmt);
java.util.Date sd = formatter.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(sd);
cal.add(5, numDay);
bdate = cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return bdate;
}
public static java.util.Date parseDate(String strdate, String format) {
java.util.Date bdate = null;
if (null == strdate)
return bdate;
try {
SimpleDateFormat dFormat = new SimpleDateFormat(format);
dFormat.setLenient(false);
bdate = new java.util.Date(dFormat.parse(strdate).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return bdate;
}
public static String formatDate(java.util.Date date, String format) {
if (date == null || format == null) {
return "";
} else {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
}
public static String formatDate(Date date, String format) {
if (date == null || format == null) {
return "";
} else {
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(date);
}
}
public static java.util.Date toDate(String date) {
if (date == null || date.equals(""))
return null;
DateFormat df = SimpleDateFormat.getDateInstance(3, Locale.CHINA);
java.util.Date d = null;
try {
d = df.parse(date.trim());
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
public static Calendar getCalendar(java.util.Date date) {
if (date == null) {
return null;
} else {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}
}
public static java.util.Date getDate(Calendar c) {
if (c == null)
return null;
else
return c.getTime();
}
/** 获取当前月末日期 */
public static int getLastDay(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
int endday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
//System.out.println(calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1 + "月:" + endday));
return endday;
}
public static void main(String[] args) {
getLastDay(2013, 2);
}
}
|
package scater.Service;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import scater.DAO.ProductDAO;
import scater.POJO.Product;
import scater.common.Constant;
import csAsc.EIO.MsgEngine.CEIOMsgRouter.CParam;
public class ProductService {
private CParam param;
private ProductDAO dao;
private JSONObject result;
public ProductService(CParam param){
this.param=param;
dao=new ProductDAO(param);
result=new JSONObject();
}
public JSONObject queryAllProduct(JSONObject data) throws SQLException, JSONException{
int page=data.getInt("page");
int pageSize=data.getInt("pageSize");
ResultSet set=dao.queryAllProduct(page, pageSize);
JSONArray array=Constant.getJsonArrayFromSet(set, Product.market_int_col, Product.market_string_col, null, null);
result.put("page", page);
result.put("pageSize",pageSize);
result.put("array", array);
return result;
}
public JSONObject queryProById(JSONObject data) throws JSONException, SQLException{
String productId=data.getString("productId");
ResultSet set=dao.queryProById(productId);
if(set!=null){
set.next();
JSONObject product=Constant.setValue(set, Product.product_int, Product.product_string, null, null);
result.put("product", product);
}
set=dao.queryPriceById(productId);
JSONArray array=Constant.getJsonArrayFromSet(set, Product.price_int, null, Product.price_float, null);
result.put("price", array);
return result;
}
public JSONObject querySelfPro(JSONObject data) throws JSONException, SQLException{
int page=data.getInt("page");
int pageSize=data.getInt("pageSize");
String companyId=data.getString("companyId");
ResultSet set=dao.querySelfPro(page, pageSize, companyId);
JSONArray array=Constant.getJsonArrayFromSet(set, Product.market_int_col, Product.market_string_col, null, null);
result.put("page", page);
result.put("companyId", companyId);
result.put("pageSize",pageSize);
result.put("array", array);
return result;
}
}
|
package com.example.codeclan.whisky_galore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WhiskyGaloreApplication {
public static void main(String[] args) {
SpringApplication.run(WhiskyGaloreApplication.class, args);
}
}
|
package br.com.mixfiscal.prodspedxnfe.gui.applet;
import java.awt.FlowLayout;
import javax.swing.JApplet;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
public class SelecionadorArquivo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JFileChooser fc = new JFileChooser();
FlowLayout flow = new FlowLayout();
flow.addLayoutComponent("fc", fc);
SelecionadorArquivo.this.setLayout(flow);
}
});
} catch(Exception ex) {
System.err.println("Erro ao carregar o applet: " + ex.getMessage());
}
}
}
|
package com.palak.devicemanager;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.palak.devicemanager.db.CommandEntity;
import com.palak.devicemanager.db.DeviceEntity;
import com.palak.devicemanager.db.MessageEntity;
import com.palak.devicemanager.db.ObjectBox;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import io.objectbox.Box;
public class CommandHistoryFragment extends Fragment
{
public static final String TAG = "CommandHistoryFragment";
public static final String ARG = "deviceId";
private static DeviceEntity device;
private static Box<MessageEntity> messageBox;
private static RecyclerView recyclerView;
private static MessageListAdapter rvAdapter;
private static ArrayList<MessageListItem> messageList;
public CommandHistoryFragment()
{
}
public static CommandHistoryFragment newInstance(long deviceId)
{
CommandHistoryFragment fragment = new CommandHistoryFragment();
Bundle args = new Bundle();
args.putLong(ARG, deviceId);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_command_history, container, false);
long id = getArguments().getLong(ARG);
device = MainActivity.deviceBox.get(id);
messageBox = ObjectBox.get().boxFor(MessageEntity.class);
recyclerView = view.findViewById(R.id.recyclerView_HistoryList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
setRecyclerView();
return view;
}
private void setRecyclerView()
{
messageList = new ArrayList<>();
for (MessageEntity message : messageBox.getAll())
{
if (message.device.getTargetId() == device.id)
messageList.add(new MessageListItem(message));
}
Collections.sort(messageList);
rvAdapter = new MessageListAdapter(messageList);
recyclerView.setAdapter(rvAdapter);
}
}
|
package com.esum.common.sftp;
import org.apache.log4j.PropertyConfigurator;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
/**
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class SFTPConnectionCmd {
private static String username;
private static String password;
public static void main(String[] args) throws Exception {
System.out.println("SFTP Connection Test ...\n");
if(args==null || args.length!=5)
throw new Exception("Usage : [host] [port] [username] [password] [compression]");
String installPath = System.getProperty("xtrus.home");
PropertyConfigurator.configure(installPath + "/conf/log.properties");
System.out.println("Connecting to " + args[0] + ":" + args[1]);
username = args[2];
password = args[3];
System.out.println("Username : " + username+", password : ********");
SFTPConnectionCmd command = new SFTPConnectionCmd();
command.connectionTest(args[0], Integer.parseInt(args[1]), Boolean.parseBoolean(args[4]));
System.out.println();
}
public void connectionTest(String host, int port, boolean useCompression) {
Session session = null;
try {
JSch jsch = new JSch();
jsch.setKnownHosts(System.getProperty("xtrus.home") + "/conf/sftp/ssh_known_hosts");
session = jsch.getSession(username, host, port);
session.setConfig("MaxAuthTries", "3");
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PreferredAuthentications", "password");
if (useCompression) {
session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
session.setConfig("zlib", com.jcraft.jsch.jcraft.Compression.class.getName());
session.setConfig("zlib@openssh.com", com.jcraft.jsch.jcraft.Compression.class.getName());
// 1 gives best speed, 9 gives best compression,
// 0 gives no compression at all (the input data is simply copied a block at a time).
// Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (currently equivalent to level 6)
session.setConfig("compression_level", "9");
}
session.setTimeout(5000);
// directly
UserInfo ui = new LocalUserInfo();
session.setUserInfo(ui);
if (!session.isConnected()) {
session.connect();
System.out.println("SSH Session connected.");
}
} catch (Exception e) {
System.out.println("SSH Connection Error! " + e.toString());
} finally {
session.disconnect();
}
}
private final class LocalUserInfo implements UserInfo, UIKeyboardInteractive {
public void showMessage(String message) {
System.out.println(message);
}
public boolean promptYesNo(String message) {
return true;
}
public boolean promptPassword(String message) {
return true;
}
public boolean promptPassphrase(String message) {
return true;
}
public String getPassword() {
return password;
}
public String getPassphrase() {
return "";
}
public String[] promptKeyboardInteractive(String destination,
String name, String instruction, String[] prompt, boolean[] echo) {
final String p = password;
return p != null ? new String[] { p } : null;
}
}
}
|
package org.vpontus.vuejs.web.rest.errors;
import org.zalando.problem.AbstractThrowableProblem;
import org.zalando.problem.Status;
public class TaskStatusNotFoundException extends AbstractThrowableProblem {
public TaskStatusNotFoundException() {
this("Task status not found.");
}
public TaskStatusNotFoundException(String message) {
super(ErrorConstants.STATUS_NOT_FOUND_TYPE, message, Status.NOT_FOUND);
}
}
|
package br.com.wasys.library.exception;
import br.com.wasys.library.http.Error;
/**
* Created by pascke on 05/09/16.
*/
public class EndpointException extends Exception {
public Error error;
public EndpointException(Error error) {
if (error == null) {
throw new IllegalArgumentException("error is null");
}
this.error = error;
}
@Override
public String getMessage() {
return error.getMessage();
}
}
|
package com.jgchk.haven.ui.detail;
public interface DetailNavigator {
void handleError(Throwable throwable);
void showReserveView(int numReservations);
void showReleaseView();
void onCapacityError();
void onReservationError();
}
|
package com.example.a77354.android_final_project;
import android.Manifest;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.example.a77354.android_final_project.PartnerAsking.PartnerAskingActivity;
import com.example.a77354.android_final_project.RunMusic.RunMusicActivity;
import com.example.a77354.android_final_project.RunPlan.RunPlanActivity;
import com.example.a77354.android_final_project.Trajectory.TrajectoryActivity;
import com.github.mzule.fantasyslide.SideBar;
import com.github.mzule.fantasyslide.SimpleFantasyListener;
import com.github.mzule.fantasyslide.Transformer;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private MapView mMapView = null;
private BaiduMap mBaiduMap;
private LocationClient mLocClient;
public MyLocationListenner myListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SDKInitializer.initialize(getApplicationContext());
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23){
verifylocation();
}else{
initView();//init为定位方法
}
initRunButton();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final DrawerArrowDrawable indicator = new DrawerArrowDrawable(this);
indicator.setColor(Color.WHITE);
getSupportActionBar().setHomeAsUpIndicator(indicator);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
drawerLayout.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (((ViewGroup) drawerView).getChildAt(1).getId() == R.id.leftSideBar) {
indicator.setProgress(slideOffset);
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
return true;
}
//点击跳转到其他页面
public void onClick(View view) {
if (view instanceof TextView) {
String title = ((TextView) view).getText().toString();
if (title.equals("跑步计划")) {
startActivity(new Intent(this, RunPlanActivity.class));
} else if (title.equals("跑步歌单")) {
startActivity(new Intent(this, RunMusicActivity.class));
} else if (title.equals("同校约跑")) {
startActivity(new Intent(this, PartnerAskingActivity.class));
} else if (title.equals("跑步轨迹")) {
startActivity(new Intent(this, TrajectoryActivity.class));
} else {
startActivity(UniversalActivity.newIntent(this, title));
}
} else if (view.getId() == R.id.userInfo) {
startActivity(new Intent(this, PersonalActivity.class));
}
}
public void initRunButton() {
Button run = (Button) findViewById(R.id.run);
run.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), TrajectoryActivity.class));
}
});
}
private void initView() {
mMapView = (MapView) findViewById(R.id.bmapView); //找到我们的地图控件
mBaiduMap = mMapView.getMap(); //获得地图
mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL); //设置为普通模式的地图
mBaiduMap.setMyLocationEnabled(true); // 开启定位图层
mLocClient = new LocationClient(getApplicationContext()); //定位用到的一个类
myListener = new MyLocationListenner();
mLocClient.registerLocationListener(myListener); //注册监听
///LocationClientOption类用来设置定位SDK的定位方式,
LocationClientOption option = new LocationClientOption(); //以下是给定位设置参数
option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
option.setOpenGps(true); // 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(1000);
option.setLocationNotify(true);
option.setIgnoreKillProcess(false);
option.SetIgnoreCacheException(false);
option.setWifiCacheTimeOut(5*60*1000);
option.setEnableSimulateGps(false);
mLocClient.setLocOption(option);
mLocClient.start();
}
@Override
protected void onStop() {
super.onStop();
//停止定位
mBaiduMap.setMyLocationEnabled(false);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
public class MyLocationListenner implements BDLocationListener {
private boolean isFirstIn = true;
@Override
public void onReceiveLocation(BDLocation location){
MyLocationData data= new MyLocationData.Builder()
.direction(location.getDirection())//设定图标方向
.accuracy(location.getRadius())//getRadius 获取定位精度,默认值0.0f
.latitude(location.getLatitude())//百度纬度坐标
.longitude(location.getLongitude())//百度经度坐标
.build();
//设置定位数据, 只有先允许定位图层后设置数据才会生效,参见 setMyLocationEnabled(boolean)
mBaiduMap.setMyLocationData(data);
if(isFirstIn) {
//地理坐标基本数据结构
LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
//描述地图状态将要发生的变化,通过当前经纬度来使地图显示到该位置
MapStatusUpdate msu= MapStatusUpdateFactory.newLatLng(latLng);
//改变地图状态
mBaiduMap.setMapStatus(msu);
isFirstIn=false;
}
}
}
// 确认已经获取定位的权限
public void verifylocation(){
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
initView();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Android6.0申请权限的回调方法
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 获取到权限,作相应处理(调用定位SDK应当确保相关权限均被授权,否则可能引起定位失败)
initView();
} else {
// 没有获取到权限,做特殊处理
Toast.makeText(getApplicationContext(), "获取位置权限失败,请手动开启", Toast.LENGTH_SHORT).show();
}
}
}
|
package Command;
/**
* Created by thomas on 2/23/15.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.StringTokenizer;
import ChronoTimers.ChronoTimer;
public class Command
{
private LocalDateTime timeStamp;
private String cmdName;
private ArrayList<String> args;
public Command(String timestamp, String cmdName, ArrayList<String> args) {
try{
String[] hoursminutes = timestamp.split(":");
String[] secondsmillis = hoursminutes[2].split("\\.");
timeStamp = LocalDateTime.of(LocalDateTime.now().getYear(),
LocalDateTime.now().getMonth(),
LocalDateTime.now().getDayOfMonth(),
Integer.parseInt(hoursminutes[0]),
Integer.parseInt(hoursminutes[1]),
Integer.parseInt(secondsmillis[0]),
Integer.parseInt(secondsmillis[1]));
}catch(Exception e){
}
this.cmdName = cmdName;
this.args = args;
}
public LocalDateTime getTimestamp(){
return timeStamp;
}
public static Command commandFromString(String str)
{
String timeStamp = null;
String cmdName = null;
ArrayList<String> args = new ArrayList<String>();
StringTokenizer multiTokenizer = new StringTokenizer(str);
int index = 0;
while (multiTokenizer.hasMoreTokens())
{
//System.out.println(multiTokenizer.nextToken());
// USE TOKENS APPROPRIATELY
switch (index)
{
case 0:
cmdName = multiTokenizer.nextToken();
break;
// CMD ARG
default:
args.add(multiTokenizer.nextToken());
break;
}
++ index;
}
return new Command(timeStamp, cmdName, args);
}
public static ArrayList<Command> parseCommandFile(File fin) throws IOException
{
ArrayList<Command> commandList = new ArrayList<Command>();
FileInputStream fis = new FileInputStream(fin);
//Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null)
{
String timeStamp = null;
String cmdName = null;
ArrayList<String> args = new ArrayList<String>();
StringTokenizer multiTokenizer = new StringTokenizer(line);
int index = 0;
while (multiTokenizer.hasMoreTokens())
{
//System.out.println(multiTokenizer.nextToken());
// USE TOKENS APPROPRIATELY
switch (index)
{
// TIMESTAMP
case 0:
timeStamp = multiTokenizer.nextToken();
break;
// CMD NAME
case 1:
cmdName = multiTokenizer.nextToken();
break;
// CMD ARG
default:
args.add(multiTokenizer.nextToken());
break;
}
++ index;
}
commandList.add(new Command(timeStamp, cmdName, args));
}
br.close();
return commandList;
}
public void execute(ChronoTimer timer) throws Exception
{
if (this.cmdName.equals("ON"))
{
timer.turnOn();
}
else if (this.cmdName.equals("OFF"))
{
timer.turnOff();
}
else if (this.cmdName.equals("NUM"))
{
timer.num(Integer.parseInt(this.args.get(0)));
}
else if (this.cmdName.equals("CONN"))
{
timer.connect(this.args.get(0), Integer.parseInt(this.args.get(1)));
}
else if (this.cmdName.equals("TOGGLE"))
{
timer.toggle(Integer.parseInt(this.args.get(0)));
}
else if (this.cmdName.equals("START"))
{
timer.start();
}
else if (this.cmdName.equals("FIN"))
{
timer.end();
}
else if (this.cmdName.equals("EXIT"))
{
System.exit(0);
}
else if(this.cmdName.equals("DNF")){
timer.DNF();
}
else if(this.cmdName.equals("PRINT")){
timer.print();
}
else if(this.cmdName.equals("TIME")){
String[] split = args.get(0).split(":");
LocalDateTime set = LocalDateTime.of(LocalDateTime.now().getYear(),
LocalDateTime.now().getMonth(),
LocalDateTime.now().getDayOfMonth(),
Integer.parseInt(split[0]),
Integer.parseInt(split[1]),
Integer.parseInt(split[2]));
timer.time(set);
}
else if(this.cmdName.equals("EVENT")){
timer.event(args.get(0));
}
else if(this.cmdName.equals("EXPORT")){
timer.export(Integer.parseInt(args.get(0)));
}
else if(this.cmdName.equals("TRIG")){
timer.trigger(Integer.parseInt(args.get(0)));
}
else if(this.cmdName.equals("NEWRUN")){
timer.newRun();
}
else if(this.cmdName.equals("ENDRUN")){
timer.endRun();
}
else if(this.cmdName.equals("")){}
else{
System.out.println(" dpofjpwf : " + this.cmdName);
throw new Exception("Invalid command name");
}
}
}
|
/**
*
*/
package com.android.aid;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.android.aid.ApkFileHelper.ApkInfos;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
/**
* @author wangpeifeng
*
*/
public abstract class ThreadDownload extends Thread{
/*
* CONSTANTS, PROTECTED
*/
protected static final int MAX_THREADS = 3;
protected static final int MIN_THREADS = 1;
protected static final int MAX_DUMMY_TIMER = 30000;
protected static final int BUFFER_SIZE = 8192;
protected static final long SLEEP_TIMER = 100;
protected static final String SLASH = "/";
protected static final String APP_DIR = "/ApkStore";
protected static final String DOWNLOAD_SUFFIX = ".download";
/*
* PROPERTIES,PROTECTED
*/
protected Context context;
protected boolean running;
protected long stamp;
protected boolean pause;
protected boolean finished;
protected boolean downloadFlag;
protected String filename;
protected String savename;
protected String download_root;
protected String download_path;
protected String save_path;
protected int download_count;
protected long size;
protected int serial;
protected DBSchemaDownload schema;
protected DBSchemaDownload.Columns column;
/*
* CONSTRUCTOR
*/
public ThreadDownload(Context context){
super();
this.context = context;
}
public ThreadDownload(Context context, DBSchemaDownload schema, String download_root,
String download_path, String save_path, DBSchemaDownload.Columns columns) {
super();
this.context = context;
this.schema = schema;
this.running = false;
this.pause = false;
this.finished = false;
this.downloadFlag = false;
this.filename = columns.getFileFrom();
this.savename = columns.getFileTo();
this.download_root = download_root;
this.download_path = download_path;
this.save_path = save_path;
this.download_count = columns.getCount();
this.size = columns.getSize();
this.serial = columns.getSerial();
this.column = columns;
checkSaveDir();
getThreadList();
getThreadMap();
}
/*
* METHODS, PROTECTED
*/
protected boolean isRunning(){
return this.running;
}
protected boolean isPause(){
return this.pause;
}
protected void pauseThread(){
this.pause = true;
}
protected void resumeThread(){
this.pause = false;
}
protected void stopThread(){
this.running = false;
this.pause = false;
//Log.i(this.getClass().getName(),"stop thread:"+this.filename);
}
protected String getFilename(){
return this.filename;
}
protected void setFileName(String filename){
this.filename = filename;
}
protected boolean isDownloading(String filename){
boolean bool = getThreadMap().containsKey(filename);
//Log.i(this.getClass().getName(), "isDownloading:"+filename+"="+bool);
return bool;
}
protected void addDownloadThread(ThreadDownload thread){
getThreadList().add(thread);
getThreadMap().put(thread.getFilename(), thread);
//Log.i(this.getClass().getName(), "add thread " + this.filename +" to:"+getThreadList().size());
}
protected void removeDownloadThread(Thread thread,String filename){
//ThreadDownload thread = getThreadMap().get(filename);
getThreadList().remove(thread);
getThreadMap().remove(filename);
//Log.i(this.getClass().getName(), "remove thread" + this.filename + " to:"+getThreadList().size());
}
protected void stopDownloadThread(String filename){
//ThreadDownload thread = getThreadMap().get(filename);
//Log.i(this.getClass().getName(), "stop download thread:"+filename);
ThreadDownload thread = getThread(filename);
if(thread!=null){
thread.stopThread();
}
}
public ThreadDownload getThread(int index){
if(getThreadList().size()>index){
return getThreadList().get(index);
}
else{
return null;
}
}
public ThreadDownload getThread(String filename){
ThreadDownload thread = null;
ArrayList<ThreadDownload> list = getThreadList();
int i =0;
if(list!=null){
int size = getThreadList().size();
for(i=0; i< size; i++){
if(filename.equals(list.get(i).filename)){
thread = list.get(i);
//Log.i(this.getClass().getName(), "getThread:"+i);
break;
}
}
}
return thread;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
downloadFlag = false;
FileOutputStream fos = null;
InputStream is = null;
try{
super.run();
running = true;
stamp = System.currentTimeMillis();
long downloadLenght = 0;
long savedLenght =0;
long fileLenght = 0;
long downloadLoops = 0;
HttpURLConnection httpConnection = null;
if(StoragePreferences.isStorageAvailable()){
try{
//Log.i(this.getClass().getName(), "run:"+this.filename);
URL url = new URL(getDownloadRoot()+java.net.URLEncoder.encode(filename, "UTF-8"));
httpConnection = (HttpURLConnection) url.openConnection();
fileLenght = httpConnection.getContentLength();
httpConnection.disconnect();
if(this.size != fileLenght){
this.schema.updateDownloadFileSize(filename, fileLenght);
}
File downloadFile = new File(getSaveFile()
+ StoragePreferences.getDownloadSuffix());
if(downloadFile.exists()){
savedLenght = (new RandomAccessFile(downloadFile,"rw")).length();
}
if(savedLenght == fileLenght && fileLenght >0 ){
this.finished = true;
downloadFlag = true;
}
else{
httpConnection = (HttpURLConnection) url.openConnection();
//httpConnection.setAllowUserInteraction(true);
Log.i(this.getClass().getName(),"Range => bytes=" + savedLenght + "-" + fileLenght);
httpConnection.setConnectTimeout(12*1000);
httpConnection.setRequestProperty("accept", "*/*");
httpConnection.setRequestProperty("Range", "bytes=" + savedLenght + "-" + fileLenght);
httpConnection.connect();
Log.i(this.getClass().getName(), "resp code:"+httpConnection.getResponseCode());
is = httpConnection.getInputStream();
if(fileLenght>1 && savedLenght > 0 && savedLenght < fileLenght )
{
// httpConnection = (HttpURLConnection) url.openConnection();
// httpConnection.setAllowUserInteraction(true);
// httpConnection.setRequestProperty("Range", "bytes=" + savedLenght + "-" + fileLenght);
fos = new FileOutputStream(downloadFile,true);
}
else{
savedLenght = 0;
fos = new FileOutputStream(downloadFile,false);
}
int readLenght = 0;
//byte[] buffer = null;
byte[] buffer = new byte[BUFFER_SIZE];
//Log.i(this.getClass().getName(), filename+" start saveLenght/fileLenght="+savedLenght+"/"+fileLenght);
//downloadLoops = (fileLenght - savedLenght)/BUFFER_SIZE + 1;
while(running && savedLenght<fileLenght && downloadLoops >= 0){
//running = false;
stamp = System.currentTimeMillis();
/*
if(fileLenght-savedLenght > BUFFER_SIZE){
buffer = new byte[BUFFER_SIZE];
}
else{
buffer = new byte[(int) (fileLenght-savedLenght)];
}
*/
//downloadLoops--;
/*
if(readLenght > 0){
Thread.sleep(SLEEP_TIMER);
Log.i(this.getClass().getName(), this.filename +" sleep:"+downloadLoops);
}
*/
try{
readLenght=is.read(buffer);
Log.i(this.getClass().getName(), "serial:"+ column.getSerial() +","+ filename +":" + savedLenght +"/" + fileLenght+"@"+readLenght+"/"+buffer.length);
if(readLenght>0){
fos.write(buffer, 0, readLenght);
downloadFlag=true;
downloadLenght += readLenght;
savedLenght += readLenght;
}
}
catch(Exception writeE){
writeE.printStackTrace();
readLenght = 0;
running = false;
downloadFlag = false;
}
if(isApkDownloading()){
if(!(new ConfigPreferences(context).isDownloadConnection())){
running = false;
}
}
else{
if(!new DataConnectionHelper(context).isDataOnline()){
running = false;
}
}
Thread.sleep(SLEEP_TIMER);
}
if(savedLenght >= fileLenght && fileLenght > 0){
this.finished = true;
downloadFlag = true;
//Log.i(this.getClass().getName(), "download finished:"+filename);
}
}
}
catch(Exception e){
e.printStackTrace();
Log.i(this.getClass().getName(), "download exception:"+e.getCause()+","+e.getMessage());
}
finally{
try{
if(fos!=null){
fos.close();
}
if(is!=null){
is.close();
}
httpConnection.disconnect();
}
catch(Exception eIO){
eIO.printStackTrace();
}
}
}
}
catch(Exception eThread){
eThread.printStackTrace();
}
finally{
if(!downloadFlag){
schema.updateDownloadFile(this.filename, this.download_count+1);
}
exitDownload();
}
}
protected void checkSaveDir(){
File file = new File(getAppDir());
if(!file.exists()){
file.mkdirs();
}
file = new File(getSaveRoot());
if(!file.exists()){
file.mkdir();
}
}
protected void exitDownload(){
try{
saveDownloaded();
removeDownloadThread(this,this.filename);
onDownloadFinished();
}
catch(Exception e){
e.printStackTrace();
}
}
private void saveDownloaded(){
try{
if(this.finished){
File file = new File(getSaveFile() + StoragePreferences.getDownloadSuffix());
file.renameTo(new File(getSaveFile()));
schema.deleteDownloaded(this.filename);
}
else{
if(this.download_count == DBSchemaDownload.VAL_DOWNLOAD_COUNT_MAX){
//Log.i("ThreadDownload", "delete: " + this.filename);
schema.deleteDownloaded(this.filename);
if(this.filename.substring(this.filename.lastIndexOf('.')).toLowerCase().equals(".apk")){
new DBSchemaReportDownload(context).addActionRecord(column.getPackage(),
column.getVerCode(), DBSchemaReport.VAL_ACTION_DOWNLOAD_DROP);
}
}
else{
schema.updateDownloadFile(this.filename, this.download_count+1);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
protected String getAppDir(){
return StoragePreferences.getAppDir();
}
protected String getSaveFile(){
return getSaveRoot() + this.savename;
}
protected String getDownloadRoot() {
// TODO Auto-generated method stub
return this.download_root+this.download_path+SLASH;
}
public String getSaveRoot() {
// TODO Auto-generated method stub
return this.save_path;
}
protected boolean isThreadListAvailable()
{
// TODO Auto-generated method stub
boolean bool = false;
if(new PackageHelper(context).isRunningMe()){
if(getThreadList().size() < MAX_THREADS){
bool = true;
//Log.i(this.getClass().getName(), "threads available = "+(MAX_THREADS-getThreadList().size()));
}
}
else{
if(getThreadList().size() < MIN_THREADS){
bool = true;
//Log.i(this.getClass().getName(), "threads available = "+(MAX_THREADS-getThreadList().size()));
}
}
if(!bool){
ArrayList<ThreadDownload> list = getThreadList();
//Iterator<ThreadDownload> iterator = list.iterator();
//while(iterator.hasNext()){
//Log.i(this.getClass().getName(),iterator.next().getFilename());
//}
String firstfile = list.get(0).getFilename();
list.get(0).stopDownloadThread(firstfile);
//Log.i(this.getClass().getName(), "firstfile:"+firstfile+"@"+list.get(0).stamp+"/"+System.currentTimeMillis());
long timer = System.currentTimeMillis() - list.get(0).stamp - MAX_DUMMY_TIMER;
Log.i(this.getClass().getName(), "timer:"+(int)(timer));
if(((int)(timer)) > 0){
//Log.i(this.getClass().getName(), "remove:"+firstfile);
removeDownloadThread(list.get(0),list.get(0).getFilename());
//getThreadList().remove(0);
//getThreadMap().remove(firstfile);
}
}
return bool;
}
protected boolean isApkDownloading(){
boolean bool = false;
if(this.column.getFileFrom().toLowerCase().endsWith(".apk")){
bool = true;
}
return bool;
}
protected boolean startDownloadThread(){
boolean bool = false;
//Log.i(this.getClass().getName(), "start thread:"+this.filename);
if(this.isThreadListAvailable()){
bool = true;
if(!this.isDownloading(this.getFilename())){
this.addDownloadThread(this);
this.start();
}
}
return bool;
}
/*
* METHODS, ABSTRACT
*/
protected abstract ArrayList<ThreadDownload> getThreadList();
protected abstract HashMap<String, ThreadDownload> getThreadMap();
/**
* onDownloadFinished()
* called while running exit
*/
protected abstract void onDownloadFinished();
}
|
package com.example.choonhee.hack2hired_21.activity.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.choonhee.hack2hired_21.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style._AppThemeActionBar);
setContentView(R.layout.activity_main);
Button searchButton = (Button) findViewById(R.id.search_button);
final EditText editText = (EditText) findViewById(R.id.search_title_edit_text);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!editText.getText().equals("")) {
Intent intent = new Intent(getBaseContext(), BookSearchActivity.class);
intent.putExtra("bookTitle", editText.getText().toString());
startActivity(intent);
}
}
});
}
}
|
package pl.coderslab.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import pl.coderslab.model.Book;
import pl.coderslab.service.BookService;
import pl.coderslab.service.TransferService;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@Controller
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService memoryBookService;
@RequestMapping("/hello")
public String hello(){
return "{hello: World}";
}
@RequestMapping("/helloBook")
public Book helloBook(){
return new Book(1L,"9788324631766","Thinking in Java",
"Bruce Eckel","Helion","programming");
}
@RequestMapping("/books")
@ResponseBody
public List<Book> displayAllBooks() {
return memoryBookService.getList();
}
@RequestMapping("/books/{id}")
@ResponseBody
public Book getBook(@PathVariable long id) {
return memoryBookService.getBookById(id);
}
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/books", method = RequestMethod.POST)
@ResponseBody
public String addBook(@RequestBody Book book) {
memoryBookService.updateBookById(book);
return "Book was added";
}
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/books/{id}", method = RequestMethod.PUT)
@ResponseBody
public String updateBook(@RequestBody Book book, @PathVariable long id) {
memoryBookService.updateBookById(book);
return "Book was modified";
}
@RequestMapping(value = "/books/{id}", method = RequestMethod.DELETE)
@ResponseBody
public String deleteBook(HttpServletRequest request, @PathVariable long id) {
memoryBookService.deleteBookById(id);
return "Book was deleted.";
}
}
|
package com.gyg.d_sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase database;
private ListView mlv;
private SimpleCursorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB_Helper db_helper = new DB_Helper(this);
database = db_helper.getWritableDatabase();
//SimpleCursorAdapter 适配器,null指代的地方是cursor对象
mlv = findViewById(R.id.lv);
adapter = new SimpleCursorAdapter(this,R.layout.layout,null,
new String[] {"_id","name","nickname"},new int[] {R.id.tv_id,R.id.tv_name,R.id.tv_nickname},
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
mlv.setAdapter(adapter);
}
public void insert(View view){
// String sql = "insert into student(_id,name,nickname) values(2017,'傲娇刚','小老虎')";
// database.execSQL(sql);
//该类中有返回的方法,可以知道到底有没有插入表,底层是MAP
for (int i=0;i<50;i++){
ContentValues con = new ContentValues();
con.put("_id",i);
con.put("name","傲娇刚");
con.put("nickname","小可爱"+i);
//返回最近插入的一行的行号
long insert = database.insert("student",null,con);
// insert > 0表示插入成功
// if (insert>0){
// Toast.makeText(this,"添加成功",Toast.LENGTH_SHORT).show();
// }
}
}
public void query(View view){
//当使用SimpleCursorAdapter时候 cursor必须包裹_id这个字段,可以不使用里面的数据
//cursor 游标
Cursor cursor = database.query("student",null,"name=?",
new String[] {"傲娇刚"},null,null,null);
//将一个新的cursor交换旧的cursor
adapter.swapCursor(cursor);
//刷新list View的数据
adapter.notifyDataSetChanged();
// while (cursor.moveToNext()){
// int id = cursor.getInt(cursor.getColumnIndex("_id"));
// String name = cursor.getString(cursor.getColumnIndex("name"));
// String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
//
// Toast.makeText(this,id+"\t"+name+"\t"+nickname, Toast.LENGTH_SHORT).show();
// }
}
//修改表
public void update(View view) {
ContentValues values = new ContentValues();
values.put("name","小鱼儿");
//受着一条语句影响的行数,如果有li
long result = database.update("student",values,"nickname=?",new String[] {"小可爱"});
if (result>0){
Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
}
}
//删除表
public void delete(View view) {
int result = database.delete("student","name=?",new String[] {"傲娇刚"});
if (result>0){
Toast.makeText(this,"删除成功",Toast.LENGTH_SHORT).show();
}
}
}
|
package com.example.projetpfebam;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProjetpfebamApplication {
public static void main(String[] args) {
SpringApplication.run(ProjetpfebamApplication.class, args);
}
}
|
package cn.hassan.spi;
/**
* Created with idea
* Author: hss
* Date: 2019/7/17 8:48
* Description:
*/
public class GoodPrinter implements Printer {
@Override
public void print() {
System.out.println("this is good printer");
}
}
|
package com.example.service;
import com.example.entity.Product;
import com.example.entity.User;
import java.util.List;
public interface UserService {
boolean subscribe(User user, Product product);
List<User> subscribedUsers(Product product);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tomitribe.lieutenant.cli;
import org.tomitribe.crest.api.Command;
import org.tomitribe.crest.api.Default;
import org.tomitribe.crest.api.Option;
import org.tomitribe.lieutenant.Config;
import org.tomitribe.lieutenant.Lieutenant;
import org.tomitribe.lieutenant.LieutenantConfig;
import org.tomitribe.lieutenant.docker.Docker;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class LieutenantCommand {
@Command
public void purge(@Option("withBranch") @Default("true") boolean withBranch,
@Option("withTags") @Default("true") boolean withTags,
@Option("dockerproperties") File dockerProperties) throws IOException {
final File currentDir = new File(".");
final File lieutenantFile = new File(currentDir, "lieutenant.yml");
Docker.DockerConfig dockerConfig = loadDockerProperties(dockerProperties);
Lieutenant lieutenant = new Lieutenant(currentDir);
if (lieutenantFile.exists()) {
Config config = Config.readFile(lieutenantFile);
LieutenantConfig lieutenantConfig = getLieutenantConfig(null, null, withBranch, withTags,
null);
config.setDockerConfig(dockerConfig);
config.setLieutenantConfig(lieutenantConfig);
lieutenant.purge(config);
} else {
LieutenantConfig lieutenantConfig = getLieutenantConfig(null, null, withBranch, withTags,
null);
lieutenant.purge(lieutenantConfig, dockerConfig);
}
}
@Command
public void push(@Option("force") @Default("false") boolean force,
@Option("prefix") String prefix, @Option("suffix") String suffix,
@Option("withBranch") @Default("true") boolean withBranch,
@Option("withTags") @Default("true") boolean withTags,
@Option("exclusionImages") String exclusionImages,
@Option("dockerproperties") File dockerProperties) throws IOException {
final File currentDir = new File(".");
final File lieutenantFile = new File(currentDir, "lieutenant.yml");
Docker.DockerConfig dockerConfig = loadDockerProperties(dockerProperties);
Lieutenant lieutenant = new Lieutenant(currentDir);
if (lieutenantFile.exists()) {
Config config = Config.readFile(lieutenantFile);
LieutenantConfig lieutenantConfig = getLieutenantConfig(prefix, suffix, withBranch, withTags,
exclusionImages);
config.setDockerConfig(dockerConfig);
config.setLieutenantConfig(lieutenantConfig);
lieutenant.push(config);
} else {
LieutenantConfig lieutenantConfig = getLieutenantConfig(prefix, suffix, withBranch, withTags,
exclusionImages);
lieutenant.push(lieutenantConfig, dockerConfig);
}
}
@Command
public void build(@Option("force") @Default("false") boolean force,
@Option("prefix") String prefix, @Option("suffix") String suffix,
@Option("withBranch") @Default("true") boolean withBranch,
@Option("withTags") @Default("true") boolean withTags,
@Option("dockerproperties") File dockerProperties) throws IOException {
final File currentDir = new File(".");
final File lieutenantFile = new File(currentDir, "lieutenant.yml");
Docker.DockerConfig dockerConfig = loadDockerProperties(dockerProperties);
Lieutenant lieutenant = new Lieutenant(currentDir);
if (lieutenantFile.exists()) {
Config config = Config.readFile(lieutenantFile);
LieutenantConfig lieutenantConfig = getLieutenantConfig(prefix, suffix, withBranch, withTags,
null);
config.setDockerConfig(dockerConfig);
config.setLieutenantConfig(lieutenantConfig);
lieutenant.build(config);
} else {
LieutenantConfig lieutenantConfig = getLieutenantConfig(prefix, suffix, withBranch, withTags,
null);
lieutenant.build(lieutenantConfig, dockerConfig);
}
}
private LieutenantConfig getLieutenantConfig(String prefix, String suffix,
boolean withBranch, boolean withTags, String exclusionImages) {
LieutenantConfig lieutenantConfig = new LieutenantConfig();
lieutenantConfig.setExclusionImagesPattern(exclusionImages);
lieutenantConfig.setWithBranches(withBranch);
lieutenantConfig.setWithTags(withTags);
lieutenantConfig.setSuffix(suffix);
lieutenantConfig.setPrefix(prefix);
return lieutenantConfig;
}
private Docker.DockerConfig loadDockerProperties(File dockerProperties) throws IOException {
Docker.DockerConfig dockerConfig = new Docker.DockerConfig();
if (dockerProperties != null) {
if (!dockerProperties.isFile()) {
throw new IllegalStateException("Not a file: " + dockerProperties.getAbsolutePath());
}
if (!dockerProperties.exists()) {
throw new IllegalStateException("File does not exist: " + dockerProperties.getAbsolutePath());
}
if (!dockerProperties.canRead()) {
throw new IllegalStateException("Not readable: " + dockerProperties.getAbsolutePath());
}
final Properties p = new Properties();
p.load(new FileInputStream(dockerProperties));
dockerConfig.withProperties(p);
}
return dockerConfig;
}
}
|
package com.fanfte.singleton;
public class DCLSingleton {
private static volatile DCLSingleton singleton;
public static DCLSingleton getInstance() {
if(singleton == null) {
synchronized (Singleton.class) {
if(singleton == null) {
singleton = new DCLSingleton();
}
}
}
return singleton;
}
}
|
package com.itcia.itgoo.dto;
import java.util.List;
import org.apache.ibatis.type.Alias;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@NoArgsConstructor
@AllArgsConstructor
@Alias("smallmeeting")
@Data
@Accessors(chain=true)
public class SmallMeeting {
private int smallnumber;
private String id;
private String smalllocation;
private int maximumdog;
private String meetingname;
private int meetparticipatecnt;
private String time;
private int smalldogcnt;
private String meetingdate;
private int status;
}
|
package service;
import com.dubbo.entity.User;
import com.dubbo.service.UserService;
public class UserServiceImpl implements UserService {
public User queryById(String id) {
User u=new User().setId(id);
return u;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package servlet;
import session.CartObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
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;
import javax.swing.RowFilter;
import order.OrderDAO;
import order.OrderDTO;
/**
*
* @author nguyenhongphat0
*/
@WebServlet(name = "CheckoutServlet", urlPatterns = {"/CheckoutServlet"})
public class CheckoutServlet extends HttpServlet {
private final String successPage = "shoppingOnline.html";
private final String errorPage = "viewcart.jsp";
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String url = errorPage;
try {
HttpSession session = request.getSession();
CartObject cart = (CartObject) session.getAttribute("CART");
OrderDAO dao = new OrderDAO();
OrderDTO dto = new OrderDTO(cart);
boolean res = dao.saveOrderToDB(dto);
if (res) {
url = successPage;
session.removeAttribute("CART");
}
} catch (SQLException ex) {
log("CheckoutServlet _ SQLException: " + ex.getMessage());
} catch (NamingException ex) {
log("CheckoutServlet _ NamingException: " + ex.getMessage());
} finally {
response.sendRedirect(url);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
package trungph.com;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import trungph.com.R;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class Class extends Activity {
EditText txtNameClass;
ListView listView;
ArrayAdapter<ObjClass> adapter;
List<ObjClass> classList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.class_layout);
txtNameClass = (EditText)findViewById(R.id.editNameClass);
listView = (ListView)findViewById(R.id.listClass);
DisplayListView();
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
final Dialog dia = new Dialog(Class.this);
dia.setTitle("Bạn có muốn xóa lớp không");
dia.setContentView(R.layout.delete);
dia.show();
final Button btnYes =(Button)dia.findViewById(R.id.btnYes);
final Button btnNo =(Button)dia.findViewById(R.id.btnNo);
btnYes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ObjClass objClass = adapter.getItem(position);
try {
deleteLop("https://trungpham-api.herokuapp.com/lops", Integer.valueOf(objClass.Class_id));
DisplayListView();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "errors: " + e.toString(), Toast.LENGTH_LONG).show();
} finally {
dia.dismiss();
}
}
});
btnNo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dia.dismiss();
}
});
return true;
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), Student.class);
ObjClass obj = adapter.getItem(position);
intent.putExtra("classID", obj.Class_id);
startActivity(intent);
}
});
//.........................THÊM DỮ LIỆU VÀO CSDL........................//
Button button =(Button)findViewById(R.id.btnAddClass);
button.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View a) {
final Dialog dia = new Dialog(Class.this);
dia.setContentView(R.layout.addclass_layout);
dia.setTitle("Thêm lớp");
dia.show();
final EditText txtNameClass = (EditText)dia.findViewById(R.id.editNameClass);
final Spinner intNienKhoa =(Spinner)dia.findViewById(R.id.spinner1);
Button addClass = (Button)dia.findViewById(R.id.btnClassDia);
addClass.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
try {
ObjClass c = new ObjClass();
c.Class_name = txtNameClass.getText().toString();
c.School_Year = intNienKhoa.getSelectedItem().toString();
postLop("https://trungpham-api.herokuapp.com/lops.json", String.valueOf(c.Class_name), String.valueOf(c.School_Year));
DisplayListView();
dia.dismiss();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "errors: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
});
Button clearClass = (Button)dia.findViewById(R.id.btnClearClass);
clearClass.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
txtNameClass.setText("");
intNienKhoa.setSelection(0);
}
});
}
});
}
private void DisplayListView() {
classList = new ArrayList<ObjClass>();
try {
JSONArray jArr = new JSONArray(String.valueOf(readLop("https://trungpham-api.herokuapp.com/lops.json")));
for(int i = 0; i < jArr.length(); i++){
ObjClass classObj = new ObjClass(String.valueOf(jArr.getJSONObject(i).getInt("id")), String.valueOf(jArr.getJSONObject(i).getString("ten")), String.valueOf(jArr.getJSONObject(i).getString("nien_khoa")));
classList.add(classObj);
}
adapter = new ArrayAdapter<ObjClass>(getApplicationContext(), android.R.layout.simple_list_item_1, classList);
listView.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "errors: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
// READ DANH SACH LOP //
public static String readLop(String urlString) throws IOException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
try {
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.connect();
InputStream in = null;
switch (connection.getResponseCode()) {
case 200:
in = new BufferedInputStream(connection.getInputStream());
break;
case 401:
in = null;
sb.append("Unauthorized");
break;
default:
in = null;
sb.append("Unknown response code");
break;
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return sb.toString();
}
// THEM LOP //
private String postLop(String urlString, String ten, String nien_khoa) throws IOException, JSONException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection connection = null;
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
JSONObject lop = new JSONObject();
lop.put("ten", ten);
lop.put("nien_khoa", nien_khoa);
JSONObject data = new JSONObject();
data.put("lop", lop);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.toString().getBytes());
outputStream.close();
InputStream in = null;
switch (connection.getResponseCode()) {
case 201:
in = new BufferedInputStream(connection.getInputStream());
break;
case 401:
in = null;
sb.append("Unauthorized");
break;
case 422:
in = new BufferedInputStream(connection.getErrorStream());
break;
default:
in = null;
sb.append("Unknown response code");
break;
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return sb.toString();
}
// CAP NHAT LOP //
private String putLop(String urlString, String ten, String nien_khoa, int id) throws IOException, JSONException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(urlString + "/" + id + ".json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
try {
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestMethod("PUT");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
JSONObject lop = new JSONObject();
lop.put("ten", ten);
lop.put("nien_khoa", nien_khoa);
JSONObject data = new JSONObject();
data.put("lop", lop);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.toString().getBytes());
outputStream.close();
InputStream in = null;
switch (connection.getResponseCode()) {
case 200:
in = new BufferedInputStream(connection.getInputStream());
break;
case 401:
in = null;
sb.append("Unauthorized");
break;
case 422:
in = new BufferedInputStream(connection.getErrorStream());
break;
default:
in = null;
sb.append("Unknown response code");
break;
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return sb.toString();
}
// XOA LOP //
private String deleteLop(String urlString, int id) throws IOException, JSONException {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL(urlString + "/" + id + ".json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
try {
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-type", "application/json");
connection.setRequestMethod("DELETE");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.connect();
InputStream in = null;
switch (connection.getResponseCode()) {
case 204:
in = new BufferedInputStream(connection.getInputStream());
break;
case 401:
in = null;
sb.append("Unauthorized");
break;
case 422:
in = new BufferedInputStream(connection.getErrorStream());
break;
default:
in = null;
sb.append("Unknown response code");
break;
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return sb.toString();
}
}
|
package info.tasks5.sumToChar;
import static org.junit.Assert.*;
import org.junit.Test;
public class SumToCharTest {
@Test
public void testSumCharValue() {
assertNotNull(SumToChar.sumCharValue());
assertEquals(15, SumToChar.sumCharValue());
assertTrue(SumToChar.sumCharValue() > 10 || 20 < SumToChar.sumCharValue());
}
}
|
package in.ponram.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import in.ponram.dao.ReportRepository;
import in.ponram.dto.ProductDTO;
import in.ponram.model.Order;
@Service
public class ReportManager {
@Autowired
private ReportRepository reportRepository;
public List<ProductDTO> getFullStockReport() {
return reportRepository.findAll();
}
public List<Order> getProductSalesReport(int id) {
return reportRepository.findByProductId(id);
}
}
|
package com.cjx.nexwork.activities;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.cjx.nexwork.R;
import com.cjx.nexwork.fragments.FragmentFriendList;
import com.cjx.nexwork.fragments.UserProfileFragment;
import com.cjx.nexwork.fragments.study.FragmentListStudy;
import com.cjx.nexwork.fragments.work.FragmentListWork;
import com.cjx.nexwork.managers.user.UserDetailCallback;
import com.cjx.nexwork.managers.user.UserManager;
import com.cjx.nexwork.model.User;
import com.cjx.nexwork.util.BlurTransformation;
import com.cjx.nexwork.util.CircleTransform;
import com.cjx.nexwork.util.CustomProperties;
import com.github.florent37.picassopalette.PicassoPalette;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
@SuppressLint("NewApi")
public class ContactProfileActivity extends AppCompatActivity implements UserDetailCallback {
View view;
private User user;
private TextView userFacebook, userTwitter, userGithub, userDescription;
private ProgressBar spinner;
private LinearLayout boxUser;
private ViewPager mViewPager;
Drawable drawableHomeIcon;
Drawable drawableChatIcon;
Drawable drawableManagementIcon;
private TextView userName;
private ImageView userImage;
private TextView userAlias;
private ImageView userBackground;
private TabLayout tabLayout;
public static Boolean profileConnected = false;
CollapsingToolbarLayout collapsingToolbar;
private AppBarLayout appBarLayout;
private Toolbar toolbarCollapsed;
private String userLogin;
private ImageView backButton;
private TextView toolbarTitle;
private int colorScrim = 0;
private int colorTextScrim = 0;
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.collapse_layout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
Bundle extras = getIntent().getExtras();
if(extras != null) {
userLogin = extras.getString("friendlogin");
}
UserManager.getInstance().getUser(userLogin, this);
collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.htab_collapse_toolbar);
//collapsingToolbar.setTitle("Username");
collapsingToolbar.setExpandedTitleColor(getResources().getColor(android.R.color.transparent));
Toolbar htab_toolbar = (Toolbar) findViewById(R.id.htab_toolbar);
toolbarTitle = (TextView) htab_toolbar.findViewById(R.id.toolbar_title);
backButton = (ImageView) htab_toolbar.findViewById(R.id.imageView7);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
appBarLayout = (AppBarLayout) findViewById(R.id.htab_appbar);
tabLayout = (TabLayout) findViewById(R.id.tabs_profile);
AppBarLayout.OnOffsetChangedListener mListener = new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
Log.d("verticalOffset", String.valueOf(verticalOffset));
if (collapsingToolbar.getHeight() + verticalOffset < 2 * ViewCompat.getMinimumHeight(collapsingToolbar)) {
Log.d("collapse", "collapse");
//toolbarTitle.setAlpha(1.0f);
} else {
Log.d("collapsed", "no collapsed");
toolbarTitle.setAlpha(0.0f);
}
if(verticalOffset <= -335){
if(colorScrim == 0){
collapsingToolbar.setContentScrimColor(getResources().getColor(R.color.colorAccent));
collapsingToolbar.setStatusBarScrimColor(getResources().getColor(R.color.colorAccent));
}else{
collapsingToolbar.setContentScrimColor(colorScrim);
collapsingToolbar.setStatusBarScrimColor(colorScrim);
}
if(colorTextScrim == 0){
backButton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
}
else{
backButton.setColorFilter(colorTextScrim, PorterDuff.Mode.SRC_IN);
}
}else{
collapsingToolbar.setContentScrimColor(Color.argb(0,0,0,0));
collapsingToolbar.setStatusBarScrimColor(Color.argb(0,0,0,0));
backButton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}
float alpha = Math.abs(verticalOffset / (float)
appBarLayout.getTotalScrollRange());
userImage.setAlpha(1.0f - alpha);
userName.setAlpha(1.0f - alpha);
userAlias.setAlpha(1.0f - alpha);
toolbarTitle.setAlpha(0.0f + alpha);
}
};
appBarLayout.addOnOffsetChangedListener(mListener);
userName = (TextView) findViewById(R.id.profileUserRealName);
userImage = (ImageView) findViewById(R.id.profileUserImage);
userAlias = (TextView) findViewById(R.id.profileUserAlias);
userBackground = (ImageView) findViewById(R.id.profileUserBackgroundImage);
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
tabLayout.addTab(tabLayout.newTab());
collapsingToolbar.setTitleEnabled(false);
htab_toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
ContactProfileActivity.DemoCollectionPagerAdapter adapter = new ContactProfileActivity.DemoCollectionPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager_profile);
mViewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setText(getString(R.string.works_tab));
tabLayout.getTabAt(1).setText(getString(R.string.studies_tab));
tabLayout.getTabAt(2).setText(getString(R.string.contacts_tab));
}
@Override
public void onSuccess(final User user) {
//collapsingToolbar.setTitleEnabled(false);
// collapsingToolbar.setTitle(user.getFirstName().concat(" ").concat(user.getLastName()));
toolbarTitle.setText(user.getFirstName().concat(" ").concat(user.getLastName()));
if(user.getImagen() == null){
userImage.setImageResource(R.drawable.account_circle);
userBackground.setImageResource(R.drawable.account_circle);
}else{
Log.d("width", String.valueOf(userImage.getWidth()));
Log.d("height", String.valueOf(userImage.getHeight()));
userImage.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// Wait until layout to call Picasso
@Override
public void onGlobalLayout() {
// Ensure we call this only once
userImage.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
Picasso.with(getApplicationContext()).load(CustomProperties.baseUrl+"/"+user.getImagen())
.resize(userImage.getWidth(), userImage.getHeight())
.transform(new CircleTransform())
.into(userImage,
PicassoPalette.with(CustomProperties.baseUrl+"/"+user.getImagen(), userImage)
.intoCallBack(
new PicassoPalette.CallBack() {
@Override
public void onPaletteLoaded(Palette palette) {
paletteToolbar(palette);
}
})
);
}
});
userBackground.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// Wait until layout to call Picasso
@Override
public void onGlobalLayout() {
// Ensure we call this only once
userBackground.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
Picasso
.with(getApplicationContext())
.load(CustomProperties.baseUrl+"/"+user.getImagen())
//.resize(userBackground.getWidth(), userBackground.getHeight())
.resize(userBackground.getWidth(), userBackground.getHeight())
.transform(new BlurTransformation(getApplicationContext()))
.centerCrop()
.into(userBackground);
}
});
}
userName.setText(user.getFirstName() + " " + user.getLastName());
userAlias.setText(user.getLogin());
}
@Override
public void onFailure(Throwable t) {
}
@Override
public void onSuccessSaved(User user) {
}
@Override
public void onFailureSaved(Throwable t) {
}
public class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0: return new FragmentListWork(userLogin, false);
case 1: return new FragmentListStudy(userLogin, false);
case 2: return new FragmentFriendList(userLogin, false);
default: return new FragmentListWork(userLogin, false);
}
}
@Override
public int getCount() {
return 3;
}
public void addFragment(Fragment fragment) {
mFragmentList.add(fragment);
}
}
public void paletteToolbar(Palette palette){
Palette.Swatch vibrantSwatch = palette.getVibrantSwatch();
Palette.Swatch vibrantLightSwatch = palette.getLightVibrantSwatch();
Palette.Swatch vibrantDarkSwatch = palette.getDarkVibrantSwatch();
Palette.Swatch mutedSwatch = palette.getMutedSwatch();
Palette.Swatch dominantSwatch = palette.getDominantSwatch();
Palette.Swatch mutedLightSwatch = palette.getLightMutedSwatch();
Palette.Swatch mutedDarkSwatch = palette.getDarkMutedSwatch();
if(vibrantSwatch != null){
colorScrim = vibrantSwatch.getRgb();
colorTextScrim = vibrantSwatch.getTitleTextColor();
collapsingToolbar.setContentScrimColor(vibrantSwatch.getRgb());
collapsingToolbar.setStatusBarScrimColor(vibrantSwatch.getRgb());
toolbarTitle.setTextColor(vibrantSwatch.getTitleTextColor());
tabLayout.setTabTextColors(vibrantSwatch.getTitleTextColor(), vibrantSwatch.getBodyTextColor());
tabLayout.setBackgroundColor(vibrantSwatch.getRgb());
appBarLayout.setBackgroundColor(vibrantSwatch.getRgb());
}
else{
if(vibrantLightSwatch == null){
colorScrim = dominantSwatch.getRgb();
colorTextScrim = dominantSwatch.getTitleTextColor();
collapsingToolbar.setContentScrimColor(dominantSwatch.getRgb());
collapsingToolbar.setStatusBarScrimColor(dominantSwatch.getRgb());
toolbarTitle.setTextColor(dominantSwatch.getTitleTextColor());
tabLayout.setTabTextColors(dominantSwatch.getTitleTextColor(), dominantSwatch.getBodyTextColor());
tabLayout.setBackgroundColor(dominantSwatch.getRgb());
appBarLayout.setBackgroundColor(dominantSwatch.getRgb());
}
else{
colorTextScrim = vibrantLightSwatch.getTitleTextColor();
toolbarTitle.setTextColor(vibrantLightSwatch.getTitleTextColor());
colorScrim = vibrantLightSwatch.getRgb();
collapsingToolbar.setContentScrimColor(vibrantLightSwatch.getRgb());
collapsingToolbar.setStatusBarScrimColor(vibrantLightSwatch.getRgb());
tabLayout.setTabTextColors(vibrantLightSwatch.getTitleTextColor(), vibrantLightSwatch.getBodyTextColor());
tabLayout.setBackgroundColor(vibrantLightSwatch.getRgb());
appBarLayout.setBackgroundColor(vibrantLightSwatch.getRgb());
}
}
}
}
|
/**
* This problem finds all possible solution to place n queens in a chess so that those queens do not kill themselves
* Remember, queens can kill each other when they are in same row, same column and diagonally
* Time complexity - exponential due to backtracking and space complexity
* Time complexity O(n*n)
* Space complexity O(n*n)
* Refer this link for more details: https://www.youtube.com/watch?time_continue=2&v=xouin83ebxE
*
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class NQueenProblemAllSolution {
//Position class
static class Position {
int row, col;
Position(int row, int col) {
this.row = row;
this.col = col;
}
}
public static List<List<String>> nQueenPos(int n) {
Position[] positions = new Position[n];
List<List<String>> result = new ArrayList<>();
nQueenSolutionUtil(n, 0, positions, result);
return result;
}
public static void nQueenSolutionUtil(int n, int row, Position[] position, List<List<String>> result) {
//means all queens have placed themselves in a position that they are not killing each other
if(n == row) {
StringBuilder sb = new StringBuilder();
List<String> oneResult = new ArrayList<>();
for(Position p: position) {
for(int i = 0; i < n; i++) {
if(p.col == i) {
sb.append("Q ");
} else {
sb.append(". ");
}
}
oneResult.add(sb.toString());
//reset sb to 0
sb.setLength(0);
}
result.add(oneResult);
}
int col;
for(col = 0; col < n; col++) {
boolean foundSafe = true;
//check rows and columns are not under attch for previous queen
for(int queen = 0 ; queen < row; queen++) {
if(position[queen].col == col || position[queen].row - position[queen].col == row - col
|| position[queen].row + position[queen].col == row + col) {
foundSafe = false;
break;
}
}
if(foundSafe) {
position[row] = new Position(row, col);
nQueenSolutionUtil(n, row + 1, position, result);
}
}
}
//main method
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
List<List<String>> lists = nQueenPos(n);
for(List<String> list:lists) {
System.out.print("\n");
for(int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
sc.close();
}
} |
/*
* Created on 22/08/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.persistence.pl.dao;
import java.math.BigInteger;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.entity.pl.TplProdAssetTypeMovEntity;
/**
* @author rcoelho
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface TplProdAssetTypeMovDAO extends BaseTplProdAssetTypeDAO
{
public DataSet list( BigInteger prodAssetTypeCode_, String prodAssetTypeText_ , String lastUpdUserId);
public TplProdAssetTypeMovEntity insert(
TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity_ );
public void update( TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity_ );
public void delete( TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity_ );
public boolean exists( TplProdAssetTypeMovEntity tplProdAssetTypeMovEntity_ );
}
|
package com.dataart.was.entities;
public class WineType extends SimpleEntity{
}
|
package com.binary.smartlib.ui.fragment;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
/**
* Created by yaoguoju on 15-12-24.
*/
public abstract class SmartFragment extends Fragment implements OnClickListener{
protected Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity().getApplicationContext();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return initView(inflater,container,savedInstanceState);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initData(savedInstanceState);
}
@Override
public void onClick(View v) {
onViewClick(v);
}
/**
* 启动应用内Activty
* @param context
* @param toClass
* @param bundle
*/
protected void toActivity(Context context,Class<?> toClass,Bundle bundle) {
if(context == null || toClass == null) {
return ;
}
Intent intent = new Intent(context,toClass);
if(bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* 启动应用外Activty
* @param pkgname
* @param classname
* @param bundle
*/
protected void toActivty(String pkgname,String classname,Bundle bundle) {
if(TextUtils.isEmpty(pkgname) || TextUtils.isEmpty(classname)) {
return ;
}
ComponentName componentName = new ComponentName(pkgname,classname);
Intent intent = new Intent();
intent.setComponent(componentName);
if(bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
/**
* 初始化界面
* @param inflater
* @param container
* @param saveInstanceState
* @return
*/
protected abstract View initView(LayoutInflater inflater,ViewGroup container,Bundle saveInstanceState);
/**
* 初始化数据
* @param savedInstanceState
*/
protected abstract void initData(Bundle savedInstanceState);
/**
* 处理界面View点击事件
* @param v
*/
protected abstract void onViewClick(View v);
}
|
package book;
import controllers.BookController;
import models.Book;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.Application;
import play.data.FormFactory;
import play.data.format.Formatters;
import play.db.jpa.DefaultJPAApi;
import play.db.jpa.JPA;
import play.db.jpa.JPAApi;
import play.i18n.MessagesApi;
import play.inject.guice.GuiceApplicationBuilder;
import play.inject.guice.Guiceable;
import play.libs.Json;
import play.libs.concurrent.HttpExecutionContext;
import play.mvc.Http;
import play.mvc.Result;
import play.twirl.api.Content;
import repositories.BookRepository;
import repositories.SBookRepository;
import javax.persistence.EntityManager;
import javax.validation.Validator;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import static java.util.concurrent.CompletableFuture.supplyAsync;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static play.mvc.Http.Status.OK;
import static play.mvc.Http.Status.SEE_OTHER;
import static play.test.Helpers.*;
/**
* Created by greenlucky on 6/3/17.
*/
public class UnitTest{
private static final Logger LOGGER = LoggerFactory.getLogger(UnitTest.class);
private JPAApi jpaApi;
@Before
public void init() throws Exception {
}
@Test
public void checkIndex() {
BookRepository repository = mock(BookRepository.class);
SBookRepository srepository = mock(SBookRepository.class);
FormFactory formFactory = mock(FormFactory.class);
HttpExecutionContext ec = new HttpExecutionContext(ForkJoinPool.commonPool());
final BookController controller = new BookController(formFactory, repository, srepository, ec);
final Result result = controller.index();
assertThat(result.status()).isEqualTo(OK);
}
@Test
public void checkTemplate() throws Exception {
Content html = views.html.book.render();
assertThat(html.contentType()).isEqualTo("text/html");
assertThat(contentAsString(html)).contains("Add book");
}
@Test
public void checkAddBook() throws Exception {
MessagesApi messages = mock(MessagesApi.class);
Validator validator = mock(Validator.class);
FormFactory formFactory = new FormFactory(messages, new Formatters(messages), validator);
SBookRepository srepository = mock(SBookRepository.class);
BookRepository repository = mock(BookRepository.class);
Book book = new Book.BookBuilder()
.setId(1L)
.setName("Play Action")
.setPrice(10.5)
.createBook();
when(repository.add(any(Book.class))).thenReturn(supplyAsync(() -> book));
final Http.RequestBuilder requestBuilder = new Http.RequestBuilder().method("post").bodyJson(Json.toJson(book));
final CompletionStage<Result> stage = invokeWithContext(requestBuilder, () -> {
HttpExecutionContext ec = new HttpExecutionContext(ForkJoinPool.commonPool());
final BookController controller = new BookController(formFactory, repository, srepository, ec);
return controller.addBook();
});
verify(repository).add(book);
await().atMost(1, TimeUnit.SECONDS).until(() -> {
assertThat(stage.toCompletableFuture()).isCompletedWithValueMatching(result ->
result.status() == SEE_OTHER, ""
);
});
}
@Test
public void getBook() throws Exception {
BookRepository repository = mock(BookRepository.class);
verify(repository).get(1L);
}
@Test
public void removeBook() throws Exception {
final Http.RequestBuilder requestBuilder1 = new Http.RequestBuilder().method("get").bodyJson(Json.toJson(1));
final CompletionStage<Result> stage = invokeWithContext(requestBuilder1, () -> {
FormFactory formFactory = mock(FormFactory.class);
BookRepository repository = mock(BookRepository.class);
SBookRepository srepository = mock(SBookRepository.class);
HttpExecutionContext ec = new HttpExecutionContext(ForkJoinPool.commonPool());
final BookController controller = new BookController(formFactory, repository, srepository, ec);
return controller.deleteBook(1);
});
await().atMost(1, TimeUnit.SECONDS).until(() ->
assertThat(stage.toCompletableFuture()).isCompletedWithValueMatching(result ->
result.status() == SEE_OTHER, ""
)
);
Thread.sleep(100);
}
@Test
public void addBoosTest() throws Exception {
running(fakeApplication(), new Runnable() {
@Override
public void run() {
JPA.withTransaction(() -> {
EntityManager em = JPA.em();
Book book = new Book.BookBuilder()
.setName("Play Action")
.setPrice(10.5)
.createBook();
em.persist(book);
Book actualBook = em.find(Book.class, book.getId());
Assert.assertEquals(actualBook, book);
});
}
});
Thread.sleep(100);
}
}
|
public class TrolleyItem {
private Product product;
private int quantity;
private Company company;
public TrolleyItem(Product product, int quantity, Company company) {
this.product = product;
this.quantity = quantity;
this.company = company;
}
public void changeQuantity(int quantity) {
this.quantity = quantity;
}
public void addQuantity(int quantity) {
this.quantity += quantity;
}
public void subQuantity(int quantity) {
this.quantity -= quantity;
}
public String toString() {
return product.getName() + "(" + product.getPid() + ") $" + product.getPrice() + "*" + quantity + " $"
+ (product.getPrice() * quantity);
}
public Product getProduct() {
return this.product;
}
public int getQuantity() {
return this.quantity;
}
public double getTotal() {
return product.getPrice() * quantity;
}
public Company getCompany() {
return company;
}
}
|
package kow.test.filesystem;
import java.io.File;
import org.junit.Test;
public class TestEnoughSpace {
@Test
public void testHaveSpace() {
org.junit.Assert.assertEquals("must be true", true, EnoughSpace.canWrite(1));
}
@Test
public void testNotEnough() {
File file = new File(".");
long freeBytes = file.getFreeSpace();
org.junit.Assert.assertEquals("must be false", false, EnoughSpace.canWrite(freeBytes + 1));
}
}
|
package ru.goodroads.net.jsonrpc;
public class JSONRPCClientException extends Exception {
private static final long serialVersionUID = 1L;
public JSONRPCClientException(String message) {
super(message);
}
}
|
package com.ifeng.recom.mixrecall.common.model.item;
import java.util.List;
import java.util.Map;
import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo;
import lombok.Getter;
import lombok.Setter;
/**
* Created by jibin on 2018/1/23.
*/
@Getter
@Setter
public class MixResult {
/**
* 召回结果
*/
List<Index4User> index4UserList;
/**
* 预留,供召回实验分组,回传引擎使用
*/
Map<String, String> abtestMap;
/**
* 召回批次id
*/
String recallid;
public MixResult() {
}
public MixResult(List<Index4User> index4UserList, Map<String, String> abtestMap, MixRequestInfo mixRequestInfo) {
this.index4UserList = index4UserList;
this.recallid = mixRequestInfo.getRecallid();
this.abtestMap = abtestMap;
}
}
|
package intelligent.net.agent;
import org.apache.mina.statemachine.annotation.State;
import org.apache.mina.statemachine.annotation.Transition;
public class NodeStateHandler {
@State public static final String OK = "Normal";
@State public static final String ADJ = "Adjancies Problem";
@State public static final String SW = "Software/Configuration Problem";
@Transition(on = "ok2adj", in = OK, next = ADJ)
public void ok2adj(String Msg) {
System.out.println("ok2adj Transition");
}
@Transition(on = "adj2sw", in = ADJ, next = SW)
public void adj2sw(String Msg) {
System.out.println("adj2sw Transition");
}
@Transition(on = "ok2sw", in = OK, next = SW)
public void ok2sw(String Msg) {
System.out.println("ok2sw Transition");
}
@Transition(on = "sw2adj", in = SW, next = ADJ)
public void sw2adj(String Msg) {
System.out.println("sw2adj transition");
}
@Transition(on = "adj2ok", in = ADJ, next = OK)
public void adj2okTape(String Msg) {
System.out.println("adj2ok Transition");
}
} |
package com.example.nene.movie20.activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.nene.movie20.R;
import com.example.nene.movie20.adapter.VideoListAdapter;
import com.example.nene.movie20.data.DataServer;
import com.example.nene.movie20.data.Video;
import java.util.List;
public class VideoListActivity extends AppCompatActivity {
private RecyclerView recyclerView;
VideoListAdapter videoListAdapter;
private List<Video> data = DataServer.getVideoListData();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initView();
}
private void initView() {
recyclerView = findViewById(R.id.video_list_rv);
recyclerView.setLayoutManager(new GridLayoutManager(VideoListActivity.this,2));
videoListAdapter = new VideoListAdapter(R.layout.content_video, data);
recyclerView.setAdapter(videoListAdapter);
}
}
|
package com.ifeng.recom.mixrecall.core.channel.impl;
import com.ifeng.recom.mixrecall.common.constant.GyConstant;
import com.ifeng.recom.mixrecall.common.constant.RecomChannelEnum;
import com.ifeng.recom.mixrecall.common.model.Document;
import com.ifeng.recom.mixrecall.common.model.UserModel;
import com.ifeng.recom.mixrecall.common.model.request.LogicParams;
import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo;
import com.ifeng.recom.mixrecall.core.channel.excutor.UserSubRecallExecutor;
import com.ifeng.recom.tools.common.logtools.model.TimerEntity;
import com.ifeng.recom.tools.common.logtools.utils.timer.TimerEntityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lilg1 on 2018/1/18.
*/
@Service
public class UserSubChannelImpl {
private final static Logger logger = LoggerFactory.getLogger(UserSubChannelImpl.class);
private static final Logger timeLogger = LoggerFactory.getLogger(TimerEntityUtil.class);
private final static int timeout = 400;
/**
* 用户订阅通道
* @param mixRequestInfo
* @return
*/
public List<Document> doRecall(MixRequestInfo mixRequestInfo) {
UserModel userModel = mixRequestInfo.getUserModel();
TimerEntity timer = TimerEntityUtil.getInstance();
timer.addStartTime("total");
LogicParams logicParams = mixRequestInfo.getLogicParams();
List<Document> result = new ArrayList<>();
try {
UserSubRecallExecutor userSubRecallExecutor = new UserSubRecallExecutor(mixRequestInfo, logicParams);
result = userSubRecallExecutor.call();
} catch (Exception e) {
logger.error("User Sub thread error {}", e);
e.printStackTrace();
}
timer.addEndTime("total");
timeLogger.info("ChannelLog UserSubChannel {} uid:{}", timer.getStaticsInfo(), userModel.getUserId());
TimerEntityUtil.remove();
return result;
}
private int getNumToAdd(MixRequestInfo mixRequestInfo) {
int numToAdd = GyConstant.num_Sub;
if (RecomChannelEnum.momentsnew.getValue().equals(mixRequestInfo.getRecomChannel())) {
numToAdd = GyConstant.num_Sub_Momentsnew;
}
return numToAdd;
}
}
|
package com.example.user.kurswork;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
public class MyService extends Service {
NotificationManager nm;
DBHelper db;
ExecutorService es;
Integer NOTIFICATION_ID = 0;
@Override
public void onCreate() {
super.onCreate();
es = Executors.newFixedThreadPool(1);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
db = new DBHelper(getApplicationContext());
}
public int onStartCommand(Intent intent, int flags, int startId) {
es.execute(new MyRunner(intent));
stopSelf();
return START_STICKY;
}
public void onDestroy() {
super.onDestroy();
}
public IBinder onBind(Intent arg0) {
return null;
}
void sendNotif(Intent intent) {
String text = "";
String currDate = intent.getExtras().getString("currDate");
String today = intent.getExtras().getString("time");
SQLiteDatabase dbHelper = db.getReadableDatabase();
Cursor c = null;
if (dbHelper != null) {
try {
c = dbHelper.query("myDb", new String[]{"task"}, "date=? AND time=?", new String[]{currDate, today}, null, null, null);
c.moveToFirst();
text = c.getString(c.getColumnIndexOrThrow("task"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (c != null) {
if (c.isLast()) {
c.close();
}
c.close();
}
}
if (text == null || text.equals("")) {
text = "";
} else {
Intent resultIntent = new Intent(this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Нужно сделать")
.setContentText(text)
.setContentIntent(resultPendingIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
++NOTIFICATION_ID;
nm.notify(NOTIFICATION_ID, notification);
}
}
db.close();
}
class MyRunner implements Runnable{
Intent intent;
MyRunner(Intent intent1){
intent = intent1;
}
@Override
public void run() {
sendNotif(intent);
}
}
} |
package status;
import task.Task_Status;
public class Testing extends Status{
public Testing() {
super("Testing", "Lorem ipsum dolor sit amet, consectetur adipiscing elit");
anterior = Task_Status.TO_DO;
siguiente = Task_Status.DONE;
}
}
|
/*
* TransactionDaoImplJDBC.java
*
* Created on 2008年2月24日, 下午3:54
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package tot.dao.jdbc;
import tot.dao.AbstractDao;
import tot.db.DBUtils;
import tot.util.StringUtils;
import tot.global.Sysconfig;
import tot.exception.ObjectNotFoundException;
import tot.exception.DatabaseException;
import java.sql.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import tot.bean.DataField;
/**
*
* @author Administrator
*/
public class TransactionDaoImplJDBC extends AbstractDao{
private static Log log = LogFactory.getLog(TransactionDaoImplJDBC.class);
/** Creates a new instance of TransactionDaoImplJDBC */
public TransactionDaoImplJDBC() {
}
/** add transation history
* @param transtype 交易类别,0=在线充值,1=人工录款,2=会员支付交易
* @param money 充值数值,单位:元
* @param fromuser 来自
* @param touser 去向
* @param moditime 日期
* @param status 状态
* @param fname 产品名称
* @param furl 产品地址
* @param fdesc 备注
* @param transid 流水号
* @return boolean 返回值,bool(是/否)
*/
public boolean addTransaction(int transtype,Float money,String fromuser,String touser,Timestamp moditime,int status,String fname,String furl,String fdesc,String transid){
Connection conn = null;
PreparedStatement ps = null;
boolean returnValue=true;
String sql="insert into t_transaction(TransType,Money,FromUser,ToUser,TransDate,Fstatus,Fname,Furl,Fdesc,TransId) values(?,?,?,?,?,?,?,?,?,?)";
try{
conn = DBUtils.getConnection();
conn.setAutoCommit(false);
ps=conn.prepareStatement(sql);
ps.setInt(1,transtype);
ps.setFloat(2,money);
ps.setString(3,fromuser);
ps.setString(4,touser);
ps.setTimestamp(5,moditime);
ps.setInt(6,status);
ps.setString(7,fname);
ps.setString(8,furl);
ps.setString(9,fdesc);
ps.setString(10,transid);
if(ps.executeUpdate()!=1) returnValue=false;
conn.commit();
} catch(SQLException e){
if(conn!=null){
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
log.error("add Transaction error",e);
} finally{
if(conn!=null){
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return returnValue;
}
public boolean delTransaction(int id) throws ObjectNotFoundException,DatabaseException{
return exe("delete from t_transaction where id="+id);
}
public void batDel(String[] s){
this.bat("delete from t_transaction where id=?",s);
}
public Collection getTransactionList_Limit(int currentpage,int pagesize,String uid){
String fields="id,TransType,Money,FromUser,ToUser,TransDate,Fstatus,Fname,Furl,Fdesc,TransId";
if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){
return getDataList_mysqlLimit("select "+fields+" from t_transaction where ToUser='"+uid+"' or FromUser='"+uid+"' order by id desc",fields,pagesize,(currentpage-1)*pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
String sql="SELECT TOP "+pagesize+" "+fields+" FROM t_transaction WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP "+((currentpage-1)*pagesize+1)+" id FROM t_transaction where ToUser='"+uid+"' or FromUser='"+uid+"' ORDER BY id DESC) AS t)) and (ToUser='"+uid+"' or FromUser='"+uid+"') ORDER BY id DESC";
return getData(sql,fields);
} else{
return getDataList_Limit_Normal("select "+fields+" from t_transaction",fields,pagesize,(currentpage-1)*pagesize);
}
}
public Collection getTransactionList_Limit(int tanstype,int status,String userid,String dateStart,String dateEnd,int currentpage,int pagesize){
String fields="id,TransType,Money,FromUser,ToUser,TransDate,Fstatus,Fname,Furl,TransId";
StringBuffer sql=new StringBuffer(512);
if(DBUtils.getDatabaseType() == DBUtils.DATABASE_MYSQL){
sql.append("select "+fields+" from t_transaction where 1=1");
if(tanstype>=0){
sql.append(" and TransType="+tanstype);
}
if(status>=0){
sql.append(" and Fstatus="+status);
}
if(userid!=null){
sql.append(" and (ToUser='"+userid+"' or FromUser='"+userid+"')");
}
if(dateStart!=null && dateEnd!=null){
sql.append(" and to_days(TransDate)>=to_days('").append(dateStart).append("') and to_days(TransDate)<=to_days('").append(dateEnd).append("')");
}
//System.out.print(sql.toString());
sql.append(" order by id desc");
return getDataList_mysqlLimit(sql.toString(),fields,pagesize,(currentpage-1)*pagesize);
} else if (DBUtils.getDatabaseType() == DBUtils.DATABASE_SQLSERVER) {
//String sql="SELECT TOP "+pagesize+" "+fields+" FROM t_transaction WHERE (id <=(SELECT MIN(id) FROM (SELECT TOP "+((currentpage-1)*pagesize+1)+" id FROM t_transaction ORDER BY id DESC) AS t)) ORDER BY id DESC";
return getData(sql.toString(),fields);
} else{
return getDataList_Limit_Normal("select "+fields+" from t_transaction",fields,pagesize,(currentpage-1)*pagesize);
}
}
public int getTotalCount(int tanstype,int status,String userid,String dateStart,String dateEnd){
int totalNum=0;
//数据库变量
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
StringBuffer sql=new StringBuffer(512);
sql.append("select count(*) from t_transaction where 1=1");
if(tanstype>=0){
sql.append(" and TransType="+tanstype);
}
if(status>=0){
sql.append(" and Fstatus="+status);
}
if(userid!=null){
sql.append(" and (ToUser='"+userid+"' or FromUser='"+userid+"')");
}
if(dateStart!=null && dateEnd!=null){
sql.append(" and to_days(TransDate)>=to_days('").append(dateStart).append("') and to_days(TransDate)<=to_days('").append(dateEnd).append("')");
}
try{
conn = DBUtils.getConnection();
ps=conn.prepareStatement(sql.toString());
rs=ps.executeQuery();
if(rs.next()){
totalNum=rs.getInt(1);
}
}catch(SQLException e){
} finally{
DBUtils.closeResultSet(rs);
DBUtils.closePrepareStatement(ps);
DBUtils.closeConnection(conn);
}
return totalNum;
}
public DataField getTransaction(int id){
String fields="TransType,Money,FromUser,ToUser,TransDate,Fstatus,Fname,Furl,Fdesc,TransId";
return getFirstData("select "+fields+" from t_transaction where id="+id,fields);
}
}
|
package com.legaoyi.protocol.upstream.messagebody;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.legaoyi.protocol.message.MessageBody;
/**
* 终端升级结果通知
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2019-05-20
*/
@Scope("prototype")
@Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "0108_2019" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX)
public class Jt808_2019_0108_MessageBody extends MessageBody {
private static final long serialVersionUID = -3392914164582453750L;
public static final String MESSAGE_ID = "0108";
/** 升级类型 **/
@JsonProperty("upgradeType")
private int upgradeType;
/** 升级结果 **/
@JsonProperty("result")
private int result;
public final int getUpgradeType() {
return upgradeType;
}
public final void setUpgradeType(int upgradeType) {
this.upgradeType = upgradeType;
}
public final int getResult() {
return result;
}
public final void setResult(int result) {
this.result = result;
}
}
|
package slimeknights.tconstruct.tools.common.tileentity;
import net.minecraft.block.Block;
import net.minecraft.block.BlockPane;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import slimeknights.mantle.common.IInventoryGui;
import slimeknights.tconstruct.shared.block.BlockTable;
import slimeknights.tconstruct.shared.block.PropertyTableItem;
import slimeknights.tconstruct.shared.inventory.ConfigurableInvWrapperCapability;
import slimeknights.tconstruct.shared.tileentity.TileTable;
import slimeknights.tconstruct.tools.common.client.GuiCraftingStation;
import slimeknights.tconstruct.tools.common.inventory.ContainerCraftingStation;
public class TileCraftingStation extends TileTable implements IInventoryGui {
public TileCraftingStation() {
super("gui.craftingstation.name", 9);
this.itemHandler = new ConfigurableInvWrapperCapability(this, true, false);
}
@Override
public Container createContainer(InventoryPlayer inventoryplayer, World world, BlockPos pos) {
return new ContainerCraftingStation(inventoryplayer, this);
}
@Override
@SideOnly(Side.CLIENT)
public GuiContainer createGui(InventoryPlayer inventoryplayer, World world, BlockPos pos) {
return new GuiCraftingStation(inventoryplayer, world, pos, this);
}
@Override
protected IExtendedBlockState setInventoryDisplay(IExtendedBlockState state) {
PropertyTableItem.TableItems toDisplay = new PropertyTableItem.TableItems();
float s = 0.125f;
float o = 3f / 16f; // we want to move it 3 pixel in a 16 width texture
for(int i = 0; i < 9; i++) {
ItemStack itemStack = getStackInSlot(i);
PropertyTableItem.TableItem item = getTableItem(itemStack, this.getWorld(), null);
if(item != null) {
item.x = +o - (i % 3) * o;
item.z = +o - (i / 3) * o;
item.y = -0.5f + s / 32f; // half itemmodel height + move it down to the bottom from the center
//item.s *= 0.46875f;
item.s = s;
// correct itemblock because scaling
if(itemStack.getItem() instanceof ItemBlock && !(Block.getBlockFromItem(itemStack.getItem()) instanceof BlockPane)) {
item.y = -(1f - item.s) / 2f;
}
//item.s *= 2/5f;
toDisplay.items.add(item);
}
}
// add inventory if needed
return state.withProperty(BlockTable.INVENTORY, toDisplay);
}
}
|
package ch.usz.fhirstack;
import android.content.Context;
import android.util.Log;
import com.birbit.android.jobqueue.JobManager;
import com.birbit.android.jobqueue.config.Configuration;
import com.birbit.android.jobqueue.log.CustomLogger;
import ca.uhn.fhir.context.FhirContext;
import ch.usz.fhirstack.dataqueue.DataQueue;
/**
* Created by manny on 08.06.2016.
*/
public class FHIRStack {
private static FhirContext fhirContext;
private static JobManager jobManager;
private static DataQueue dataQueue;
private FHIRStack() {
}
public static void init(Context context, String FHIRServerURL) {
initFhirContext();
initJobManager(context);
initDataQueue(FHIRServerURL);
}
public static void init(Context context) {
initFhirContext();
initJobManager(context);
}
public static void initFhirContext() {
if (fhirContext == null) {
fhirContext = FhirContext.forDstu3();
}
}
public static void initJobManager(Context context) {
if (jobManager == null) {
jobManager = new JobManager(getDefaultBuilder(context).build());
}
}
public static void initDataQueue(String FHIRServerURL){
if (dataQueue == null){
dataQueue = new DataQueue(FHIRServerURL, getJobManager());
}
}
public static FhirContext getFhirContext() {
return fhirContext;
}
public static JobManager getJobManager() {
return jobManager;
}
public static DataQueue getDataQueue(){
return dataQueue;
}
private static Configuration.Builder getDefaultBuilder(Context context) {
Configuration.Builder builder = new Configuration.Builder(context)
.customLogger(new CustomLogger() {
private static final String TAG = "JOBMANAGER";
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public void d(String text, Object... args) {
Log.d(TAG, String.format(text, args));
}
@Override
public void e(Throwable t, String text, Object... args) {
Log.e(TAG, String.format(text, args), t);
}
@Override
public void e(String text, Object... args) {
Log.e(TAG, String.format(text, args));
}
@Override
public void v(String text, Object... args) {
}
})
.minConsumerCount(1)//always keep at least one consumer alive
.maxConsumerCount(3)//up to 3 consumers at a time
.loadFactor(3)//3 jobs per consumer
.consumerKeepAlive(120);//wait 2 minute
return builder;
}
}
|
package com.trump.auction.order.model;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
public class PaymentInfoModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3107927688647724241L;
private Integer id;
private String paymentId;
private Integer userId;
private String orderId;
private String userPhone;
private BigDecimal paymentAmount;
private Date buyPayTime;
private BigDecimal orderAmount;
private Integer paymentType;
private Integer paymentSubtype;
private String serialNo;
private Integer paymentStatus;
private Integer paymentCount;
private String remark;
private String paymentRemark;
private Integer payflag;
private Date updateTime;
private Date createDate;
private Integer buyCoinId;
private BigDecimal buyCoinMoney;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPaymentId() {
return paymentId;
}
public void setPaymentId(String paymentId) {
this.paymentId = paymentId == null ? null : paymentId.trim();
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone == null ? null : userPhone.trim();
}
public BigDecimal getPaymentAmount() {
return paymentAmount;
}
public void setPaymentAmount(BigDecimal paymentAmount) {
this.paymentAmount = paymentAmount;
}
public Date getBuyPayTime() {
return buyPayTime;
}
public void setBuyPayTime(Date buyPayTime) {
this.buyPayTime = buyPayTime;
}
public BigDecimal getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(BigDecimal orderAmount) {
this.orderAmount = orderAmount;
}
public Integer getPaymentType() {
return paymentType;
}
public void setPaymentType(Integer paymentType) {
this.paymentType = paymentType;
}
public Integer getPaymentSubtype() {
return paymentSubtype;
}
public void setPaymentSubtype(Integer paymentSubtype) {
this.paymentSubtype = paymentSubtype;
}
public String getSerialNo() {
return serialNo;
}
public void setSerialNo(String serialNo) {
this.serialNo = serialNo == null ? null : serialNo.trim();
}
public Integer getPaymentStatus() {
return paymentStatus;
}
public void setPaymentStatus(Integer paymentStatus) {
this.paymentStatus = paymentStatus;
}
public Integer getPaymentCount() {
return paymentCount;
}
public void setPaymentCount(Integer paymentCount) {
this.paymentCount = paymentCount;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getPaymentRemark() {
return paymentRemark;
}
public void setPaymentRemark(String paymentRemark) {
this.paymentRemark = paymentRemark == null ? null : paymentRemark.trim();
}
public Integer getPayflag() {
return payflag;
}
public void setPayflag(Integer payflag) {
this.payflag = payflag;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Integer getBuyCoinId() {
return buyCoinId;
}
public void setBuyCoinId(Integer buyCoinId) {
this.buyCoinId = buyCoinId;
}
public BigDecimal getBuyCoinMoney() {
return buyCoinMoney;
}
public void setBuyCoinMoney(BigDecimal buyCoinMoney) {
this.buyCoinMoney = buyCoinMoney;
}
} |
package com.example.krishna.tripmaza;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import static android.R.string.no;
public class HotelsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word(" Hotel Maurya -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: boring road ",R.drawable.mayurya));
words.add(new Word(" Hotel The Panache -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: bally road ",R.drawable.hotel2));
words.add(new Word(" Hotel Chanakya--Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: boring road ",R.drawable.hotel3));
words.add(new Word(" Hotel Patliputra--Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: bally road ",R.drawable.hotel4));
words.add(new Word(" Hotel Recedency -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: Gandhi medan ",R.drawable.mayurya));
words.add(new Word(" Hotel Fort -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: boring road ",R.drawable.hotel2));
words.add(new Word(" Hotel Windsor -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: Gandhi medan",R.drawable.hotel3));
words.add(new Word(" Hotel Republic -- Rs:7079/day "," 5 star hotel \n Contact no: 7543045467 \n Address: boring road ",R.drawable.hotel4));
WordAdapter adapter = new WordAdapter(this,words,R.color.textColor);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
|
package com.payroll.presentation;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.payroll.business.Employee;
import com.payroll.business.FullTime;
import com.payroll.business.MonthlyPayAscComparator;
import com.payroll.business.MonthlyPayDESCComparator;
public class PayrollProgram {
private static void printStars() {
System.out.println("**********");
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
printStars();
System.out.println(new Date());
FullTime ft = new FullTime("bob","bob@gmail.com",125000);
FullTime ft2 = new FullTime("nancy","nancy@gmail.com",5000);
FullTime ft3 = new FullTime("anubhav","anubhav@gmail.com",25000);
Employee[] employees = new Employee[3];
employees[0] = ft;
employees[1] = ft2;
employees[2] = ft3;
for (Employee temp : employees) {
System.out.println(temp);
}
System.out.println("******");
Arrays.sort(employees);
for (Employee temp : employees) {
System.out.println(temp);
}
System.out.println("****** Pay Ascending ******");
Arrays.sort(employees, new MonthlyPayAscComparator());
for (Employee temp : employees) {
System.out.println(temp);
}
System.out.println("****** Pay DESC ******");
//anonymous inner class
Arrays.sort(employees,
(Object o1, Object o2) -> {
Employee emp1 = (Employee) o1;
Employee emp2 = (Employee) o2;
//if THIS object comes BEFORE o POSITIVE
if (emp1.calcMonthlyPay() > emp2.calcMonthlyPay()) {
return 111;
}
//if THIS object comes AFTER o NEGATIVE
else if (emp1.calcMonthlyPay() < emp2.calcMonthlyPay()) {
return -222111;
}
return 0; // EQUAL
}
);
for (Employee temp : employees) {
System.out.println(temp);
}
Map<Employee, String> myMap = new HashMap<Employee, String>();
myMap.put(ft, "hello");
String received = myMap.get(ft);
//myMap.put("World", ft2)
String[] currencies = { "one", "two", "three"};
List<String> currList = Arrays.asList(currencies);
}
}
|
package com.git.cloud.handler.automation.fw.impl;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.git.cloud.handler.automation.fw.FirewallCommonHandler;
import com.git.cloud.handler.automation.fw.model.NatStatusEnum;
import com.git.cloud.handler.automation.fw.model.NatTypeEnum;
import com.git.cloud.handler.automation.fw.model.RmNwOutsideNatPolicyPo;
/**
* 删除山石防火墙NAT
* @author shl
*/
public class DeleteHillstoneNatHandler extends FirewallCommonHandler {
private static Logger logger = LoggerFactory.getLogger(DeleteHillstoneNatHandler.class);
public void executeOperate(HashMap<String, Object> contextParams) throws Exception {
logger.info("[DeleteHillstoneNatHandler] delete nat start ...");
String srId = (String) contextParams.get("srvReqId");
String firewallRequestId = super.findFirewallRequestIdBySrId(srId);
// 根据防火墙请求ID获取NAT策略
List<RmNwOutsideNatPolicyPo> natPolicyList = super.getFirewallAutomationService().findRmNwOutsideNatPolicyListByFirewallRequestId(firewallRequestId);
logger.info("[DeleteHillstoneNatHandler] the object natPolicyList is : " + JSONObject.toJSONString(natPolicyList));
int natPolicyLen = natPolicyList == null ? 0 : natPolicyList.size();
RmNwOutsideNatPolicyPo natPolicy = null;
String ids = "";
for (int i = 0 ; i < natPolicyLen ; i++) {
natPolicy = natPolicyList.get(i);
ids += "," + natPolicy.getTargetNatId();
}
if (ids.length() > 0) {
logger.info("[DeleteHillstoneNatHandler] delete hillstone nat start ...");
super.getFirewallAutomationService().updateOutsideNatPolicyDeleteStatus(natPolicyList);
ids = ids.substring(1);
if (natPolicy.getNatType().equals(NatTypeEnum.DNAT.getValue())) {
super.getFirewallAutoRao().deleteHillstoneDnat(natPolicy.getFwId(), ids.split(","));
} else if (natPolicy.getNatType().equals(NatTypeEnum.SNAT.getValue())) {
super.getFirewallAutoRao().deleteHillstoneSnat(natPolicy.getFwId(), ids.split(","));
}
logger.info("[DeleteHillstoneNatHandler] delete hillstone nat end ...");
}
// 根据防火墙申请ID删除关联的Nat策略关系表
super.getFirewallAutomationService().deleteRmNwOutsideNatPolicyRefByFirewallRequestId(firewallRequestId);
logger.info("[DeleteHillstoneNatHandler] delete nat end ...");
}
}
|
package com.pibs.action;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.pibs.constant.ActionConstant;
import com.pibs.constant.MapConstant;
import com.pibs.constant.MiscConstant;
import com.pibs.constant.ModuleConstant;
import com.pibs.constant.ParamConstant;
import com.pibs.form.BillingDetailsFormBean;
import com.pibs.model.Billing;
import com.pibs.model.User;
import com.pibs.service.ServiceManager;
import com.pibs.service.ServiceManagerImpl;
import com.pibs.util.BillingUtils;
public class BillingDetailsAction extends Action {
private final static Logger logger = Logger.getLogger(BillingDetailsAction.class);
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
BillingDetailsFormBean formBean = (BillingDetailsFormBean) form;
String forwardAction = ActionConstant.NONE;
String command = request.getParameter("command");
//session expired checking
if (request.getSession().getAttribute(MiscConstant.USER_SESSION) == null) {
forwardAction = ActionConstant.SHOW_AJAX_EXPIRED;
} else {
if (command!=null) {
// int module = ModuleConstant.BILLING_DETAILS;
if (command.equalsIgnoreCase(ParamConstant.AJAX_GO_TO_CHILD)) {
//fetch the data
int patientCaseSystemId = Integer.parseInt(request.getParameter("patientCaseSystemId"));
formBean.setPatientCaseSystemId(patientCaseSystemId);
BillingUtils bill = new BillingUtils();
bill.setPatientCaseSystemId(patientCaseSystemId);
//below should be in order for the billing report
bill.getLaboratoryExaminationDetails();
bill.getMedicalSupplyDetails();
bill.getRadiologyDetails();
bill.getSurgeryDetails();
bill.getAdditionalServicesDetails();
bill.getEquipmentDetails();
bill.computeRoomFee();
bill.getOtherRoomDetails();
bill.computeDoctorFee();
bill.getOtherDoctorDetails();
bill.computeTotalAmtFee();
bill.getDiscountDetails();
bill.computeTotalAmtDue();
//set the list/details
formBean.setLabExamList(bill.getLabExamList());
formBean.setMedSupplyList(bill.getMedSupplyList());
formBean.setRadiologyList(bill.getRadiologyList());
formBean.setSurgeryList(bill.getSurgeryList());
formBean.setAdditionalServicesList(bill.getAdditionalServicesList());
formBean.setEquipmentList(bill.getEquipmentList());
formBean.setOtherRoomList(bill.getOtherRoomList());
formBean.setOtherDoctorList(bill.getOtherDoctorList());
formBean.setDiscountList(bill.getDiscountList());
//set totals
formBean.setTotalAmtLabExam(bill.getTotalAmtLabExam());
formBean.setTotalAmtMedSupply(bill.getTotalAmtMedSupply());
formBean.setTotalAmtRadiology(bill.getTotalAmtRadiology());
formBean.setTotalAmtSurgery(bill.getTotalAmtSurgery());
formBean.setTotalAmtAddServices(bill.getTotalAmtAddServices());
formBean.setTotalAmtEquip(bill.getTotalAmtEquip());
formBean.setTotalAmtRoom(bill.getTotalAmtRoom());
formBean.setTotalAmtOtherRoom(bill.getTotalAmtOtherRoom());
formBean.setTotalAmtDoctor(bill.getTotalAmtDoctor());
formBean.setTotalAmtOtherDoctor(bill.getTotalAmtOtherDoctor());
formBean.setTotalAmtFee(bill.getTotalAmtFee());
formBean.setTotalAmtDiscount(bill.getTotalAmtDiscount());
formBean.setTotalAmtDue(bill.getTotalAmtDue());
formBean.setDaysAdmitted(bill.getDaysAdmitted());
formBean.setRoomRate(bill.getRoomRate());
formBean.setDoctorFee(bill.getDoctorFee());
//check first if record exists in Patient bill table
Billing modelCheck = new Billing();
modelCheck.setPatientCaseSystemid(patientCaseSystemId);
HashMap<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put(MapConstant.MODULE, ModuleConstant.BILLING);
dataMap.put(MapConstant.CLASS_DATA, modelCheck);
dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA);
ServiceManager service = new ServiceManagerImpl();
Map<String, Object> resultMap = service.executeRequest(dataMap);
if (resultMap!=null && !resultMap.isEmpty()) {
Billing model = (Billing) resultMap.get(MapConstant.CLASS_DATA);
User user = (User) request.getSession().getAttribute(MiscConstant.USER_SESSION);
dataMap = null;
service = null;
resultMap = null;
formBean.populateModelBilling(bill);//need to get the latest computation from BillingUtils
if (model.getId()>0) {
formBean.getModelBilling().setId(model.getId());//update the billing id for update
//code here for update
dataMap = new HashMap<String, Object>();
dataMap.put(MapConstant.MODULE, ModuleConstant.BILLING);
dataMap.put(MapConstant.CLASS_DATA, formBean.getModelBilling());
dataMap.put(MapConstant.USER_SESSION_DATA, user);
dataMap.put(MapConstant.ACTION, ActionConstant.UPDATE);
service = new ServiceManagerImpl();
resultMap = service.executeRequest(dataMap);
if (resultMap!=null && !resultMap.isEmpty()) {
boolean transactionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS);
if (transactionStatus) {
formBean.setTransactionStatus(transactionStatus);
//need to update the formbean for Billing Id
formBean.updateFormBeanForBillingId();
logger.info("Patient Bill successfully updated (Patient case system ID): " + formBean.getPatientCaseSystemId());//Patient Case System Id
}
}
} else {
//save totals to patient bill table
dataMap = new HashMap<String, Object>();
dataMap.put(MapConstant.MODULE, ModuleConstant.BILLING);
dataMap.put(MapConstant.CLASS_DATA, formBean.getModelBilling());
dataMap.put(MapConstant.USER_SESSION_DATA, user);
dataMap.put(MapConstant.ACTION, ActionConstant.SAVE);
service = new ServiceManagerImpl();
resultMap = service.executeRequest(dataMap);
if (resultMap!=null && !resultMap.isEmpty()) {
boolean transactionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS);
if (transactionStatus) {
formBean.setTransactionStatus(transactionStatus);
//need to update the formbean for Billing Id
formBean.updateFormBeanForBillingId();
logger.info("Patient Bill successfully saved (Patient case system ID): " + formBean.getPatientCaseSystemId());//Patient Case System Id
}
}
}
String caseNo = request.getParameter("caseNo");
//generate pdf bill report
bill.generateReport(request, caseNo);
} else {
logger.info("Resultmap is empty...");
}
forwardAction = ActionConstant.SHOW_AJAX_GO_TO_CHILD;
}
} else {
//show main screen
forwardAction = ActionConstant.SHOW_AJAX_MAIN;
}
}
return mapping.findForward(forwardAction);
}
}
|
package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Shape;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BoxView;
import javax.swing.text.ComponentView;
import javax.swing.text.Element;
import javax.swing.text.IconView;
import javax.swing.text.LabelView;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.ParagraphView;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;
import javax.swing.text.View;
import javax.swing.text.ViewFactory;
public class RedSquigglyUnderline
{
public RedSquigglyUnderline()
{
JFrame fr = new JFrame("TEST");
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JEditorPane pane = new JEditorPane();
pane.setEditorKit(new NewEditorKit());
pane.setText("test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");
StyledDocument doc = (StyledDocument) pane.getDocument();
MutableAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setLineSpacing(attr, 5f);
doc.setParagraphAttributes(0, doc.getLength(), attr, false);
JScrollPane sp = new JScrollPane(pane);
fr.getContentPane().add(sp);
fr.setSize(300, 300);
fr.show();
}
public static void main(String[] args)
{
RedSquigglyUnderline test = new RedSquigglyUnderline();
}
}
class NewEditorKit extends StyledEditorKit
{
public ViewFactory getViewFactory()
{
return new NewViewFactory();
}
}
class NewViewFactory implements ViewFactory
{
public View create(Element elem)
{
String kind = elem.getName();
if (kind != null)
{
if (kind.equals(AbstractDocument.ContentElementName))
return new JaggedLabelView(elem);
else if (kind.equals(AbstractDocument.ParagraphElementName))
return new ParagraphView(elem);
else if (kind.equals(AbstractDocument.SectionElementName))
return new BoxView(elem, View.Y_AXIS);
else if (kind.equals(StyleConstants.ComponentElementName))
return new ComponentView(elem);
else if (kind.equals(StyleConstants.IconElementName))
return new IconView(elem);
}
// default to text display
return new LabelView(elem);
}
}
class JaggedLabelView extends LabelView
{
public JaggedLabelView(Element elem)
{
super(elem);
}
public void paint(Graphics g, Shape allocation)
{
super.paint(g, allocation);
paintJaggedLine(g, allocation);
}
public void paintJaggedLine(Graphics g, Shape a)
{
int y = (int) (a.getBounds().getY() + a.getBounds().getHeight());
int x1 = (int) a.getBounds().getX();
int x2 = (int) (a.getBounds().getX() + a.getBounds().getWidth());
Color old = g.getColor();
g.setColor(Color.red);
for (int i = x1; i <= x2; i += 6)
{
g.drawArc(i + 3, y - 3, 3, 3, 0, 180);
g.drawArc(i + 6, y - 3, 3, 3, 180, 181);
}
g.setColor(old);
}
}
|
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
@WebServlet(name = "${Class_Name}Servlet", urlPatterns = "/${Class_Name}Servlet")
public class ${Class_Name}Servlet extends BaseServlet {
private void writerDate(HttpServletResponse res, String json) {
try (PrintWriter writer = res.getWriter()) {
writer.write(json);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.leverx.animals.repository;
import com.leverx.animals.dao.UserDao;
import com.leverx.animals.dao.UserDaoImpl;
import com.leverx.animals.entity.User;
import java.util.List;
import java.util.Optional;
public class UserRepositoryImpl implements UserRepository {
private final UserDao userDao;
public UserRepositoryImpl() {
userDao = new UserDaoImpl();
}
@Override
public Optional<User> getById(long id) {
return userDao.getById(id);
}
@Override
public User create(User user) {
return userDao.create(user);
}
@Override
public List<User> getAll() {
return userDao.getAll();
}
@Override
public User update(User user) {
return userDao.update(user);
}
@Override
public void deleteById(long id) {
userDao.deleteById(id);
}
}
|
package com.bigpotato.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* Created by hjy on 3/5/16.
*/
public class AppCommonUtil {
/**
* 构造给客户端的json字符串
* @param code
* @param msg
* @param data
* @return
*/
public static JSONObject constructResponse(int code, String msg, Object data) {
JSONObject jo = new JSONObject();
jo.put("code", code);
jo.put("msg", msg);
jo.put("data", JSON.toJSON(data));
return jo;
}
}
|
package Lec_07_Nested_Loops;
import java.util.Scanner;
public class Lab_07_08_MagicNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете цяло число за намиране на всички магически числа: ");
int inputNum = Integer.parseInt(scanner.nextLine());
for (int num1 = 1; num1 <= 9 ; num1++) {
for (int num2 = 1; num2 <= 9 ; num2++) {
for (int num3 = 1; num3 <= 9; num3++) {
for (int num4 = 1; num4 <= 9; num4++) {
for (int num5 = 1; num5 <= 9; num5++) {
for (int num6 = 1; num6 <= 9; num6++) {
int result = num1 * num2 * num3 * num4 * num5 * num6;
if (result == inputNum){
System.out.printf("%d%d%d%d%d%d ", num1, num2, num3, num4, num5, num6);
}
}
}
}
}
}
}
}
}
|
package com.sum.flowable.service;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.Firestore;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;
@Service
public class FirebaseService {
@Value("${firebase.key.file}")
private String firebaseKeyFile;
private Firestore db = null;
private void initialize() throws FirebaseServiceException {
try {
InputStream serviceAccount = new FileInputStream(this.firebaseKeyFile);
GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
FirebaseOptions options = new FirebaseOptions.Builder().setCredentials(credentials).build();
FirebaseApp.initializeApp(options);
this.db = FirestoreClient.getFirestore();
} catch (IOException e) {
throw new FirebaseServiceException(e);
}
}
public Firestore getFirestore() throws FirebaseServiceException {
if (this.db == null) {
this.initialize();
}
return this.db;
}
}
|
package ltd.getman.testjobproject.domain.models.sort;
import java.util.List;
import ltd.getman.testjobproject.domain.models.mechanizm.Mechanizm;
/**
* Created by Artem Getman on 18.05.17.
* a.e.getman@gmail.com
*/
public class InsertSort extends BaseSortedClass {
public InsertSort() {
super(TYPE.INSERT);
}
@Override public <T extends Mechanizm> List<T> sort(List<T> mechanizmList) {
T temp;
int j;
for (int i = 0; i < mechanizmList.size() - 1; i++) {
if (mechanizmList.get(i).compareTo(mechanizmList.get(i + 1)) > 0) {
temp = mechanizmList.get(i + 1);
mechanizmList.set(i + 1, mechanizmList.get(i));
j = i;
while (j > 0 && 0 < temp.compareTo(mechanizmList.get(j - 1))) {
mechanizmList.set(j, mechanizmList.get(j - 1));
j--;
}
mechanizmList.set(j, temp);
}
}
return mechanizmList;
}
}
|
package com.worldchip.bbp.ect.adapter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.worldchip.bbp.ect.R;
import com.worldchip.bbp.ect.entity.MusicInfo;
import com.worldchip.bbp.ect.entity.MusicInfo.MusicState;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MediaShareMusicAdapter extends BaseAdapter {
static class Holder {
private TextView mMusicValue;
private ImageView mMusicPlay;
private TextView mMusicTime;
private LinearLayout mMusicBg;
}
private List<MusicInfo> mDataList;
private Context mContext;
private List<MusicInfo> shareList = new ArrayList<MusicInfo>();
private String data = "";
private int mSelection = -1;
private Typeface mTypeface;
/**
* 获取所有要分享的音乐
*/
public List<MusicInfo> getShareMusicData() {
return shareList;
}
public MediaShareMusicAdapter(Activity context, List<MusicInfo> list) {
this.mContext = context;
mDataList = list;
mTypeface = Typeface.createFromAsset(mContext.getAssets(), "DroidSans-Bold.ttf");
}
@Override
public int getCount() {
int count = 0;
if (mDataList != null) {
count = mDataList.size();
}
return count;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = View.inflate(mContext, R.layout.share_musicplay_item, null);
holder.mMusicValue = (TextView) convertView
.findViewById(R.id.music_value);
holder.mMusicTime=(TextView)convertView.findViewById(R.id.music_time);
holder.mMusicPlay=(ImageView)convertView.findViewById(R.id.playermusic);
holder.mMusicBg=(LinearLayout)convertView.findViewById(R.id.linerlayout_music_bg);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
final MusicInfo music = mDataList.get(position);
if (mSelection == position) {
holder.mMusicBg.setBackgroundResource(R.drawable.musictiao_bg_checked);
} else {
holder.mMusicBg.setBackgroundResource(R.drawable.musictiao_bg);
}
MusicState state = music.getState();
if (state == MusicState.STOP || state == MusicState.PAUSE) {
holder.mMusicPlay.setImageResource(R.drawable.music_play);
holder.mMusicBg.setBackgroundResource(R.drawable.musictiao_bg);
} else {
holder.mMusicPlay.setImageResource(R.drawable.music_pause);
holder.mMusicBg.setBackgroundResource(R.drawable.musictiao_bg_checked);
}
String suffix = getExtensionName(music.getData());
holder.mMusicValue.setTypeface(mTypeface);
holder.mMusicTime.setTypeface(mTypeface);
long minutes = (Integer.parseInt(music.getDuration()) % (1000 * 60 * 60)) / (1000 * 60);
long seconds = (Integer.parseInt(music.getDuration()) % (1000 * 60)) / 1000;
holder.mMusicValue.setText(music.getTitle() + "." + suffix);
holder.mMusicTime.setText("0"+String.valueOf(minutes)+" : "+String.valueOf(seconds));
holder.mMusicBg.setSelected(true);
return convertView;
}
/**
* 获取指定文件的后缀名
*
* @param filename
* @return
*/
private static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* 删除图片
*/
public void delItem(MusicInfo musicInfo) {
mDataList.remove(musicInfo);
notifyDataSetChanged();
}
/**
* 删除列表项
*/
public void delItem(String data) {
Iterator<MusicInfo> ite = mDataList.iterator();
while (ite.hasNext()) {
if (ite.next().getData().equals(data)) {
ite.remove();
notifyDataSetChanged();
}
}
}
/**
* 选中列表项
*/
public void selectItem(String data) {
Iterator<MusicInfo> ite = mDataList.iterator();
while (ite.hasNext()) {
MusicInfo info = ite.next();
if (info.getData().equals(data)) {
info.isSelected = false;
notifyDataSetChanged();
break;
}
}
}
/**
* 获取点击的音乐路径
*/
public String getMusicData() {
return data;
}
/**
* 清除
*/
public void clearShareMusicList() {
if (shareList != null) {
shareList.clear();
}
}
public void setDatas(List<MusicInfo> dataList) {
mDataList = dataList;
}
public List<MusicInfo> getDatas() {
return mDataList;
}
public int getSelection() {
return mSelection;
}
public void setSelection(int mSelection) {
this.mSelection = mSelection;
}
public void onChangeMusicData(int position, MusicState musicState) {
if (mDataList != null && !mDataList.isEmpty()) {
for (int i=0; i<mDataList.size(); i++) {
MusicInfo musicInfo = mDataList.get(i);
if (i == position) {
musicInfo.setState(musicState);
} else {
musicInfo.setState(MusicState.STOP);
}
}
}
}
} |
package com.alderson.zoo;
public abstract class Mammal extends Animal {
public Mammal(String species, String gender) {
super(species, gender);
}
} |
package com.deepakm.algo.backtrack.nqueen;
/**
* Created by dmarathe on 1/22/16.
*/
public class NQueenProblem {
int board[][];
int N = 0;
public NQueenProblem(int board[][]) {
if (board == null) {
throw new IllegalArgumentException("board cannot be null");
}
if (board.length == 0) {
throw new IllegalArgumentException("board size == 0");
}
if (board[0].length == 0) {
throw new IllegalArgumentException("board size == 0");
}
if (board.length != board[0].length) {
throw new IllegalArgumentException("malformed board");
}
this.board = board;
this.N = this.board.length;
}
public boolean isSafe(int row, int col) {
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i] == 1)
return false;
/* Check upper diagonal on left side */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;
/* Check lower diagonal on left side */
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j] == 1)
return false;
return true;
}
public boolean solve(int column) {
if (column == this.N) {
return true;
}
for (int i = 0; i < this.N; i++) {
if (isSafe(i, column)) {
board[i][column] = 1;
if (solve(column + 1)) {
return true;
}
board[i][column] = 0;
}
}
return false;
}
public void printSolution() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
System.out.print(board[i][j] + " , ");
}
System.out.println();
}
}
public static void main(String[] args) {
int board[][] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
};
NQueenProblem problem = new NQueenProblem(board);
if (problem.solve(0)) {
problem.printSolution();
}
}
}
|
package com.zenwerx.findierock.data;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class FindieDbAdapter {
private static final String TAG = "findierock.FindieDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "data";
private static final String CREATE_TABLE_ARTISTS = "create table artists( _id integer primary key, name text, bio text, website text, smallimage text, largeimage text, fetchedalbums integer )";
private static final String CREATE_TABLE_EVENTARTISTS = "create table eventartists( eventid integer, artistid integer, primary key( eventid, artistid ) )";
private static final String CREATE_TABLE_EVENTS = "create table events ( _id integer primary key, latitude real, longitude real, name text, description text, startTime integer, ageOfMajority integer, venueId integer );";
private static final String CREATE_TABLE_OPERATIONS = "create table operations ( _id integer primary key autoincrement, status integer );";
private static final String CREATE_TABLE_STATUS = "create table status ( _id integer primary key autoincrement, lastUpdate text, lastLatitude real, lastLongitude real );";
private static final String CREATE_TABLE_VENUES = "create table venues ( _id integer primary key, name text, address text, address2 text, city text, province text, country text, website text, latitude real, longitude real, smallimage text, largeimage text)";
private static final String CREATE_TABLE_ALBUMS = "create table albums ( _id integer primary key, artistid integer, name text, moreurl text, smallimage text, largeimage text, releasedate integer, lastfmid text )";
private static final String CREATE_TABLE_FAVOURITES = "create table favourites ( favtype integer, favid integer, primary key( favtype, favid ) )";
private static final String CREATE_TABLE_ALBUMTRACKS = "create table albumtracks ( _id integer primary key, albumid integer, name text, length integer, lastfmid text)";
private static final String UPDATE_TABLE_EVENTS_0 = "alter table events add venueId integer";
private static final String UPDATE_TABLE_VENUES_0 = "alter table venues add latitude real";
private static final String UPDATE_TABLE_VENUES_1 = "alter table venues add longitude real";
private static final String UPDATE_TABLE_VENUES_2 = "alter table venues add fav integer";
private static final String UPDATE_TABLE_VENUES_3 = "alter table venues add smallimage text";
private static final String UPDATE_TABLE_VENUES_4 = "alter table venues add largeimage text";
private static final String UPDATE_TABLE_ARTISTS_0 = "alter table artists add fav integer";
private static final String UPDATE_TABLE_ARTISTS_1 = "alter table artists add smallimage text";
private static final String UPDATE_TABLE_ARTISTS_2 = "alter table artists add largeimage text";
private static final String UPDATE_TABLE_ARTISTS_3 = "alter table artists add fetchedalbums integer";
private static final String UPDATE_TABLE_STATUS_0 = "alter table status add lastLatitude real";
private static final String UPDATE_TABLE_STATUS_1 = "alter table status add lastLongitude real";
private static final String UPDATE_TABLE_ALBUMS_0 = "alter table albums add releasedate integer";
private static final String UPDATE_TABLE_ALBUMS_1 = "alter table albums add lastfmid text";
private static final int DATABASE_VERSION = 18;
private final Context mContext;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_EVENTS);
db.execSQL(CREATE_TABLE_OPERATIONS);
db.execSQL(CREATE_TABLE_STATUS);
db.execSQL(CREATE_TABLE_ARTISTS);
db.execSQL(CREATE_TABLE_EVENTARTISTS);
db.execSQL(CREATE_TABLE_VENUES);
db.execSQL(CREATE_TABLE_ALBUMS);
db.execSQL(CREATE_TABLE_FAVOURITES);
db.execSQL(CREATE_TABLE_ALBUMTRACKS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
if (oldVersion < 7)
{
db.execSQL(CREATE_TABLE_ARTISTS);
db.execSQL(CREATE_TABLE_EVENTARTISTS);
}
if (oldVersion < 9)
{
db.execSQL(CREATE_TABLE_VENUES);
db.execSQL(UPDATE_TABLE_EVENTS_0);
}
if (oldVersion < 10)
{
db.execSQL(UPDATE_TABLE_VENUES_0);
db.execSQL(UPDATE_TABLE_VENUES_1);
}
if (oldVersion < 11)
{
db.execSQL(UPDATE_TABLE_VENUES_2);
db.execSQL(UPDATE_TABLE_ARTISTS_0);
}
if (oldVersion < 14)
{
db.execSQL(UPDATE_TABLE_STATUS_0);
db.execSQL(UPDATE_TABLE_STATUS_1);
}
if (oldVersion < 15)
{
db.execSQL(UPDATE_TABLE_VENUES_3);
db.execSQL(UPDATE_TABLE_VENUES_4);
db.execSQL(UPDATE_TABLE_ARTISTS_1);
db.execSQL(UPDATE_TABLE_ARTISTS_2);
db.execSQL(UPDATE_TABLE_ARTISTS_3);
db.execSQL(CREATE_TABLE_ALBUMS);
}
if (oldVersion < 16)
{
db.execSQL(UPDATE_TABLE_ALBUMS_0);
}
if (oldVersion < 17)
{
db.execSQL(CREATE_TABLE_FAVOURITES);
}
if (oldVersion < 18)
{
db.execSQL(CREATE_TABLE_ALBUMTRACKS);
db.execSQL(UPDATE_TABLE_ALBUMS_1);
}
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param mContext the Context within which to work
*/
public FindieDbAdapter(Context context) {
this.mContext = context;
}
/**
* Open the findie database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public FindieDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public EventsHelper getEventsHelper()
{
return new EventsHelper(mDb);
}
public ArtistHelper getArtistHelper()
{
return new ArtistHelper(mDb);
}
public VenueHelper getVenueHelper()
{
return new VenueHelper(mDb);
}
public StatusHelper getStatusHelper()
{
return new StatusHelper(mDb);
}
public AlbumHelper getAlbumHelper()
{
return new AlbumHelper(mDb);
}
public FavouriteHelper getFavouriteHelper() {
return new FavouriteHelper(mDb);
}
public AlbumTrackHelper getAlbumTrackHelper() {
return new AlbumTrackHelper(mDb);
}
}
|
package us.gibb.dev.gwt.view;
public interface View<V> {
V getImpl();
}
|
package ch8;
public class NewExceptionTest {
public static void main(String[] args) {
try {
startInstall();
copyFiles();
} catch (SpaceException e) {
System.out.println("에러 메세지 : "+e.getMessage());
e.printStackTrace();
System.out.println("공간을 확보한 후에 다시 설치하시기 바랍니다.");
} catch(MemoryException me) {
System.out.println("에러 메세지 : "+me.getMessage());
me.printStackTrace();
System.gc(); //Garbage Collection을 수행하여 메모리를 늘려준다.
System.out.println("다시 설치를 시도하세요.");
} finally {
deleteTempFiles();
}
}
static void startInstall() throws SpaceException, MemoryException {
//startInstall을 수행하는 동안 발생할 수 있으며 실행결과에 따라 예외의 종류다 달라지게 코딩
if(!enoughSpace())
throw new SpaceException("설치할 공간이 부족합니다.");
if(!enoughMemory())
throw new MemoryException("메모리가 부족합니다.");
}
static void copyFiles() {/*파일 복사 코드*/}
static void deleteTempFiles() {/*임시파일 삭제 코드*/}
static boolean enoughSpace() {
//설치하는데 필요한 공간이 있는지 확인하는 코드
return true;
}
static boolean enoughMemory() {
//설치하는데 필요한 메모리 공간이 있는지 확인하는 코드
return false;
}
}
//설치에 필요한 공간 예외 처리
class SpaceException extends Exception{
SpaceException(String msg) {
super(msg);
}
}
//설치에 필요한 메모리공간 예외 처리
class MemoryException extends Exception{
MemoryException(String msg){
super(msg);
}
}
|
package com.lovers.java.domain;
import java.util.Date;
public class UserPhoto {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.photo_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private Integer photoId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.album_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private Integer albumId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.file_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private Integer fileId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.photo_position
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private String photoPosition;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.photo_describe
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private String photoDescribe;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.upload_time
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private Date uploadTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.user_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private Integer userId;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.for_module
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private String forModule;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_photo.photo_name
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
private String photoName;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.photo_id
*
* @return the value of user_photo.photo_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public Integer getPhotoId() {
return photoId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.photo_id
*
* @param photoId the value for user_photo.photo_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setPhotoId(Integer photoId) {
this.photoId = photoId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.album_id
*
* @return the value of user_photo.album_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public Integer getAlbumId() {
return albumId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.album_id
*
* @param albumId the value for user_photo.album_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setAlbumId(Integer albumId) {
this.albumId = albumId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.file_id
*
* @return the value of user_photo.file_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public Integer getFileId() {
return fileId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.file_id
*
* @param fileId the value for user_photo.file_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setFileId(Integer fileId) {
this.fileId = fileId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.photo_position
*
* @return the value of user_photo.photo_position
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public String getPhotoPosition() {
return photoPosition;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.photo_position
*
* @param photoPosition the value for user_photo.photo_position
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setPhotoPosition(String photoPosition) {
this.photoPosition = photoPosition == null ? null : photoPosition.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.photo_describe
*
* @return the value of user_photo.photo_describe
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public String getPhotoDescribe() {
return photoDescribe;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.photo_describe
*
* @param photoDescribe the value for user_photo.photo_describe
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setPhotoDescribe(String photoDescribe) {
this.photoDescribe = photoDescribe == null ? null : photoDescribe.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.upload_time
*
* @return the value of user_photo.upload_time
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public Date getUploadTime() {
return uploadTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.upload_time
*
* @param uploadTime the value for user_photo.upload_time
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setUploadTime(Date uploadTime) {
this.uploadTime = uploadTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.user_id
*
* @return the value of user_photo.user_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public Integer getUserId() {
return userId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.user_id
*
* @param userId the value for user_photo.user_id
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setUserId(Integer userId) {
this.userId = userId;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.for_module
*
* @return the value of user_photo.for_module
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public String getForModule() {
return forModule;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.for_module
*
* @param forModule the value for user_photo.for_module
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setForModule(String forModule) {
this.forModule = forModule == null ? null : forModule.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_photo.photo_name
*
* @return the value of user_photo.photo_name
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public String getPhotoName() {
return photoName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_photo.photo_name
*
* @param photoName the value for user_photo.photo_name
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
public void setPhotoName(String photoName) {
this.photoName = photoName == null ? null : photoName.trim();
}
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tfar.daoImpl;
import com.tfar.dao.AndrogeneDao;
import com.tfar.entity.Androgene;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
/**
*
* @author hatem
*/
public class AndrogeneDaoImpl implements AndrogeneDao{
private Androgene newAndrogene;
private Androgene androgene;
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
@Autowired
private SessionFactory sessionFactory= configuration.buildSessionFactory(builder.build());
@Override
public void add(Androgene newAndrogene)
{
Session session = sessionFactory.openSession();
try
{
// begin a transaction
session.beginTransaction();
session.saveOrUpdate(newAndrogene);
session.flush();
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
@Override
public void update(Androgene androgene)
{
Session session = sessionFactory.openSession();
try
{
// begin a transaction
session.beginTransaction();
session.update(androgene);
session.flush();
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
@Override
public List<Androgene> getAllAndrogene() {
@SuppressWarnings("unchecked")
List <Androgene> DaoAllAndrogene = null;
Session session = sessionFactory.openSession();
try
{
session.beginTransaction();
DaoAllAndrogene = (List<Androgene>) session.createCriteria(Androgene.class).list();
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
return DaoAllAndrogene;
}
@Override
public List<Androgene> getListAndrogeneParnDossier(String nDossier) {
@SuppressWarnings("unchecked")
List <Androgene> DaoAllAndrogene = new ArrayList<Androgene>();
Session session = sessionFactory.openSession();
try
{
System.out.println("DAO ------ getListAndrogeneParnDossier .........");
session.beginTransaction();
DetachedCriteria query = DetachedCriteria.forClass(Androgene.class)
.add( Restrictions.eq("androgenePK.nDossierPa", nDossier) );
System.out.println("query:"+query.toString());
DaoAllAndrogene = query.getExecutableCriteria(session).list();
//freres.add(F);
System.out.println("DaoAndrogeneParNDossier:"+DaoAllAndrogene.toString());
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
return DaoAllAndrogene;
}
@Override
public void delete(Androgene androgene) {
Session session = sessionFactory.openSession();
try
{
session.beginTransaction();
session.delete(androgene);
session.getTransaction().commit();
}
catch (Exception e)
{
e.printStackTrace();
session.getTransaction().rollback();
}
session.close();
}
}
|
package two.constructors;
/**
* @author Tedikova O.
* @version 1.0
*/
public class B extends A {
public Logger field = new Logger("B.field");
public static Logger CONSTANT = new Logger("B.CONSTANT");
{
System.out.println("B.block");
}
{
System.out.println("B.anotherBlock ");
}
static {
System.out.println("B.block - static");
}
public B() {
System.out.println("B.constructor");
}
public void method() {
super.method();
System.out.println("B.method");
}
}
|
package com.talmir.mickinet.helpers;
import android.content.Context;
import android.net.wifi.p2p.WifiP2pManager;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static android.os.Looper.getMainLooper;
/**
* A class helps to change name (WifiDirect name, Bluetooth name)
* of the device. Since, Kotlin implementation of the following
* lines is quite possible. However, during Kotlin code execution
* I got a cryptic error. To reduce searching time for that error
* and also to keep the {{@link com.talmir.mickinet.screens.main.fragments.DeviceDetailFragment}}
* class a bit more clean, I decided to keep that codes in Java...
*
* @author mirjalal
* @since Jul 30, 2018
*/
public final class DeviceNameChangerUtil {
/**
* Changes device name using Java Reflection API explicitly.
* Because of, Android have not gave any option to achieve
* this functionality, I used this method to achieve it.
*
* @param activity current activity object
* @param newName new device name to be set
* @return `true` if newName was set successfully, `false` otherwise.
*/
public static boolean changeDeviceName(@NonNull FragmentActivity activity, @NonNull String newName) {
final WifiP2pManager[] mManager = new WifiP2pManager[1];
WifiP2pManager.Channel channel;
try {
mManager[0] = (WifiP2pManager) activity.getSystemService(Context.WIFI_P2P_SERVICE);
assert mManager[0] != null;
channel = mManager[0].initialize(
activity,
getMainLooper(),
() -> {}
);
Class[] paramTypes = new Class[3];
paramTypes[0] = WifiP2pManager.Channel.class;
paramTypes[1] = String.class;
paramTypes[2] = WifiP2pManager.ActionListener.class;
Method setDeviceName = mManager[0].getClass().getMethod("setDeviceName", paramTypes);
setDeviceName.setAccessible(true);
Object[] argList = new Object[3];
argList[0] = channel;
argList[1] = newName;
argList[2] = new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
// nothing to do here
}
@Override
public void onFailure(int reason) {
// nothing to do in this method
}
};
setDeviceName.invoke(mManager[0], argList);
return true;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
return false;
}
}
}
|
package de.minestar.syncchest.core;
import org.bukkit.Location;
import org.bukkit.plugin.PluginManager;
import de.minestar.syncchest.commands.AddCommand;
import de.minestar.syncchest.commands.InfoCommand;
import de.minestar.syncchest.commands.RemoveCommand;
import de.minestar.syncchest.commands.SyncChestCommand;
import de.minestar.syncchest.database.DatabaseHandler;
import de.minestar.syncchest.library.AbstractCore;
import de.minestar.syncchest.library.CommandList;
import de.minestar.syncchest.library.ConsoleUtils;
import de.minestar.syncchest.listener.ActionListener;
import de.minestar.syncchest.listener.InventoryListener;
import de.minestar.syncchest.units.DataNode;
import de.minestar.syncchest.utils.BlockVector;
import de.minestar.syncchest.utils.ChestUtils;
import de.minestar.syncchest.utils.Permissions;
public class Core extends AbstractCore {
public static final String NAME = "SyncChests";
private static Core INSTANCE = null;
/**
* Manager
*/
private DataNode dataNode;
private DatabaseHandler databaseManager;
/**
* Listener
*/
private ActionListener actionListener;
private InventoryListener inventoryListener;
public Core() {
this(NAME);
}
public Core(String name) {
super(NAME);
INSTANCE = this;
}
@Override
protected boolean createManager() {
this.databaseManager = new DatabaseHandler("SyncChests", this.getDataFolder());
this.dataNode = this.databaseManager.loadSyncChests();
return true;
}
@Override
protected boolean createListener() {
this.actionListener = new ActionListener(this.dataNode, this.databaseManager);
this.inventoryListener = new InventoryListener(this.dataNode);
return true;
}
@Override
protected boolean createCommands() {
//@formatter:off;
this.cmdList = new CommandList(
new SyncChestCommand ("/sync", "", "",
new AddCommand ("add", "<NodeName>", Permissions.CHEST_ADD, this.actionListener),
new RemoveCommand ("remove", "", Permissions.CHEST_REMOVE, this.actionListener),
new InfoCommand ("info", "", Permissions.CHEST_INFO, this.actionListener)
)
);
// @formatter: on;
return true;
}
@Override
protected boolean commonDisable() {
ConsoleUtils.printInfo(Core.NAME, "Shutting down...");
if(!this.dataNode.doShutDown()) {
ConsoleUtils.printError(Core.NAME, "Something went wrong!");
}
// close SQLite-Connection
if(this.databaseManager.hasConnection()) {
this.databaseManager.closeConnection();
}
return true;
}
@Override
protected boolean commonEnable() {
this.dataNode.doStartUp();
return this.dataNode != null;
}
@Override
protected boolean registerEvents(PluginManager pm) {
pm.registerEvents(this.actionListener, this);
pm.registerEvents(this.inventoryListener, this);
return true;
}
public static Core getInstance() {
return INSTANCE;
}
public boolean isSyncChest(Location location) {
return (ChestUtils.getSyncChest(this.dataNode, new BlockVector(location)) != null);
}
}
|
package com.SearchHouse.dao.impl;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.SearchHouse.dao.HouseDao;
import com.SearchHouse.pojo.House;
@Repository
public class HouseImpl implements HouseDao{
@Autowired
SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
@Override
public void addHouse(House house) {
// TODO Auto-generated method stub
Session session=getSession();
session.save(house);
}
@Override
public void updateHouse(House house) {
// TODO Auto-generated method stub
Session session=getSession();
session.update(house);
}
@Override
public void deleteHouse(int houseId) {
// TODO Auto-generated method stub
Session session=getSession();
House house=(House) session.get(House.class, houseId);
session.delete(house);
}
@Override
public House getHouseById(int houseId) {
Session session=getSession();
House house=(House) session.get(House.class, houseId);
// TODO Auto-generated method stub
return house;
}
@Override
public List<House> queryHouse() {
Session session=getSession();
Query query=session.createQuery("from House");
List<House> houses=query.list();
System.out.println("houses:"+houses);
// TODO Auto-generated method stub
return houses;
}
}
|
package com.aps.arobot.sserver;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.util.Log;
import com.jayway.android.robotium.common.message.EventInvokeMethodMessage;
import com.jayway.android.robotium.common.message.EventReturnValueMessage;
import com.jayway.android.robotium.common.message.Message;
import com.jayway.android.robotium.common.message.MessageFactory;
import com.jayway.android.robotium.common.message.UnsupportedMessage;
import com.jayway.android.robotium.common.util.TypeUtils;
import com.jayway.android.robotium.solo.Solo;
public class MessageWorker {
private static final String TAG = "MessageWorker";
private Solo mSolo;
private Activity mActiviy;
private Instrumentation mInstrumentation;
private Intent mIntent;
private static Map<String, Object> referencedObjects;
public MessageWorker() {
// stores weak reference of an object
referencedObjects = Collections.synchronizedMap(new HashMap<String, Object>());
}
public void setConfiguration(Solo solo, Activity activity, Instrumentation inst, Intent intent) {
mSolo = solo;
mActiviy = activity;
mInstrumentation = inst;
mIntent = intent;
}
private void checkConfiguration() {
if(mSolo == null || mActiviy == null || mInstrumentation == null || mIntent == null) {
throw new IllegalArgumentException("Instrumentation missing configuration");
}
}
public Message receivedEventInvokeMethodMessage(EventInvokeMethodMessage mMessage) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
// a event message contains object and method was invoked
EventInvokeMethodMessage eventMsg = mMessage;
Log.d(TAG, (eventMsg).getMessageHeader());
Method receivedMethod = eventMsg.getMethodReceived();
// Log.d(TAG, "Calling on method:" + receivedMethod.toString());
Class<?> returnType = receivedMethod.getReturnType();
// Log.d(TAG, "Return type:" + returnType.getName());
// check if this has a List Collection interface and
boolean hasListInterface = TypeUtils.hasListInterfaceType(returnType);
boolean hasCollectionInterface = TypeUtils.hasCollectionInterfaceType(returnType);
if (eventMsg.getTargetObjectClass().getName().equals(
Solo.class.getName())) {
Log.d(TAG, "calling on Solo base");
try {
Object returnValue = receivedMethod.invoke(mSolo, eventMsg
.getParameters());
Log.d(TAG, "solo.invoked.");
if (returnType.equals(void.class)) {
// send success
Message responseMsg = MessageFactory
.createSuccessMessage();
return responseMessage(responseMsg, mMessage);
} else {
// response to non void return type
return responseToNonVoidReturnType(mMessage, hasListInterface, hasCollectionInterface, returnValue);
}
} catch (Exception ex){
Message responseMsg = MessageFactory.createExceptionMessage(ex, "Error invoking Solo method");
return responseMessage(responseMsg, mMessage);
}
} else {
Log.d(TAG, "Calling on non-solo object");
String objID = eventMsg.getTargetObjectId();
Object realObj = null;
synchronized (referencedObjects) {
Log.d(TAG, "referencdObjects size: " + referencedObjects.size());
Log.d(TAG, "Need find: " + objID);
Log.d(TAG, "Has: " + referencedObjects.keySet().toString());
if(referencedObjects.containsKey(objID)) {
realObj = referencedObjects.get(objID);
}
}
if(realObj != null) {
// check parameters: they could be remote references.
Class<?>[] tmpTypes = eventMsg.getParameterTypes();
Object[] tmpParams = eventMsg.getParameters();
Object[] checkedParams = new Object[tmpParams.length];
for(int i = 0; i < tmpTypes.length; i++) {
if(TypeUtils.isPrimitive(tmpTypes[i]) || tmpTypes[i].equals(Class.class)) {
checkedParams[i] = tmpParams[i];
} else {
String objRemoteID = tmpParams[i].toString();
Object refObj = referencedObjects.get(objRemoteID);
Log.d(TAG, "Object in parameter found");
if(refObj != null)
checkedParams[i] = refObj;
else
throw new UnsupportedOperationException(
"This may not be a remote object or the server lost reference.");
}
}
Log.d(TAG, "Found remote object in hashmap");
Object returnValue = eventMsg.getMethodReceived().invoke(realObj, checkedParams);
Log.d(TAG, "Return value:" + returnValue.toString());
if(eventMsg.getMethodReceived().getReturnType().getClass().equals(void.class)) {
// no need to return value
// send success
Message responseMsg = MessageFactory
.createSuccessMessage();
return responseMessage(responseMsg, mMessage);
} else {
// response to non void return type request
return responseToNonVoidReturnType(mMessage, hasListInterface, hasCollectionInterface, returnValue);
}
} else {
Message responseMsg = MessageFactory.createFailureMessage("No Object found for: " + objID);
return responseMessage(responseMsg, mMessage);
}
}
}
private Message responseToNonVoidReturnType(EventInvokeMethodMessage mMessage, boolean hasListInterface, boolean hasCollectionInterface, Object returnValue) {
Class<?> returnType = mMessage.getMethodReceived().getReturnType();
// get object reference
if (returnType.isPrimitive() || returnType.equals(String.class)) {
// construct return value message, copy the original
// message ID
// and write to the client channel
Message responseMsg = new EventReturnValueMessage(
returnType, void.class,
new Object[] { returnValue });
return responseMessage(responseMsg, mMessage);
} else if (!returnType.isPrimitive()
&& !hasListInterface && !hasCollectionInterface) {
String key = UUID.randomUUID().toString();
// store the object in WeakHashMap for later
// use
synchronized (referencedObjects) {
referencedObjects.put(key, returnValue);
}
Message responseMsg = new EventReturnValueMessage(
returnType, void.class,
new Object[] { key });
return responseMessage(responseMsg, mMessage);
} else if (hasListInterface) {
// if the top root is list, then cast it as a list
// get the first element in the list to find out the
// class type
Object element = ((List<?>) returnValue).get(0);
Class<?> innerClassType = element.getClass();
// if the inner generic class is not primitive, we
// have to constructs an object reference
// and store it in the WeakHashMap
Message responseMsg;
if (!innerClassType.isPrimitive()) {
List<String> shouldReturnValue = new ArrayList<String>();
String key;
for (Object ele : (List<?>) returnValue) {
// use UUID as the object ID
key = String.valueOf(UUID.randomUUID());
shouldReturnValue.add(key);
// store the object in WeakHashMap for later
// use
synchronized (referencedObjects) {
referencedObjects.put(key, ele);
}
Log.d(TAG, "Added new, now referencdObjects size: " + referencedObjects.size());
Log.d(TAG, "Has: " + referencedObjects.keySet().toString());
}
responseMsg = new EventReturnValueMessage(
returnType, innerClassType,
shouldReturnValue.toArray());
} else {
responseMsg = new EventReturnValueMessage(
returnType, innerClassType,
((List<?>) returnValue).toArray());
}
return responseMessage(responseMsg, mMessage);
} else {
// response an unsupported message
Message responseMsg = new UnsupportedMessage(
"Returned value only can be List, primitives and other non-collection objects.");
return responseMessage(responseMsg, mMessage);
}
}
/**
* Returns a Message for given message JSONString
* @param msgString String message in JSON String
*/
public Message parseMessage(String msgString) {
Message mMessage = null;
try {
Log.d(TAG+":Parsing", msgString);
mMessage = MessageFactory.parseMessageString(msgString);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
Log.d(TAG, "Receiving MSG: " + mMessage.toString());
return mMessage;
}
/**
* Start the current target Intent activity
*/
public void startTargetIntent() {
checkConfiguration();
mInstrumentation.startActivitySync(mIntent);
}
public Message responseMessage(Message responseMsg, Message incomingMsg) {
responseMsg.setMessageId(incomingMsg.getMessageId());
Log.d(TAG, "Server replied message");
Log.d(TAG, "MessageType: " + responseMsg.getMessageHeader());
Log.d(TAG, "MessageType: " + responseMsg.toString());
return responseMsg;
}
}
|
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.mod.loan.Application;
//import com.mod.loan.util.qjldUtil.DecisionHelper;
//import com.mod.loan.common.message.OrderPayMessage;
//import com.mod.loan.common.message.RiskAuditMessage;
//import com.mod.loan.config.Constant;
//import com.mod.loan.config.qjld.QjldConfig;
//import com.mod.loan.config.rabbitmq.RabbitConst;
//import com.mod.loan.model.DTO.*;
//import com.mod.loan.util.ConstantUtils;
//import com.mod.loan.util.RsaCodingUtil;
//import com.mod.loan.util.RsaReadUtil;
//import com.mod.loan.util.rongze.RongZeRequestUtil;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
//import lombok.extern.slf4j.Slf4j;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//
//import java.util.HashMap;
//import java.util.Map;
//
///**
// * @author lijing
// * @date 2018/1/12 0012.
// */
//@Slf4j
//@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest(classes = Application.class)
//public class DecisionTest {
// public static final String CHAR_SET = "UTF-8";
// @Autowired
// private DecisionHelper decisionHelper;
// @Autowired
// private QjldConfig qjldConfig;
//
// @Autowired
// private RabbitTemplate rabbitTemplate;
//
// @Test
// public void SyncTest() {
// DecisionBaseReqDTO decisionReqDTO = new DecisionBaseReqDTO();
// decisionReqDTO.setMember_id(qjldConfig.getQjldMemberId());
// decisionReqDTO.setTerminal_id(qjldConfig.getQjldTerminalId());
// decisionReqDTO.setRes_encrypt(Boolean.FALSE);
// decisionReqDTO.setTrans_id("TEST" + System.currentTimeMillis());
// String dataContent = getDataContent();
// decisionReqDTO.setData_content(dataContent);
// DecisionBaseResDTO decision = decisionHelper.syncDecision(decisionReqDTO);
// DecisionResDetailDTO publicKey = decision.getData_content();
// log.info("决策执行完成,响应信息:{}", publicKey);
// }
//
//
//// @Test
//// public void NoSyncTest() {
//// DecisionBaseReqDTO decisionReqDTO = new DecisionBaseReqDTO();
//// decisionReqDTO.setMemberId(qjldConfig.getQjldMemberId());
//// decisionReqDTO.setTerminalId(qjldConfig.getQjldTerminalId());
//// decisionReqDTO.setEncrypt(Boolean.FALSE);
//// decisionReqDTO.setTransId("TEST" + System.currentTimeMillis());
//// String dataContent = getDataContent();
//// decisionReqDTO.setDataContent(dataContent);
//// DecisionBaseResDTO decision = decisionHelper.nosyncDecision(decisionReqDTO);
//// DecisionResDetailDTO publicKey = decision.getDataContent();
//// log.info("决策执行完成,响应信息:{}", publicKey);
//// }
//
// @Test
// public void QueryTest() {
// DecisionReqDTO reqDTO = new DecisionReqDTO();
// reqDTO.setMember_id(qjldConfig.getQjldMemberId());
// reqDTO.setTrans_id("p201904222329294");
// reqDTO.setNeed_details(ConstantUtils.Y_FLAG);
// DecisionResDetailDTO decision = decisionHelper.queryDecision(reqDTO);
// log.info("决策执行完成,响应信息:{}", decision);
// }
//
//
// /***
// * 加密参数请求
// *
// * @return 加密数据
// */
// private String getDataContent() {
//
// DecisionReqDTO reqDTO = new DecisionReqDTO();
// //添加客户基本信息(姓名身份证必填)
// BaseUserDTO userDTO = new BaseUserDTO();
// userDTO.setId_name("杨平");
// userDTO.setId_card("142729196303151633");
// userDTO.setPhone("17096140427");
// userDTO.setBank_card_no("6212260511007212158");
// reqDTO.setBase_user(userDTO);
// //添加商户信息(新颜分配的商户号)
// reqDTO.setMember_id(qjldConfig.getQjldMemberId());
// //添加事件编号(在配置页面配置事件后可以使用事件编号调用到对应事件)
// reqDTO.setDecision_code(qjldConfig.getQjldType());
// //是否返回明细
// reqDTO.setNeed_details("Y");
// //订单号(32位唯一字符串)
// reqDTO.setTrans_id("TEST" + System.currentTimeMillis());
// //添加自定义标签信息(该信息可以是map也可以是对象只要满足对应的json格式就可以)
// //没有自定义标签的可以不传这个参数
// reqDTO.setNotify_url("www.baidu.com");
// Map<String, Object> customerParams = new HashMap<>();
// customerParams.put("sex", "男");
// reqDTO.setCustom_params(customerParams);
// ObjectMapper objectMapper = new ObjectMapper();
// String jsonData = null;
// try {
// jsonData = objectMapper.writeValueAsString(reqDTO);
// log.info("请求JSON数据:{}", jsonData);
// jsonData = RsaCodingUtil.encryptByPrivateKey(Base64.encode(jsonData.getBytes(CHAR_SET)),
// RsaReadUtil.getPrivateKeyFromFile(qjldConfig.getQjldKeyPath(), qjldConfig.getQjldKeyPwd()));
//
// } catch (Exception e) {
// log.error("转换字符串异常:{}", e);
// }
//
// return jsonData;
// }
//
//
// @Test
// public void putMqData() {
// RiskAuditMessage message = new RiskAuditMessage();
// message.setOrderId(10L);
// message.setStatus(1);
// message.setMerchant("jishidai");
// message.setUid(25L);
// rabbitTemplate.convertAndSend(RabbitConst.qjld_queue_risk_order_notify, message);
// }
//
//
// @Test
// public void test11() {
// JSONObject report = null;
// try {
// String tesr="{" +
// "\"members\": {" +
// "\"update_time\": \"2019-06-12 15:46:10\"," +
// "\"error_msg\": \"请求用户数据成功\"," +
// "\"request_args\": [{" +
// "\"token\": \"15127599eaea407c8339adc619e8a7b9\"" +
// "}, {" +
// "\"env\": \"www\"" +
// "}]," +
// "\"error_code\": 31200," +
// "\"transactions\": [{" +
// "\"smses\": [{" +
// "\"start_time\": \"2019-06-09 12:10:55\"," +
// "\"update_time\": \"2019-06-12 15:46:04\"," +
// "\"subtotal\": 0.0," +
// "\"other_cell_phone\": \"10010\"," +
// "\"cell_phone\": \"13046329502\"" +
// "}, {" +
// "\"start_time\": \"2019-06-08 21:01:48\"," +
// "\"update_time\": \"2019-06-12 15:46:04\"," +
// "\"subtotal\": 0.0," +
// "\"cell_phone\": \"13046329502\"" +
// "}]," +
// "\"basic\": {" +
// "\"update_time\": \"2019-06-12 15:46:04\"," +
// "\"idcard\": \"4311****2261\"," +
// "\"reg_time\": \"2015-10-11 00:00:00\"," +
// "\"real_name\": \"柏颖\"," +
// "\"cell_phone\": \"13046329502\"" +
// "}," +
// "\"version\": \"1\"," +
// "\"token\": \"15127599eaea407c8339adc619e8a7b9\"" +
// "}]," +
// "\"status\": \"success\"" +
// "}" +
// "}";
// report=JSONObject.parseObject(tesr);
// if(report != null) {
// if(report.containsKey("members")) {
// JSONObject members = report.getJSONObject("members");
// if(members.containsKey("transactions")) {
// JSONArray transactions = members.getJSONArray("transactions");
// if(transactions.size() > 0) {
// JSONObject transactionsJson = (JSONObject) transactions.get(0);
// if(transactionsJson.containsKey("smses")) {
// JSONArray smses = transactionsJson.getJSONArray("smses");
// int n = smses.size();
// for (int i = 0; i < n; i++) {
// JSONObject smsesJson = (JSONObject) smses.get(i);
// if(!smsesJson.containsKey("other_cell_phone")) {
// System.out.println(smsesJson.toJSONString());
// }
// }
// }
// }
// }
// }
// }
// log.info("原始运营商报告数据:{}", report == null?null:report.toJSONString());
// } catch (Exception e) {
// log.error("获取原始运营商报告数据出错", e);
// }
// }
//
// @Test
// public void test12() {
// JSONObject report = null;
// String orderNo="1667131333849079808";
// try {
// JSONObject jsonObject1 = new JSONObject();
// jsonObject1.put("order_no", orderNo);
// jsonObject1.put("type", "1");
// for (int times = 0; times < 10 && report == null; times++) {
// String result = RongZeRequestUtil.doPost(Constant.rongZeQueryUrl, "api.charge.data", jsonObject1.toJSONString());
//// log.warn("原始运营商报告数据的融泽返回结果:"+result);
// //判断运营商数据
// JSONObject jsonObject = JSONObject.parseObject(result);
// if (jsonObject.containsKey("data")) {
// String dataStr = jsonObject.getString("data");
// JSONObject all = JSONObject.parseObject(dataStr);
// if (all.containsKey("data")) {
// JSONObject data = all.getJSONObject("data");
// if (data.containsKey("report")) {
// report = data.getJSONObject("report");
// }
// }
// }
// log.info(orderNo + "原始运营商报告数据当前获取运营报告循环次数:{}", times);
// }
// if (report != null) {
// if (report.containsKey("members")) {
// JSONObject members = report.getJSONObject("members");
// if (members.containsKey("transactions")) {
// JSONArray transactions = members.getJSONArray("transactions");
// if (transactions.size() > 0) {
// JSONObject transactionsJson = (JSONObject) transactions.get(0);
// if (transactionsJson.containsKey("smses")) {
// JSONArray smses = transactionsJson.getJSONArray("smses");
// int n = smses.size();
// for (int i = 0; i < n; i++) {
// JSONObject smsesJson = (JSONObject) smses.get(i);
// if(i == n-1) {
// System.out.println("1");
// }
// if (!smsesJson.containsKey("other_cell_phone") || smsesJson.get("other_cell_phone") == null) {
// System.out.println(i +"****" + smsesJson.toJSONString());
// }
// }
// }
// }
// }
// }
// }
//// log.warn("原始运营商报告数据:{},{}", orderNo, report == null ? null : report.toJSONString());
// } catch (Exception e) {
// log.error(orderNo + "获取原始运营商报告数据出错", e);
// }
// }
//
//
// @Test
// public void putMqData2() {
// OrderPayMessage message = new OrderPayMessage(10L);
// rabbitTemplate.convertAndSend(RabbitConst.baofoo_queue_order_pay, message);
// }
//
//
// @Test
// public void putMqData3() {
// OrderPayMessage message = new OrderPayMessage(10L);
// rabbitTemplate.convertAndSend(RabbitConst.kuaiqian_queue_order_pay, message);
// }
// @Test
// public void report() {
// JSONObject report = new JSONObject();
// report.put("ss",null);
// if(report.get("ss") == null){
// System.out.println("寄哪里");
// }
// }
//
//}
|
package common.util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import common.MsgCode;
import common.Severity;
import common.vo.Message;
import common.vo.MessageVo;
import play.libs.Json;
/**
* Created by yuan on 9/22/14.
*/
public class MessageUtil {
private MessageVo mesageVo;
private MessageUtil() {
super();
}
private static ThreadLocal<MessageUtil> instance = new ThreadLocal<MessageUtil>() {
protected MessageUtil initialValue() {
return (new MessageUtil());
}
};
public static MessageUtil getInstance() {
return instance.get();
}
public void setMessage(Message message) {
mesageVo = new MessageVo(message);
}
public void setMessage(Message message, Object value) {
setMessage(message);
mesageVo.setValue(value);
}
public String setMessageHeader(Object value){
Message message = mesageVo == null ? new Message(Severity.ERROR, MsgCode.OPERATE_FAILURE) : mesageVo.getMessage();
ObjectNode json = Json.newObject();
json.put("message", Json.toJson(message));
json.put("headerValue", Json.toJson(value));
return json.toString();
}
public JsonNode toJson() {
return Json.toJson(mesageVo);
}
public JsonNode msgToJson(Message message, Object value) {
setMessage(message, value);
return toJson();
}
public JsonNode msgToJson(Message message) {
setMessage(message);
return toJson();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.