text stringlengths 10 2.72M |
|---|
/*
*
* * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
* *
* * 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.huawei.myhealth.java.database.entity;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/**
* @since 2020
* @author Huawei DTSE India
*/
@Entity(tableName = "exercise_done")
public class ExerciseDone {
@PrimaryKey
@ColumnInfo(name = "uid")
@NonNull
String userUIDStr;
@ColumnInfo(name = "date_time")
String dateNTime;
@ColumnInfo(name = "exercise_id")
int exerciseId;
@ColumnInfo(name = "exercise_name")
String exerciseName;
//In Minutes
@ColumnInfo(name = "exercise_duration")
String exerciseDuration;
@ColumnInfo(name = "speed")
String speed;
//In Kilo Meters
@ColumnInfo(name = "distance_covered")
String distanceCovered;
@ColumnInfo(name = "calorie_burned")
String calorieBurned;
@ColumnInfo(name = "details_added_from")
String detailsAddedFrom;
@ColumnInfo(name = "created_at")
String createdAt;
@ColumnInfo(name = "last_update_at")
String lastUpdateAt;
public ExerciseDone(String userUIDStr, String dateNTime, int exerciseId, String exerciseName, String exerciseDuration, String speed, String distanceCovered, String calorieBurned, String detailsAddedFrom, String createdAt, String lastUpdateAt) {
this.userUIDStr = userUIDStr;
this.dateNTime = dateNTime;
this.exerciseId = exerciseId;
this.exerciseName = exerciseName;
this.exerciseDuration = exerciseDuration;
this.speed = speed;
this.distanceCovered = distanceCovered;
this.calorieBurned = calorieBurned;
this.detailsAddedFrom = detailsAddedFrom;
this.createdAt = createdAt;
this.lastUpdateAt = lastUpdateAt;
}
public String getUserUIDStr() {
return userUIDStr;
}
public void setUserUIDStr(String userUIDStr) {
this.userUIDStr = userUIDStr;
}
public String getDateNTime() {
return dateNTime;
}
public void setDateNTime(String dateNTime) {
this.dateNTime = dateNTime;
}
public int getExerciseId() {
return exerciseId;
}
public void setExerciseId(int exerciseId) {
this.exerciseId = exerciseId;
}
public String getExerciseName() {
return exerciseName;
}
public void setExerciseName(String exerciseName) {
this.exerciseName = exerciseName;
}
public String getExerciseDuration() {
return exerciseDuration;
}
public void setExerciseDuration(String exerciseDuration) {
this.exerciseDuration = exerciseDuration;
}
public String getSpeed() {
return speed;
}
public void setSpeed(String speed) {
this.speed = speed;
}
public String getDistanceCovered() {
return distanceCovered;
}
public void setDistanceCovered(String distanceCovered) {
this.distanceCovered = distanceCovered;
}
public String getCalorieBurned() {
return calorieBurned;
}
public void setCalorieBurned(String calorieBurned) {
this.calorieBurned = calorieBurned;
}
public String getDetailsAddedFrom() {
return detailsAddedFrom;
}
public void setDetailsAddedFrom(String detailsAddedFrom) {
this.detailsAddedFrom = detailsAddedFrom;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getLastUpdateAt() {
return lastUpdateAt;
}
public void setLastUpdateAt(String lastUpdateAt) {
this.lastUpdateAt = lastUpdateAt;
}
}
|
package com.v2social.socialdownloader.utils;
/**
* Created by muicv on 6/19/2017.
*/
public class AppUtils {
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class bj15312 {
public static void main(String[] args) throws IOException {
HashMap<String, Integer> alpa = new HashMap<String, Integer>();
alpa.put("A", 3);
alpa.put("B", 2);
alpa.put("C", 1);
alpa.put("D", 2);
alpa.put("E", 3);
alpa.put("F", 3);
alpa.put("G", 2);
alpa.put("H", 3);
alpa.put("I", 3);
alpa.put("J", 2);
alpa.put("K", 2);
alpa.put("L", 1);
alpa.put("M", 2);
alpa.put("N", 2);
alpa.put("O", 1);
alpa.put("P", 2);
alpa.put("Q", 2);
alpa.put("R", 2);
alpa.put("S", 1);
alpa.put("T", 2);
alpa.put("U", 1);
alpa.put("V", 1);
alpa.put("W", 1);
alpa.put("X", 2);
alpa.put("Y", 2);
alpa.put("Z", 1);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String A = br.readLine();
String B = br.readLine();
int str[] = new int[A.length() + B.length() - 1];
int temp[];
int count = 0;
for (int i = 0; i < A.length(); i++) {
str[count] = (alpa.get(A.substring(i, i + 1)) + alpa.get(B.substring(i, i + 1))) % 10;
count += 1;
if (i == A.length() - 1)
break;
str[count] = (alpa.get(B.substring(i, i + 1)) + alpa.get(A.substring(i + 1, i + 2))) % 10;
count += 1;
}
while (str.length != 2) {
temp = new int[str.length - 1];
for (int i = 0; i < temp.length; i++) {
temp[i] = (str[i] + str[i + 1]) % 10;
}
str = temp;
}
System.out.print(str[0]);
System.out.print(str[1]);
}
}
|
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootApplication
@ComponentScan("com.controller")
@EnableMongoRepositories("com.persistence")
public class SigetGrupo2Application {
public static void main(String[] args) {
SpringApplication.run(SigetGrupo2Application.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
|
package com.ads.utils;
public class ServerConfParser {
}
|
/*
* @(#) IXmlDsigInfoService.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ebms.xmldsiginfo.service;
import com.esum.appframework.service.IBaseService;
/**
*
* @author sjyim@esumtech.com
* @version $Revision: 1.5 $ $Date: 2009/01/16 08:25:40 $
*/
public interface IXmlDsigInfoService extends IBaseService {
Object searchXmlDsigInfoId(Object object);
Object selectXmlDsigInfoList(Object object);
Object checkXmlDsigInfoDuplicate(Object object);
Object selectDsiNodeList (Object object);
}
|
package action.com.project;
import action.com.AbstractAction;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import pojo.businessObject.MessageBO;
import pojo.businessObject.ProjectBO;
import pojo.valueObject.domain.UserVO;
import tool.BeanFactory;
import tool.JSONHandler;
/**
*
* ๅ ้ค้กน็ฎ
* ้่ฆprojectId
* Created by geyao on 2017/4/16.
*/
@Component
public class DeleteProjectAction extends AbstractAction {
//JSP้่ฆ
private Integer projectId;
@Autowired
private ProjectBO projectBO;
@Autowired
private MessageBO messageBO;
public String execute() throws Exception{
String role = session.get("role").toString();
UserVO userVO = (UserVO) session.get(role + "VO");
JSONObject jsonObject = BeanFactory.getJSONO();
if (role == null || userVO == null){
JSONHandler.sendJSON(jsonObject, response);
return "fail";
}
try {
messageBO.deleteProject(projectId, userVO);
projectBO.deleteProjectVO(projectId);
jsonObject.put("result", "success");
System.out.println("ๅ ้ค้กน็ฎ");
System.out.println(jsonObject);
return "success";
}catch (Exception e){
e.printStackTrace();
return "fail";
}finally {
JSONHandler.sendJSON(jsonObject, response);
}
}
public Integer getProjectId() {
return projectId;
}
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
}
|
package com.git.cloud.handler.automation.os.impl;
import com.git.cloud.handler.automation.os.GetServerHandler;
/**
* ้ช่ฏ่ฎก็ฎๅฎไพ็ถๆ๏ผๆฏๅฆไธบๆดปๅจๆ่
ๅ
ณๆบ็ถๆ
* @author SunHailong
* @version ็ๆฌๅท 2017-4-3
*/
public class CheckServerActiveOrStopStatusHandler extends GetServerHandler {
protected void commonInitParam() {
this.executeTimes = 1; // ๅชๆฅ่ฏขไธๆฌก
}
protected boolean isOperateVmSuccess(String status) {
if(status.equals("ACTIVE") || status.equals("SHUTOFF") || status.equals("STOPPED")) {
this.deviceStatus = status;
return true;
}
return false;
}
}
|
package behavioural.design.pattern.test;
import behavioural.design.pattern.context.Animal;
import behavioural.design.pattern.context.Bird;
import behavioural.design.pattern.context.Dog;
public class test {
public test() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Animal dog = new Dog();
Animal bird = new Bird();
System.out.println("dog "+dog.tryToFly());
System.out.println("bird "+bird.tryToFly());
}
}
|
package com.yuneec.galleryloader;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.util.Log;
import android.widget.ImageView;
import com.yuneec.flightmode15.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ImageLoader {
private ExecutorService executorService;
private AbstractFileCache fileCache;
private Map<Integer, String> imageViews = Collections.synchronizedMap(new WeakHashMap());
private MemoryCache memoryCache = new MemoryCache();
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
this.bitmap = b;
this.photoToLoad = p;
}
public void run() {
if (!ImageLoader.this.imageViewReused(this.photoToLoad) && this.bitmap != null) {
ImageView imageView = this.photoToLoad.imageView;
Drawable drawable = new BitmapDrawable(imageView.getResources(), this.bitmap);
TransitionDrawable td = new TransitionDrawable(new Drawable[]{new ColorDrawable(17170445), drawable});
imageView.setImageDrawable(td);
td.startTransition(1000);
}
}
}
private class PhotoToLoad {
public ImageView imageView;
public String url;
public PhotoToLoad(String u, ImageView i) {
this.url = u;
this.imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
public void run() {
if (!ImageLoader.this.imageViewReused(this.photoToLoad)) {
Bitmap bmp = ImageLoader.this.getBitmap(this.photoToLoad.url);
ImageLoader.this.memoryCache.put(this.photoToLoad.url, bmp);
if (!ImageLoader.this.imageViewReused(this.photoToLoad)) {
((Activity) this.photoToLoad.imageView.getContext()).runOnUiThread(new BitmapDisplayer(bmp, this.photoToLoad));
}
}
}
}
public ImageLoader(Context context) {
this.fileCache = new FileCache(context);
this.executorService = Executors.newFixedThreadPool(5);
}
public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {
this.imageViews.put(Integer.valueOf(((Integer) imageView.getTag()).intValue()), url);
Bitmap bitmap = this.memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else if (!isLoadOnlyFromCache) {
imageView.setImageResource(R.drawable.gallery_photo_loading);
queuePhoto(url, imageView);
}
}
private void queuePhoto(String url, ImageView imageView) {
this.executorService.submit(new PhotosLoader(new PhotoToLoad(url, imageView)));
}
public File getFileCache(String url) {
File f = this.fileCache.getFile(url);
return (f == null || !f.exists()) ? null : f;
}
private Bitmap getBitmap(String url) {
File f = this.fileCache.getFile(url);
Bitmap b = null;
if (f != null && f.exists()) {
b = decodeFile(f);
}
if (b != null) {
return b;
}
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
return decodeFile(f);
} catch (Exception ex) {
Log.e("", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
return null;
}
}
private Bitmap decodeFile(File f) {
try {
Options o = new Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
int width_tmp = o.outWidth;
int height_tmp = o.outHeight;
int scale = 1;
while (width_tmp / 2 >= 100 && height_tmp / 2 >= 100) {
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
Options o2 = new Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
return null;
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String load_url = (String) this.imageViews.get(Integer.valueOf(((Integer) photoToLoad.imageView.getTag()).intValue()));
if (load_url == null || !load_url.equals(photoToLoad.url)) {
return true;
}
return false;
}
public void clearCache() {
this.memoryCache.clear();
this.fileCache.clear();
}
public void clearMemoryCache() {
this.memoryCache.clear();
}
public void clearFileCache() {
this.fileCache.clear();
}
public static void CopyStream(InputStream is, OutputStream os) {
try {
byte[] bytes = new byte[51200];
while (true) {
int count = is.read(bytes, 0, 51200);
if (count != -1) {
os.write(bytes, 0, count);
} else {
return;
}
}
} catch (Exception e) {
Log.e("", "CopyStream catch Exception...");
}
}
}
|
package voc.ps.service;
import voc.ps.model.Word;
import java.util.List;
public interface WordService {
void addWord(Word p);
void updateWord(Word p);
List<Word> listWords();
Word getWordById(int id);
Word getWordByWord(String word);
void removeWord(int id);
boolean wordExist(Word word);
}
|
// https://www.youtube.com/watch?v=uvB-Ns_TVis&ab_channel=NickWhite
class Solution {
public void sortColors(int[] nums) {
if (nums.length == 0 || nums.length == 1) return;
int start = 0, end = nums.length - 1, index = 0;
while (index <= end && start < end) {
if (nums[index] == 0) {
nums[index] = nums[start];
nums[start] = 0;
start++;
index++;
} else if (nums[index] == 2) {
nums[index] = nums[end];
nums[end] = 2;
end--;
} else index++;
}
}
} |
package com.juan.project.vo;
public class BoardVo {
private int board_num;
private String board_writer;
private String board_title;
private int read_count;
private String reg_date;
private String board_context;
private int parent_num;
private String file_num;
public BoardVo() {
}
public BoardVo(int board_num, String board_writer, String board_title, int read_count, String reg_date,
String board_context, int parent_num, String file_num) {
super();
this.board_num = board_num;
this.board_writer = board_writer;
this.board_title = board_title;
this.read_count = read_count;
this.reg_date = reg_date;
this.board_context = board_context;
this.parent_num = parent_num;
this.file_num = file_num;
}
public int getBoard_num() {
return board_num;
}
public void setBoard_num(int board_num) {
this.board_num = board_num;
}
public String getBoard_writer() {
return board_writer;
}
public void setBoard_writer(String board_writer) {
this.board_writer = board_writer;
}
public String getBoard_title() {
return board_title;
}
public void setBoard_title(String board_title) {
this.board_title = board_title;
}
public int getRead_count() {
return read_count;
}
public void setRead_count(int read_count) {
this.read_count = read_count;
}
public String getReg_date() {
return reg_date;
}
public void setReg_date(String reg_date) {
this.reg_date = reg_date;
}
public String getBoard_context() {
return board_context;
}
public void setBoard_context(String board_context) {
this.board_context = board_context;
}
public int getParent_num() {
return parent_num;
}
public void setParent_num(int parent_num) {
this.parent_num = parent_num;
}
public String getFile_num() {
return file_num;
}
public void setFile_num(String file_num) {
this.file_num = file_num;
}
@Override
public String toString() {
return "BoardVo [board_num=" + board_num + ", board_writer=" + board_writer + ", board_title=" + board_title
+ ", read_count=" + read_count + ", reg_date=" + reg_date + ", board_context=" + board_context
+ ", parent_num=" + parent_num + "]";
}
} |
package com.celonis.challenge.repository;
import com.celonis.challenge.model.ProjectGenerationTask;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProjectGenerationTaskRepository extends JpaRepository<ProjectGenerationTask, String> {
}
|
package lab4;
import java.io.PrintWriter;
import java.util.Arrays;
public class BinHeap {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
int heap[] = new int[11];
for (int i = 0; i < 10; i++) {
heap[i] = (int) (Math.random() * 99 + 1);
}
heap[heap.length - 1] = 0;
pw.println("Array: " + Arrays.toString(heap));
int firstLeaftIndex = (heap.length / 2);
for (int i = firstLeaftIndex; i >= 0; i--) {
heapify(heap, i);
}
pw.println("Heap: " + Arrays.toString(heap));
insertHeap(heap, 50);
pw.println("Heap: " + Arrays.toString(heap));
}
public static void heapify(int a[], int i) {
int l = 2 * i + 1;
int r = 2 * i + 2;
int n = a.length;
if (!isHeap(a, i)) {
int large;
if (l >= n)
large = r;
else if (r >= n)
large = l;
else
large = a[r] > a[l] ? r : l;
swap(a, large, i);
}
if (l < n && !isHeap(a, l)) {
heapify(a, l);
}
if (r < n && !isHeap(a, r)) {
heapify(a, r);
}
}
public static void insertHeap(int a[], int n) {
int last = a.length - 1;
a[last] = n;
int parent = last >> 1;
while (parent >= 0 && a[parent] < a[last]) {
swap (a, parent, last);
last = parent;
parent = last >> 1;
}
}
public static void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static boolean isHeap(int a[], int i) {
int l = 2 * i + 1;
int r = 2 * i + 2;
int leafIndexStart = (a.length / 2);
int n = a.length;
if (i >= leafIndexStart)
return true;
if (l >= n)
return a[i] > a[r];
else if (r >= n)
return a[i] > a[l];
else
return a[i] > a[l] && a[i] > a[r];
}
}
|
package com.app.drashti.drashtiapp.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.app.drashti.drashtiapp.Adapter.MyDonationAdapter;
import com.app.drashti.drashtiapp.AddDonateActivity;
import com.app.drashti.drashtiapp.Utiliiyy.AppUtilty;
import com.app.drashti.drashtiapp.Utiliiyy.Constant;
import com.app.drashti.drashtiapp.Model.Donate;
import com.app.drashti.drashtiapp.Utiliiyy.JSONParser;
import com.app.drashti.drashtiapp.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MyDonationFragment extends Fragment {
private Button btnAddNewDonate;
private RecyclerView recyclerDonate;
private LinearLayoutManager linearLayoutManager;
private MyDonationAdapter myDonateAdapter;
private ArrayList<Donate> donates;
TextView txtStatus;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_donate, container, false);
linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerDonate = (RecyclerView) view.findViewById(R.id.recyclerDonate);
txtStatus = (TextView) view.findViewById(R.id.txtStatus);
recyclerDonate.setLayoutManager(linearLayoutManager);
btnAddNewDonate = (Button) view.findViewById(R.id.btnAddNewDonate);
btnAddNewDonate.setVisibility(View.VISIBLE);
btnAddNewDonate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AddDonateActivity.class);
startActivity(intent);
}
});
displayDonateData();
return view;
}
public void displayDonateData() {
txtStatus.setVisibility(View.VISIBLE);
txtStatus.setText("Please Wait...");
final AppUtilty appUtilty ;
appUtilty = new AppUtilty(getActivity());
new Thread(new Runnable() {
@Override
public void run() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("method", "food_list");
map.put("user_id",appUtilty.getUserData().getU_ID() );
final JSONObject result = JSONParser.doGetRequest(map, Constant.server);
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
donates = new ArrayList<Donate>();
donates.clear();
try {
if (result.getString("status").equals("true")) {
JSONObject data = result.getJSONObject("data");
JSONArray others_list = data.getJSONArray("my_list");
for (int i = 0; i < others_list.length(); i++) {
JSONObject object = others_list.getJSONObject(i);
Donate donate = new Donate();
donate.setF_name(object.getString("F_name"));
donate.setF_description(object.getString("F_description"));
donate.setF_id(object.getString("F_id"));
donate.setF_instaruction(object.getString("F_instruction"));
donate.setF_address(object.getString("F_address"));
donate.setF_quantity(object.getString("F_quantity"));
donate.setF_pickupDate(object.getString("F_pickupDate"));
donate.setF_image(object.getString("F_image"));
donate.setF_status(object.getString("F_status"));
donate.setF_pincode(object.getString("F_pincode"));
donate.setF_pickupTime(object.getString("F_pickupTime"));
donates.add(donate);
}
txtStatus.setVisibility(View.GONE);
myDonateAdapter = new MyDonationAdapter(getActivity(),donates);
recyclerDonate.setAdapter(myDonateAdapter);
myDonateAdapter.notifyDataSetChanged();
} else {
// Toast.makeText(getActivity(),result.getString("message"),Toast.LENGTH_LONG).show();
txtStatus.setVisibility(View.VISIBLE);
txtStatus.setText(result.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}
@Override
public void onResume() {
super.onResume();
displayDonateData();
}
}
|
package us.gibb.dev.gwt.demo.server;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import us.gibb.dev.gwt.command.results.StringResult;
import us.gibb.dev.gwt.demo.client.command.SayHelloCommand;
import us.gibb.dev.gwt.demo.model.Hello;
import us.gibb.dev.gwt.server.command.handler.Context;
import us.gibb.dev.gwt.server.jpa.JPACommandHandler;
import com.google.inject.Inject;
public class SayHelloCommandHandler extends JPACommandHandler<SayHelloCommand, StringResult> {
@Inject
public SayHelloCommandHandler(EntityManagerFactory emf) {
super(emf);
}
@Override
protected StringResult execute(EntityManager em, SayHelloCommand command, Context context) {
Hello hello = new Hello();
hello.setName(command.getName());
em.persist(hello);
return new StringResult(hello.toString());
}
}
|
package assign6;
public class ThreadDemo {
public static void main(String[] args) {
Runnable a=new MyThread();
Thread a1=new Thread(a);
Thread a2=new Thread(a);
//MyThread a1=new MyThread(a);
//MyThread a2=new MyThread(a);
a1.start();
a2.start();
}
}
|
package com.programapprentice.app;
/**
* User: program-apprentice
* Date: 8/23/15
* Time: 3:17 PM
*/
public class DecodeWays_91 {
// exceed time limit
public int numDecodings_V1(String s) {
if(s == null || s.isEmpty() || s.charAt(0) == '0') {
return 0;
}
if(s.length() == 1) {
return 1;
}
int t1 = 0;
int t2 = 0;
String sub = null;
sub = s.substring(1);
if(sub.isEmpty()) {
t1 = 1;
} else {
t1 = numDecodings_V1(sub);
sub = s.substring(2);
if (Integer.valueOf(s.substring(0, 2)) <= 26 &&
Integer.valueOf(s.substring(0, 2)) >= 10) {
if(sub.isEmpty()) {
t2 = 1;
} else {
t2 = numDecodings_V1(sub);
}
}
}
return t1+ t2;
}
// search in reverse
public int numDecodings(String s) {
if(s == null || s.isEmpty() || s.charAt(0) == '0') {
return 0;
}
int[] rec = new int[s.length()+1];
rec[0] = 1;
for(int i = 1; i <= s.length(); i++) {
if(s.charAt(i-1) != '0') {
rec[i] += rec[i-1];
}
if(i >= 2 && (s.charAt(i-2) == '1' || (s.charAt(i-2) == '2' && s.charAt(i-1) <= '6'))) {
rec[i] += rec[i-2];
}
}
return rec[s.length()];
}
}
|
/*
* Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.json;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* Funnel query JSON structure.
*/
@Slf4j
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class UpdateFunnelGroupQuery extends FunnelGroupQuery {
}
|
package lefkatis.personalityapp.Objects;
/**
* Created by al426 on 24/07/15.
*/
public class AnswerOptions extends Answer{
public AnswerOptions(int id, String text){
super(id, text);
}
}
|
package linkedlists;
public class DeleteValue {
public static Node deleteByValue(Node head, int value) {
Node newHead = head;
// Eliminates matches at the beginning
while (newHead != null && newHead.data == value) {
newHead = newHead.next;
}
// Eliminates matches in the rest of the list
Node runner = newHead;
Node previous = newHead;
while (runner != null) {
if (runner.data == value){
previous.next = runner.next;
}else{
previous = runner;
}
runner = runner.next;
}
return newHead;
}
}
|
package com.cybercoders.interview;
import static com.cybercoders.interview.Exercise3.TreeNode;
import static junit.framework.TestCase.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class TreeNodeTest {
/**
* The root node to be populated with children, for test purposes.
*/
private TreeNode<Integer> rootNode;
/**
* Prepares the test data. In this case, it happens to be a root node populated with children, in accordance with
* exercise #3 of the coding tasks.
*/
@Before
public void setUp() {
// Leaf Nodes (i.e. nodes without children)
TreeNode<Integer> _78 = new TreeNode<Integer>(78);
TreeNode<Integer> _56 = new TreeNode<Integer>(56);
TreeNode<Integer> _89 = new TreeNode<Integer>(89);
TreeNode<Integer> _7 = new TreeNode<Integer>(7);
// Non-root nodes with children
TreeNode<Integer> _22 = new TreeNode<Integer>(22, ImmutableList.of(_78));
TreeNode<Integer> _12 = new TreeNode<Integer>(12, ImmutableList.of(_22));
TreeNode<Integer> _3 = new TreeNode<Integer>(3, ImmutableList.of(_89, _7));
// The Root node
rootNode = new TreeNode<Integer>(34, ImmutableList.of(_3, _56, _12));
}
@Test
public void printDataItemListInDesiredSortOrder() throws Exception {
// When:
List<Integer> printedList = rootNode.generateDataItemListInDesiredSortOrder();
// Then
assertThat(rootNode.printDataItemListInDesiredSortOrder(),is("[78, 22, 7, 89, 12, 56, 3, 34]"));
}
@Test
public void generateDataItemListInDesiredSortOrder() throws Exception {
// When:
List<Integer> printedList = rootNode.generateDataItemListInDesiredSortOrder();
// Then
assertEquals(ImmutableList.of(78, 22, 7, 89, 12, 56, 3, 34), printedList);
}
} |
package fr.apocalypse.gestionpersonnage;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Character {
HashMap<String, Integer> fields;
HashMap<String, Integer> defaults;
HashMap<String, Integer> min;
HashMap<String, Integer> max;
ArrayList<String> orders;
HashMap<String, String> visibles;
public Character(){
fields = new HashMap<>();
defaults = new HashMap<>();
min = new HashMap<>();
max = new HashMap<>();
orders = new ArrayList<>();
visibles = new HashMap<>();
}
public boolean addField(String name){
return addField(name,0);
}
public boolean addField(String name, int value){
if(!fields.containsKey(name))
{
fields.put(name, Integer.valueOf(value));
orders.add(name);
return true;
}
return false;
}
public boolean setDefault(String name, int value){
if(fields.containsKey(name)) {
if(min.containsKey(name) && min.get(name).intValue() > value)
return false;
if(max.containsKey(name) && max.get(name).intValue() < value)
return false;
defaults.put(name, Integer.valueOf(value));
return true;
}
return false;
}
public boolean unsetDefault(String name){
if(fields.containsKey(name) && defaults.containsKey(name)) {
defaults.remove(name);
return true;
}
return false;
}
public boolean setMin(String name, int value){
if(fields.containsKey(name)) {
if(max.containsKey(name) && max.get(name).intValue() < value)
return false;
min.put(name, Integer.valueOf(value));
return true;
}
return false;
}
public boolean unsetMin(String name){
if(fields.containsKey(name) && min.containsKey(name)) {
min.remove(name);
return true;
}
return false;
}
public boolean setMax(String name, int value){
if(fields.containsKey(name)) {
if(min.containsKey(name) && min.get(name).intValue() > value)
return false;
max.put(name, Integer.valueOf(value));
return true;
}
return false;
}
public boolean unsetMax(String name){
if(fields.containsKey(name) && max.containsKey(name)) {
max.remove(name);
return true;
}
return false;
}
public boolean removeField(String name){
if(fields.containsKey(name)) {
fields.remove(name);
Log.d("GESTION-PERSONNAGE", String.format("length before: %d", orders.size()));
orders.remove(name);
Log.d("GESTION-PERSONNAGE", String.format("length after: %d", orders.size()));
if(defaults.containsKey(name)) {
defaults.remove(name);
}
if(min.containsKey(name)) {
min.remove(name);
}
if(max.containsKey(name)) {
max.remove(name);
}
return true;
}
return false;
}
public boolean addToField(String name, int value){
if(fields.containsKey(name)) {
int newValue = fields.get(name).intValue() + value;
if(min.containsKey(name))
{
int min = this.min.get(name).intValue();
if(newValue < min)
newValue = min;
}
if(max.containsKey(name))
{
int max = this.max.get(name).intValue();
if(newValue > max)
newValue = max;
}
fields.put(name, newValue);
}
return false;
}
public void loadFromJson(String toString) throws JSONException {
JSONObject jsonObject = new JSONObject(toString);
try{
JSONObject sub = jsonObject.getJSONObject("fields");
Iterator<String> it = sub.keys();
while(it.hasNext()){
String name = it.next();
addField(name, sub.getInt(name));
}
sub = jsonObject.getJSONObject("defaults");
it = sub.keys();
while(it.hasNext()){
String name = it.next();
setDefault(name, sub.getInt(name));
}
sub = jsonObject.getJSONObject("min");
it = sub.keys();
while(it.hasNext()){
String name = it.next();
setMin(name, sub.getInt(name));
}
sub = jsonObject.getJSONObject("max");
it = sub.keys();
while(it.hasNext()){
String name = it.next();
setMax(name, sub.getInt(name));
}
JSONArray jsonArray = jsonObject.getJSONArray("orders");
orders.clear();
for(int i = 0; i < jsonArray.length(); i++){
orders.add((String)jsonArray.get(i));
}
sub = jsonObject.getJSONObject("visibles");
it = sub.keys();
while(it.hasNext()){
String name = it.next();
setVisible(name, sub.getString(name));
}
}
catch (Exception e){
e.printStackTrace();
}
}
public String serialize() {
JSONObject jsonObject = new JSONObject();
try{
JSONObject sub = new JSONObject();
for (Iterator<Map.Entry<String, Integer>> it = fields.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sub.put(entry.getKey(), entry.getValue());
}
jsonObject.put("fields", sub);
sub = new JSONObject();
for (Iterator<Map.Entry<String, Integer>> it = defaults.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sub.put(entry.getKey(), entry.getValue());
}
jsonObject.put("defaults", sub);
sub = new JSONObject();
for (Iterator<Map.Entry<String, Integer>> it = min.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sub.put(entry.getKey(), entry.getValue());
}
jsonObject.put("min", sub);
sub = new JSONObject();
for (Iterator<Map.Entry<String, Integer>> it = max.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sub.put(entry.getKey(), entry.getValue());
}
jsonObject.put("max", sub);
jsonObject.put("orders", new JSONArray(orders));
sub = new JSONObject();
for (Iterator<Map.Entry<String, String>> it = visibles.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
sub.put(entry.getKey(), entry.getValue());
}
jsonObject.put("visibles", sub);
}
catch (Exception e){
e.printStackTrace();
}
return jsonObject.toString();
}
public boolean resetField(String name) {
if(defaults.containsKey(name)) {
return setField(name, defaults.get(name).intValue());
}
return false;
}
public boolean setField(String name, int value) {
if(fields.containsKey(name))
{
fields.put(name,value);
return true;
}
return false;
}
public boolean hasDefault(String key) {
return defaults.containsKey(key);
}
public Integer getDefault(String key) {
return defaults.get(key);
}
public boolean hasMin(String key) {
return min.containsKey(key);
}
public Integer getMin(String key) {
return min.get(key);
}
public boolean hasMax(String key) {
return max.containsKey(key);
}
public Integer getMax(String key) {
return max.get(key);
}
public boolean hasVisible(String key) {
return visibles.containsKey(key);
}
public String getVisible(String key) {
return visibles.get(key) + "-";
}
public boolean defaultVisible(String key){
return visibles.containsKey(key) && visibles.get(key).contains("default");
}
public boolean minVisible(String key){
return visibles.containsKey(key) && visibles.get(key).contains("min");
}
public boolean maxVisible(String key){
return visibles.containsKey(key) && visibles.get(key).contains("max");
}
public void setVisible(String name, String visible) {
visibles.put(name, visible);
}
public void orderFromJson(String result) {
orders.clear();
try {
JSONArray sub = new JSONArray(result);
for(int i=0; i < sub.length(); i++){
orders.add((String)sub.get(i));
}
}
catch (Exception exp){
}
}
}
|
package gov.nih.mipav.view;
import gov.nih.mipav.model.file.*;
import gov.nih.mipav.model.structures.*;
import java.io.*;
import javax.swing.*;
/**
* User interface to open a VOI.
*
* @version 0.1 Feb 24, 1998
* @author Matthew J. McAuliffe, Ph.D.
*/
public class ViewOpenVOIUI {
//~ Instance fields ------------------------------------------------------------------------------------------------
/** The main user interface. */
private ViewUserInterface UI;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Constructor to allow user to open a file.
*/
public ViewOpenVOIUI() {
UI = ViewUserInterface.getReference();
}
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* Open a VOI array based on the suffix of the file.
*
* @param image Image to open the VOI on.
* @param doLabel DOCUMENT ME!
*
* @return the opened VOIs
*/
public VOI[] open(ModelImage image, boolean doLabel) {
VOI[] voi;
FileCheshireVOI fileCheshireVOI;
FileVOI fileVOI;
String extension = " ";
String fileName;
String directory;
int i;
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Open VOI");
if (UI.getDefaultDirectory() != null) {
File file = new File(UI.getDefaultDirectory());
if (file != null) {
chooser.setCurrentDirectory(file);
} else {
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
}
} else {
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
}
if (doLabel) {
chooser.addChoosableFileFilter(new ViewImageFileFilter(new String[] { ".lbl" }));
} else {
chooser.addChoosableFileFilter(new ViewImageFileFilter(new String[] { ".xml", ".voi" }));
}
int returnValue = chooser.showOpenDialog(UI.getMainFrame());
if (returnValue == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getName();
directory = String.valueOf(chooser.getCurrentDirectory()) + File.separatorChar;
UI.setDefaultDirectory(directory);
} else {
return null;
}
try {
i = fileName.lastIndexOf('.');
if ((i > 0) && (i < (fileName.length() - 1))) {
extension = fileName.substring(i + 1).toLowerCase();
}
if (extension.equals("oly")) {
fileCheshireVOI = new FileCheshireVOI(fileName, directory, image);
voi = fileCheshireVOI.readVOI();
} else {
fileVOI = new FileVOI(fileName, directory, image);
if (doLabel || extension.equals("lbl")) {
voi = fileVOI.readVOI(true);
} else {
voi = fileVOI.readVOI(false);
}
}
} catch (IOException error) {
MipavUtil.displayError(error.getMessage());
return null;
}
if (voi == null) {
MipavUtil.displayError("VOI is null");
return null;
}
// UI.getController().registerModel(voi);
// System.err.println("registering VOIS");
for (i = 0; i < voi.length; i++) {
image.registerVOI(voi[i]);
}
image.notifyImageDisplayListeners();
return (voi);
}
/**
* Open a VOI array based on the suffix of the file.
*
* @param image Image to open the VOI on.
*
* @return the opened VOIs
*/
public VOI[] openOtherOrientation(ModelImage image) {
VOI[] voi;
FileCheshireVOI fileCheshireVOI;
FileVOI fileVOI;
String extension = " ";
String fileName;
String directory;
int i;
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Open VOI");
if (UI.getDefaultDirectory() != null) {
File file = new File(UI.getDefaultDirectory());
if (file != null) {
chooser.setCurrentDirectory(file);
} else {
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
}
} else {
chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
}
chooser.addChoosableFileFilter(new ViewImageFileFilter(new String[] { ".xml", ".voi" }));
int returnValue = chooser.showOpenDialog(UI.getMainFrame());
if (returnValue == JFileChooser.APPROVE_OPTION) {
fileName = chooser.getSelectedFile().getName();
directory = String.valueOf(chooser.getCurrentDirectory()) + File.separatorChar;
UI.setDefaultDirectory(directory);
} else {
return null;
}
try {
i = fileName.lastIndexOf('.');
if ((i > 0) && (i < (fileName.length() - 1))) {
extension = fileName.substring(i + 1).toLowerCase();
}
if (extension.equals("oly")) {
fileCheshireVOI = new FileCheshireVOI(fileName, directory, image);
voi = fileCheshireVOI.readVOI();
} else {
fileVOI = new FileVOI(fileName, directory, image);
voi = fileVOI.readOtherOrientationVOI();
}
} catch (IOException error) {
MipavUtil.displayError(error.getMessage());
return null;
}
if (voi == null) {
MipavUtil.displayError("VOI is null");
return null;
}
// UI.getController().registerModel(voi);
// System.err.println("registering VOIS");
for (i = 0; i < voi.length; i++) {
image.registerVOI(voi[i]);
}
image.notifyImageDisplayListeners();
return (voi);
}
}
|
package com.eflagcomm.android;
/**
* <p>{d}</p>
*
* @author zhenglecheng
* @date 2020-01-14
*/
public interface IShowMessage {
/**
* ๆพ็คบๆถๆฏ
* @param message ๆถๆฏๅ
ๅฎน
*/
void showMessage(String message);
}
|
package gLearn02;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import sun.jvm.hotspot.utilities.Assert;
import static org.junit.Assert.*;
/**
* Created by LiuFangGuo on 9/14/15.
*/
public class MyApplicationTest {
private Injector injector;
@Before
public void setUp() throws Exception {
injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(MessageService.class).to(MockMessageService.class);
}
});
}
@Test
public void test() {
MyApplication appTest = injector.getInstance(MyApplication.class);
org.junit.Assert.assertEquals(false,appTest.processMessages("caonima", "xionghuai"));
}
@After
public void tearDown() throws Exception {
injector = null;
}
} |
package me.ivt.com.ui;
import org.junit.Test;
import java.io.IOException;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws IOException {
MyObject myObject=new MyObject();
new ThreadB(myObject).start();
new ThreadA(myObject).start();
}
public class MyObject{
public void methodA(){
System.out.println("ๆง่กไบAAAAAAAAAAAAAA");
}
public void methodB(){
System.out.println("ๆง่กไบBBBBBBBBBBBBBB");
}
}
public class ThreadA extends Thread{
private MyObject mMyObject;
public ThreadA(MyObject myObject){
mMyObject=myObject;
}
@Override
public void run() {
super.run();
while (true){
mMyObject.methodA();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadB extends Thread{
private MyObject mMyObject;
public ThreadB(MyObject myObject){
mMyObject=myObject;
}
@Override
public void run() {
super.run();
while (true){
mMyObject.methodB();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} |
package com.example.administrator.newtestapp;
/**
* Created by Administrator on 2016/8/26.
*/
public class TestFirstCommit {
}
|
package org.juxtasoftware.diff;
import eu.interedition.text.Range;
import eu.interedition.text.Text;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public interface TokenSource {
List<Token> tokensOf(Text text, Set<Range> ranges) throws IOException;
}
|
package uquest.com.bo.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import uquest.com.bo.models.entity.Carrera;
import uquest.com.bo.models.entity.Instituto;
import uquest.com.bo.models.services.carrera.ICarreraService;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin(origins = {"http://localhost:4200"})
@RestController
@RequestMapping("/api")
public class CarreraRestController {
@Autowired
private ICarreraService carreraService;
@GetMapping("/carreras")
public List<Carrera> index() {
return carreraService.findAll();
}
@GetMapping("/carreras/institutos/{id}")
public List<Instituto> show(@PathVariable Long id) {
return carreraService.findInstByCarreraId(id);
// return null;
// List<Instituto> institutos = null;
// Map<String, Object> response = new HashMap<>();
// try {
// institutos = carreraService.findInstByCarreraId(id);
//// usuario.setEncuestas(null);
// } catch (DataAccessException e) {
// response.put("mensaje", "Error al realizar la consulta en la Base de datos");
// response.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
// return new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
// }
// if (institutos == null) {
// response.put("mensaje", "el instituto con ID: ".concat(id.toString().concat(" no existe en la base de datos!")));
// return new ResponseEntity<Map<String, Object>>(response, HttpStatus.NOT_FOUND);
// }
//
// return new ResponseEntity<Instituto>(institutos, HttpStatus.OK);
}
@GetMapping("/carreras/id/{id}")
public Carrera carreraById(@PathVariable Long id) {
return carreraService.findById(id);
}
@PostMapping("/carreras")
private ResponseEntity<?> create(@Valid @RequestBody Carrera carrera) {
Carrera carreraNew;
Map<String, Object> response = new HashMap<>();
try {
carreraNew = carreraService.save(carrera);
} catch (DataAccessException e) {
response.put("mensaje", "Error al realizar el insert en la Base de datos");
response.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
response.put("carrera", carreraNew);
response.put("mensaje", "El registro de la categoria fue satisfactorio.");
return new ResponseEntity<Map>(response, HttpStatus.CREATED);
}
@DeleteMapping("/carreras/delete/{id}")
public ResponseEntity<?> delete(@PathVariable Long id) {
Map<String, Object> response = new HashMap<>();
try {
carreraService.delete(id);
} catch (DataAccessException e) {
response.put("mensaje", "Error al eliminar la carrera en la Base de datos");
response.put("error", e.getMessage().concat(": ").concat(e.getMostSpecificCause().getMessage()));
return new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
response.put("mensaje", "El registro de la carrera se elimino correctamente");
return new ResponseEntity<Map>(response, HttpStatus.OK);
}
}
|
package egovframework.adm.tut.service;
import java.util.List;
import java.util.Map;
public interface TutorService {
/**
* ๊ฐ์ฌ ๋ฆฌ์คํธ ์ด๊ฐ์
* @param commandMap
* @return
* @throws Exception
*/
int selectTutorTotCnt(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ๋ฆฌ์คํธ ์กฐํ
* @param commandMap
* @return
* @throws Exception
*/
List<?> selectTutorList(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ๊ฐ์ ๋ฆฌ์คํธ ์กฐํ
* @param commandMap
* @return
* @throws Exception
*/
List<?> selectTutorSubjList(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ๊ฐ์ ์ด๋ ฅ ๋ฆฌ์คํธ ์กฐํ
* @param commandMap
* @return
* @throws Exception
*/
List<?> selectTutorSubjHistoryList(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ์ ๋ณด ๋ณด๊ธฐ ํ๋ฉด
* @param commandMap
* @return
* @throws Exception
*/
Map<?, ?> selectTutorView(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ๋ฑ๋ก
* @param commandMap
* @return
* @throws Exception
*/
int insertTutor(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ์์
* @param commandMap
* @return
* @throws Exception
*/
int updateTutor(Map<String, Object> commandMap) throws Exception;
/**
* ๊ฐ์ฌ ์ญ์
* @param commandMap
* @return
* @throws Exception
*/
int deleteTutor(Map<String, Object> commandMap) throws Exception;
}
|
package com.grandsea.ticketvendingapplication.activity.device;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.other.BeepManager;
import com.grandsea.ticketvendingapplication.R;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Grandsea09 on 2017/9/30.
*/
public class QRCodeActivity extends AppCompatActivity {
@BindView(R.id.qrcode_tvResult)
TextView qrcodeTvResult;
public static final int REQUEST_CODE=0x124;
private BeepManager mBeepManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrcode);
ButterKnife.bind(this);
mBeepManager = new BeepManager(this, R.raw.beep);
}
public void start(View view) {
Toast.makeText(QRCodeActivity.this, "click", Toast.LENGTH_LONG).show();
if (checkPackage("com.telpo.tps550.api")) {
Intent intent = new Intent();
intent.setClassName("com.telpo.tps550.api", "com.telpo.tps550.api.barcode.Capture");
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
Toast.makeText(QRCodeActivity.this, getResources().getString(R.string.identify_fail), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(QRCodeActivity.this, getResources().getString(R.string.identify_fail), Toast.LENGTH_LONG).show();
}
}
private boolean checkPackage(String packageName) {
PackageManager manager = this.getPackageManager();
Intent intent = new Intent().setPackage(packageName);
List<ResolveInfo> infos = manager.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
if (infos == null || infos.size() < 1) {
return false;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0x124) {
if (resultCode == 0) {
if (data != null) {
mBeepManager.playBeepSoundAndVibrate();
String qrcode = data.getStringExtra("qrCode");
Toast.makeText(QRCodeActivity.this, "Scan result:" + qrcode, Toast.LENGTH_LONG).show();
return;
}
} else {
Toast.makeText(QRCodeActivity.this, "Scan Failed", Toast.LENGTH_LONG).show();
}
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hdfcraft;
import java.util.List;
/**
* Some container of layers.
*
* @author pepijn
*/
public interface LayerContainer {
List<Layer> getLayers();
} |
package factoryMethod;
/**
* Date: 2019/3/2
* Created by Liuian
*/
/**
* ๆฝ่ฑกๅทฅๅๆนๆณ๏ผๆฝ่ฑก็ฑป๏ผ็ไบงๆนๆณๆฏๆฝ่ฑก็ ไพ่ตๅ็ฝฎๅๅ
* ๅฐไบงๅ็ฑปไธไบงๅ็ไบง็ฑป่งฃ่ฆๅ IPizza----->ๅ
ทไฝpizza-----ๅ
ทไฝPizzStore<-----ๆฝ่ฑก็PizzaStore
*/
abstract class PizzaStore {
void orderPizza(String pizzaType) {
IPizza pizza = createPizza(pizzaType);
pizza.rotate();
pizza.bake();
pizza.pack();
}
protected abstract IPizza createPizza(String pizzaType);
}
|
package com.saviourcat.crypto.exchange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Created by saviourcat on 07/01/18.
*/
public class VipBitcoinAPITest {
@org.junit.Test
public void getTicker() throws Exception {
VipBitcoinAPI api = new VipBitcoinAPI();
Ticker ticker = api.getTicker("btc", "idr");
assertEquals(ticker.getCoin1(), "btc");
assertEquals(ticker.getCoin2(), "idr");
assertTrue(ticker.getServerTime() > 0);
}
@org.junit.Test
public void getTrades() throws Exception {
VipBitcoinAPI api = new VipBitcoinAPI();
Trades trades = api.getTrades("xrp", "idr");
assertEquals(trades.getCoin1(), "xrp");
assertTrue(trades.getTradeItems().size() > 0);
}
} |
public class gasStation{
public int canCompleteCircuit(int[] gas, int[] cost) {
int gasSum = 0;
int costSum = 0;
for(int i=0; i<gas.length; i++){
gasSum += gas[i];
costSum += cost[i];
}
if(gasSum - costSum < 0) return -1;
int idx = 0;
int prefixSum = 0;
int min = Integer.MAX_VALUE;
for(int i=0; i<gas.length; i++){
prefixSum += gas[i] - cost[i];
if(prefixSum < min){
min = prefixSum;
idx = i;
}
}
return (idx + 1) % gas.length;
}
public static void main(String[] args){
int[] gas = {1,2,3,4,5};
int[] cost = {3,4,5,1,2};
System.out.println(canCompleteCircuit(gas, cost))
}
}
|
package Scripts;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class Excel {
public static String getCellValue(String xl, String sheet, int r,int c)
{
try
{
FileInputStream fis=new FileInputStream(xl);
Workbook wb = WorkbookFactory.create(fis);
Cell cell = wb.getSheet(sheet).getRow(r).getCell(c);
return cell.getStringCellValue();
}
catch(Exception e)
{
return"";
}
}
public static int getRowCount(String xl, String sheet)
{
try {
FileInputStream fis=new FileInputStream(xl);
Workbook wb=WorkbookFactory.create(fis);
return wb.getSheet(sheet).getLastRowNum();
}
catch (Exception e)
{
return 0;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package centro.de.computo;
/**
* Permite utilizar el nรบmero de personal y su puesto a varias ventanas.
* @author PREDATOR 15 G9-78Q
*/
public class User {
private static String usuario;
private static String puesto;
private User(){
}
public static void setUsuario(String usuario) {
User.usuario = usuario;
}
public static void setPuesto(String puesto) {
User.puesto = puesto;
}
public static String getUsuario() {
return User.usuario;
}
public static String getPuesto() {
return User.puesto;
}
}
|
public class RunningAroundPark {
public int numberOfLap(int N, int[] d) {
int last = d[0];
int result = 1;
for(int i = 1; i < d.length; ++i) {
if(d[i] <= last) {
++result;
}
last = d[i];
}
return result;
}
} |
package com.mkd.adtools.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mkd.adtools.bean.AdData;
import com.mkd.adtools.bean.AdEvtData;
import com.mkd.adtools.bean.AdPrice;
import com.mkd.adtools.bean.AdSite;
import com.mkd.adtools.bean.AdType;
import com.mkd.adtools.bean.AdUser;
import com.mkd.adtools.bean.Page;
import com.mkd.adtools.mapper.AdMapper;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class AdService {
@Autowired
public AdMapper admapper ;
public Page selectAdList(AdData ad){
PageHelper.startPage(ad.getCurrentpage(),ad.getPagesize());
List<AdData> list = this.admapper.selectAdList(ad);
PageInfo<AdData> pageInfo = new PageInfo<>(list);
Page page = new Page() ;
page.setParams(ad.getPagesize(),ad.getCurrentpage(), pageInfo.getTotal(), list);
return page ;
}
public List<AdType> selectAdTypeList() {
return this.admapper.selectAdTypeList();
}
public void editAd(AdData ad) {
this.admapper.editAd(ad);
}
public void insertAd(AdData ad) {
this.admapper.insertAd(ad);
}
public Integer selectEvtTotal(AdEvtData evt) {
return this.admapper.selectEvtTotal(evt);
}
public Page selectEvtGroupByAd(AdEvtData ad){
PageHelper.startPage(ad.getCurrentpage(),ad.getPagesize());
List<AdEvtData> list = this.admapper.selectEvtGroupByAd(ad);
PageInfo<AdEvtData> pageInfo = new PageInfo<>(list);
Page page = new Page() ;
page.setParams(ad.getPagesize(),ad.getCurrentpage(), pageInfo.getTotal(), list);
return page ;
}
public Page selectEvtGroupBySite(AdEvtData ad){
PageHelper.startPage(ad.getCurrentpage(),ad.getPagesize());
List<AdEvtData> list = this.admapper.selectEvtGroupBySite(ad);
PageInfo<AdEvtData> pageInfo = new PageInfo<>(list);
Page page = new Page() ;
page.setParams(ad.getPagesize(),ad.getCurrentpage(), pageInfo.getTotal(), list);
return page ;
}
public Page selectSiteList(AdSite ad){
PageHelper.startPage(ad.getCurrentpage(),ad.getPagesize());
List<AdSite> list = this.admapper.selectSiteList(ad);
PageInfo<AdSite> pageInfo = new PageInfo<>(list);
Page page = new Page() ;
page.setParams(ad.getPagesize(),ad.getCurrentpage(), pageInfo.getTotal(), list);
return page ;
}
public void updateSite(AdSite site) {
this.admapper.updateSite(site);
}
/**
* ๆฅ่ฏขๅชไฝไธปๅๅนฟๅไธป
* @param user
* @return
*/
public Page selectAdUserList(AdUser user) {
PageHelper.startPage(user.getCurrentpage(),user.getPagesize());
List<AdUser> list = this.admapper.selectAdUserList(user);
PageInfo<AdUser> pageInfo = new PageInfo<>(list);
Page page = new Page() ;
page.setParams(user.getPagesize(),user.getCurrentpage(), pageInfo.getTotal(), list);
return page ;
}
public void updateUser(AdUser user) {
this.admapper.updateUser(user);
}
public List<AdPrice> selectPriceList(AdPrice price){
return this.admapper.selectPriceList(price);
}
public void updatePrice(Integer id,Double price) {
this.admapper.updatePrice(id, price);
}
}
|
import javax.swing.*;
/**
* Button that is used to represent and play a card
*/
public class PlayerCardButton extends JButton {
private UnoCard _unoCard;
public UnoCard get_unoCard() {
return _unoCard;
}
public PlayerCardButton(UnoCard unoCard){
_unoCard = unoCard;
}
}
|
package pl.teo.lib.entities;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
@Entity @Data
public class Book {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@OneToMany
private List<Author> authors;
@OneToOne
private Category category;
}
|
/*
* Copyright 2015 The RPC Project
*
* The RPC Project 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 io.flood.rpc.network;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public abstract class AbstractSocketWapper implements SocketWapper {
private static final Logger LOG= LoggerFactory.getLogger(AbstractSocketWapper.class);
private final LinkedHashMap<String, ChannelHandler> handlers = new LinkedHashMap<String, ChannelHandler>();
private final Map<String, Object> options = new HashMap<String, Object>();
private final List<EventListener> eventListeners = new ArrayList<EventListener>();
final EventLoopGroup bossGroup = new NioEventLoopGroup();
final EventLoopGroup workerGroup = new NioEventLoopGroup();
final MessageDispatcher<NetPackage> dispatcher;
String groupName="";
public AbstractSocketWapper(MessageDispatcher<NetPackage> messageDispatcher){
this.dispatcher=messageDispatcher;
}
public boolean isAlived() {
return false;
}
public Map<String, Object> getOptions() {
return null;
}
public Object getOption(String opName) {
// TODO Auto-generated method stub
return options.get(opName);
}
public void setOption(String opName, Object opValue) {
options.put(opName,opValue);
}
public LinkedHashMap<String, ChannelHandler> getHandlers() {
return handlers;
}
public boolean addHandler(String handlerName, ChannelHandler handler) {
ChannelHandler chHandler = handlers.put(handlerName, handler);
return null == chHandler ? false : true;
}
public List<EventListener> getListeners() {
return eventListeners;
}
public void addListener(EventListener listener) {
eventListeners.add(listener);
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.error("exceptionCaught",ctx);
}
public void channelActive(ChannelHandlerContext ctx) throws Exception {
}
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if(msg instanceof NetPackage){
dispatcher.dispatchMessageEvent(ctx,(NetPackage) msg);
}
}
public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
}
}
|
package grupog.agendamlg;
import com.google.common.collect.ComparisonChain;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Evento.java
*
* Mar 31, 2017
* @author Jean Paul Beaudry
*/
@Entity
public class Evento implements Serializable, Comparable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id_evento;
private String titulo;
@Column(name="descripcion", nullable=false)
private String descripcion;
@Column(name="fecha_inicio", nullable=false)
@Temporal(TemporalType.DATE)
private Date fecha_inicio;
@Temporal(TemporalType.DATE)
private Date fecha_fin;
private String horario;
private String precio;
private double longitud;
private double latitud;
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="jn_comentarios_id",joinColumns=@JoinColumn(name="id_evento"),inverseJoinColumns=@JoinColumn(name="id_comentario"))
private List<Comentario> comentarios;
@ManyToMany
@JoinTable(name="jn_etiqueta_id",joinColumns=@JoinColumn(name="id_evento"),inverseJoinColumns=@JoinColumn(name="id_etiqueta"))
private Set<Etiqueta> etiqueta;
@ManyToOne
private Localidad localidad;
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="jn_notificaciones_id",joinColumns=@JoinColumn(name="id_evento"),inverseJoinColumns=@JoinColumn(name="id_notificacion"))
private List <Notificacion> notificaciones;
@ManyToMany(mappedBy="megusta")
private Set<Usuario> megusta;
@ManyToMany(mappedBy="sigue")
private Set<Usuario> sigue;
@ManyToMany(mappedBy="asiste")
private Set<Usuario> asiste;
// @OneToMany
// //@JoinTable(name="jn_rol_id",joinColumns=@JoinColumn(name="id_evento"),inverseJoinColumns=@JoinColumn(name="pk"))
// private Set<Rol> rol;
@ManyToMany
@JoinTable(name="jn_destinatario_id",joinColumns=@JoinColumn(name="id_evento"),inverseJoinColumns=@JoinColumn(name="id_destinatario"))
private Set<Destinatario> destinatario;
public Set<Destinatario> getDestinatario() {
return destinatario;
}
public void setDestinatario(Set<Destinatario> destinatario) {
this.destinatario = destinatario;
}
public String getHorario() {
return horario;
}
public void setHorario(String horarios) {
this.horario = horarios;
}
public Long getId_evento() {
return id_evento;
}
public void setId_evento(Long id_evento) {
this.id_evento = id_evento;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFecha_inicio() {
return fecha_inicio;
}
public void setFecha_inicio(Date fecha_inicio) {
this.fecha_inicio = fecha_inicio;
}
public Date getFecha_fin() {
return fecha_fin;
}
public void setFecha_fin(Date fecha_fin) {
this.fecha_fin = fecha_fin;
}
public String getPrecio() {
return precio;
}
public void setPrecio(String precio) {
this.precio = precio;
}
public double getLongitud() {
return longitud;
}
public void setLongitud(double longitud) {
this.longitud = longitud;
}
public double getLatitud() {
return latitud;
}
public void setLatitud(double latitud) {
this.latitud = latitud;
}
public List<Comentario> getComentarios() {
return comentarios;
}
public void setComentarios(List<Comentario> comentarios) {
this.comentarios = comentarios;
}
public Set<Etiqueta> getEtiqueta() {
return etiqueta;
}
public void setEtiqueta(Set<Etiqueta> etiqueta) {
this.etiqueta = etiqueta;
}
public Localidad getLocalidad() {
return localidad;
}
public void setLocalidad(Localidad localidad) {
this.localidad = localidad;
}
public List<Notificacion> getNotificaciones() {
return notificaciones;
}
public void setNotificaciones(List<Notificacion> notificaciones) {
this.notificaciones = notificaciones;
}
public Set<Usuario> getMegusta() {
return megusta;
}
public void setMegusta(Set<Usuario> megusta) {
this.megusta = megusta;
}
public Set<Usuario> getSigue() {
return sigue;
}
public void setSigue(Set<Usuario> sigue) {
this.sigue = sigue;
}
public Set<Usuario> getAsiste() {
return asiste;
}
public void setAsiste(Set<Usuario> asiste) {
this.asiste = asiste;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id_evento != null ? id_evento.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id_evento fields are not set
if (!(object instanceof Evento)) {
return false;
}
Evento other = (Evento) object;
if ((this.id_evento == null && other.id_evento != null) || (this.id_evento != null && !this.id_evento.equals(other.id_evento))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Evento{" + "id_evento=" + id_evento + ", titulo=" + titulo + ", descripcion=" + descripcion + ", fecha_inicio=" + fecha_inicio + ", fecha_fin=" + fecha_fin + ", horario=" + horario + ", precio=" + precio + ", longitud=" + longitud + ", latitud=" + latitud + '}';
}
@Override
public int compareTo(Object o) {
Evento e2 = (Evento)o;
return ComparisonChain.start()
.compare(this.getTitulo(), e2.getTitulo())
.compare(this.getLocalidad(), e2.getLocalidad())
.compare(this.getFecha_inicio(), e2.getFecha_inicio())
.compare(this.getFecha_fin(), e2.getFecha_fin())
.result();
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.api.internal;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import pl.edu.icm.unity.exceptions.EngineException;
/**
* Management of the single, shared, internal Unity endpoint, which is not under administrator's control.
* It is intended for a cross-cutting functionality, where Unity has to listen for some requests but
* on an path which is not endpoint specific (e.g. for SAML responses, where return address must be the same
* for all authenticators).
*
* @author K. Benedyczak
*/
public interface SharedEndpointManagement
{
/**
* Deploys the given servlet in the internal, shared endpoint.
* @param contextPath path to the deployed servlet, will be the next element after the common context of
* the whole internal endpoint.
* @param servlet the servlet to deploy
* @throws EngineException
*/
void deployInternalEndpointServlet(String contextPath, ServletHolder servlet, boolean mapVaadinResource) throws EngineException;
/**
* @return the first element of the servlet's path, with a leading '/' and no trailing '/'.
*/
String getBaseContextPath();
/**
*
* @param servletPath last path element of the servlet, without context prefix.
* @return URL in string form, including the server's address, shared context address and
* the servlet's address.
*/
String getServletUrl(String servletPath);
/**
* Deploys the given filter in the internal, shared endpoint.
* @param contextPath
* @param filter
* @throws EngineException
*/
void deployInternalEndpointFilter(String contextPath, FilterHolder filter)
throws EngineException;
/**
* @return advertised address of the server
*/
String getServerAddress();
}
|
package src;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;
public class KeywordManager {
private List<String> keywords;
public KeywordManager(String keywordsFilename) {
try {
keywords = readKeywords(keywordsFilename);
} catch (IOException e) {
System.err.println("Error loading keywords file; loading default keywords");
keywords = Arrays.asList(new String[]{"black friday", "promoรงรฃo", "senha"});
}
}
public boolean checkKeywords(String content) {
for (String keyword : keywords) {
if (content.indexOf(keyword) != -1 ? true : false) {
return true;
}
}
return false;
}
private List<String> readKeywords(String filename) throws IOException {
List<String> keywordsList = new LinkedList<String>();
Stream<String> stream = Files.lines(Paths.get(filename));
stream.filter(keyword -> keyword.length() > 0)
.forEach(keywordsList::add);
return keywordsList;
}
}
|
package learningunit.learningunit.Objects.Learn.VocabularyPackage;
import android.util.Log;
import learningunit.learningunit.Objects.API.ManageData;
public class Vocabulary {
private String Original, Translation, LanguageName1, LanguageName2;
public Vocabulary(String original, String translation, String LanguageName1, String LanguageName2, boolean followed) {
this.LanguageName1 = LanguageName1;
this.LanguageName2 = LanguageName2;
Original = original;
Translation = translation;
if(VocabularyMethods.VocabularyLanguageUsed(LanguageName1, getLanguageName2()) == 0){
VocabularyList list;
if(ManageData.OfflineAccount != 2){
list = new VocabularyList(getLanguageName1(), LanguageName2, "AllVoc_" + LanguageName1 + " <--> " + LanguageName2, false, followed);
}else{
list = new VocabularyList(getLanguageName1(), LanguageName2, "AllVoc_" + LanguageName1 + " <--> " + LanguageName2, true, followed);
}
if(!(list.ContainsVocabulary(this))) {
list.addVocabulary(this);
VocabularyMethods.saveVocabularyList(list);
}
}else if(VocabularyMethods.VocabularyLanguageUsed(LanguageName1, getLanguageName2()) == 1){
VocabularyList list = VocabularyMethods.getVocabularyList("AllVoc_" + LanguageName1 + " <--> " + LanguageName2, false);
if(list != null) {
if (!(VocabularyMethods.ListConstainsVoc(list, this))) {
list.addVocabulary(this);
VocabularyMethods.saveVocabularyList(list);
}
}else{
list = new VocabularyList(LanguageName1, LanguageName2, "AllVoc_" + LanguageName1 + " <--> " + LanguageName2, false, false);
if(!(VocabularyMethods.ListConstainsVoc(list, this))) {
list.addVocabulary(this);
VocabularyMethods.saveVocabularyList(list);
}
VocabularyMethods.saveVocabularyList(list);
}
}else if(VocabularyMethods.VocabularyLanguageUsed(LanguageName1, getLanguageName2()) == 2){
VocabularyList list = VocabularyMethods.getVocabularyList("AllVoc_" + LanguageName2 + " <--> " + LanguageName1, false);
if(list != null) {
if (!(VocabularyMethods.ListConstainsVoc(list, this))) {
list.addVocabulary(this);
VocabularyMethods.saveVocabularyList(list);
}
}else{
list = new VocabularyList(LanguageName1, LanguageName2, "AllVoc_" + LanguageName2 + " <--> " + LanguageName1, false, false);
if(!(VocabularyMethods.ListConstainsVoc(list, this))) {
list.addVocabulary(this);
VocabularyMethods.saveVocabularyList(list);
}
VocabularyMethods.saveVocabularyList(list);
}
}
}
public String getOriginal() {
return Original;
}
public void setOriginal(String original) {
Original = original;
}
public String getTranslation() {
return Translation;
}
public void setTranslation(String translation) {
Translation = translation;
}
public String getLanguageName1() {
return LanguageName1;
}
public void setLanguageName1(String languageName1) {
LanguageName1 = languageName1;
}
public String getLanguageName2() {
return LanguageName2;
}
public void setLanguageName2(String languageName2) {
LanguageName2 = languageName2;
}
@Override
public String toString() {
return "vocabulary{" +
"Original='" + Original + '\'' +
", Translation='" + Translation + '\'' +
", LanguageName1='" + LanguageName1 + '\'' +
", LanguageName2='" + LanguageName2 + '\'' +
'}';
}
} |
package com.rachelgrau.rachel.health4theworldstroke.Activities;
/**
* Created by varun on 10/9/2017.
*/
class ChatMessage {
public boolean rightSide;
public String message;
ChatMessage(boolean rightSide, String message) {
super();
this.rightSide = rightSide;
this.message = message;
}
} |
public class ThanhVien {
protected String HoTen;
protected Integer NamSinh;
protected String NoiSinh;
protected String DiaChi;
}
|
package com.blo;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.VilleDAO;
import com.dto.Ville;
@Service
public class VilleBLOimpl implements VilleBLO {
@Autowired
private VilleDAO villeDAO;
public ArrayList<Ville> getInfoVille(String codeCommune) {
ArrayList<Ville> listeVille;
if (codeCommune == null || "".equalsIgnoreCase(codeCommune)) {
listeVille = villeDAO.findAllVilles();
} else {
listeVille = villeDAO.findVilleByValue(codeCommune);
}
return listeVille;
}
public void deleteInfoVille(String codePostal) {
villeDAO.deleteInfoVille(codePostal);
}
public void postInfoVille(Ville ville) {
villeDAO.postInfoVille(ville);
}
public void putInfoVille(Ville ville) {
villeDAO.putInfoVille(ville);
}
}
|
package br.com.secia.apisecia.service;
import br.com.secia.apisecia.dto.PrioritiesDto;
import br.com.secia.apisecia.dto.TaskDto;
import br.com.secia.apisecia.model.Client;
import br.com.secia.apisecia.model.Task;
import br.com.secia.apisecia.model.User;
import br.com.secia.apisecia.repository.ClientRepository;
import br.com.secia.apisecia.repository.TaskRepository;
import br.com.secia.apisecia.repository.UserRepository;
import br.com.secia.apisecia.utils.PrioridadeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
@Service
@Transactional
public class TaskService {
@Autowired
private TaskRepository taskRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private ClientRepository clientRepository;
public List<Task> findAll() {
return taskRepository.findAll();
}
public Task save(TaskDto taskDto) {
Task task = convertTaskDTO(taskDto);
return taskRepository.save(task);
}
private Task convertTaskDTO(TaskDto taskDto) {
User user = userRepository.findByLogin(taskDto.getUsuario());
Client cliente = clientRepository.findByCodigo(taskDto.getCliente());
Task task = new Task();
task.setDescricao(taskDto.getDescricao());
task.setUsuario(user);
task.setTitulo(taskDto.getTitulo());
task.setCliente(cliente);
task.setPrioridade(taskDto.getPrioridade());
task.setDataPrevisaoAtendimento(taskDto.getDataPrevisaoAtendimento());
task.setData(LocalDate.now());
return task;
}
public PrioritiesDto findPriorities(String email) {
Integer quantidadeUrgente;
Integer quantidadeAlta;
Integer quantidadeMedia;
Integer quantidadeBaixa;
if(email != null && !email.isEmpty()) {
quantidadeUrgente = taskRepository.countTasks(PrioridadeEnum.URGENTE.getValor(), email);
quantidadeAlta = taskRepository.countTasks(PrioridadeEnum.ALTA.getValor(), email);
quantidadeMedia = taskRepository.countTasks(PrioridadeEnum.MEDIA.getValor(), email);
quantidadeBaixa = taskRepository.countTasks(PrioridadeEnum.BAIXA.getValor(), email);
} else {
quantidadeUrgente = taskRepository.countTasks(PrioridadeEnum.URGENTE.getValor());
quantidadeAlta = taskRepository.countTasks(PrioridadeEnum.ALTA.getValor());
quantidadeMedia = taskRepository.countTasks(PrioridadeEnum.MEDIA.getValor());
quantidadeBaixa = taskRepository.countTasks(PrioridadeEnum.BAIXA.getValor());
}
return new PrioritiesDto(quantidadeUrgente, quantidadeAlta, quantidadeMedia, quantidadeBaixa);
}
}
|
package task02;
/**
* @author Samosonok Liliia
* @version 1.0
*/
public class Main {
static String[] array = new String[20000000];
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
Thread thread1 = new Thread(new Distributor(array, 0, 5000000));
Thread thread2 = new Thread(new Distributor(array, 5000000, 10000000));
Thread thread3 = new Thread(new Distributor(array, 10000000, 15000000));
Thread thread4 = new Thread(new Distributor(array, 15000000, 20000000));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
long timeSpent = System.currentTimeMillis() - startTime;
System.out.println("1 thread - The program is executed in 166163 milliseconds\n" +
"2 threads - The program is executed in 226788 milliseconds\n" +
"4 threads - The program is executed in " + timeSpent + " milliseconds");
}
}
// 1 thread - The program is executed in 166163 milliseconds
// 2 threads - The program is executed in 226788 milliseconds
// 4 threads - The program is executed in 220088 milliseconds |
package entities;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class UserStub extends User {
public static final Calendar STUB_TIME =
new GregorianCalendar(2013, 11, 13, 10, 31);
public static final String STUB_NAME = "name stub";
public static final int STUB_LOGIN_COUNT = 99;
public int getLoginCount() {
return STUB_LOGIN_COUNT;
}
public Calendar getLastLoginTime() {
return STUB_TIME;
}
public String getName() {
return STUB_NAME;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package acme_banking_system.beans;
import acme_banking_system.data_access.Customer;
import acme_banking_system.data_access.Saving;
import acme_banking_system.exceptions.LoggedInStateException;
import acme_banking_system.exceptions.DataLayerException;
import acme_banking_system.exceptions.BusinessException;
import java.util.List;
import javax.ejb.Remote;
/**
*
* @author morga_000
*/
@Remote
public interface CustomerSessionRemote {
public void login(String firstName, String lastName) throws LoggedInStateException, BusinessException, DataLayerException;
public void logout() throws LoggedInStateException;
public Customer getCustomer() throws BusinessException, DataLayerException;
public void makeRepayment(String accNum, double amount) throws BusinessException, DataLayerException;
public List<Saving> getSavings(int C_ID) throws DataLayerException;
}
|
package us.gibb.dev.gwt.command.results;
import java.util.Date;
import us.gibb.dev.gwt.command.Result;
public class DateResult implements Result {
private static final long serialVersionUID = -2837056494983701122L;
private Date o;
DateResult() {
}
public DateResult(Date o) {
this.o = o;
}
public Date getDate() {
return o;
}
}
|
package com.framgia.fsalon.screen.customerinfo.user;
import io.reactivex.disposables.CompositeDisposable;
/**
* Listens to user actions from the UI ({@link UserFragment}), retrieves the data and updates
* the UI as required.
*/
final class UserPresenter implements UserContract.Presenter {
private static final String TAG = UserPresenter.class.getName();
private final UserContract.ViewModel mViewModel;
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
UserPresenter(UserContract.ViewModel viewModel) {
mViewModel = viewModel;
}
@Override
public void onStart() {
}
@Override
public void onStop() {
mCompositeDisposable.clear();
}
}
|
package com.xeland.project;
public class ClassSps {
}
|
public class Converter
{
public static void test()
{
for(int radix = 2;radix <= 36;radix++)
{
System.out.println("[0-"+(radix>10? ("9a-"+(char)(radix+86)):(radix-1))+"]*");
}
System.out.println("" + "aaaa".matches("[a-a]*") + "aa-aa".matches("[a-a]*"));
}
public static void main(String[] args)
{
try
{
System.out.println(convert(args[0],toDecimal(args[1],10),toDecimal(args[2],10)));
}
catch(IllegalArgumentException e)
{
System.out.println("syntax error");
}
}
// Returns a decimal integer equal to the value of a String representing a base 'r' integer
public static int toDecimal(String number,int radix) throws IllegalArgumentException
{
if(radix < 2 || 36 < radix || !number.toLowerCase().matches("[0-"+(radix>10? ("9a-"+(char)(radix+86)):(radix-1))+"]*"))
throw new IllegalArgumentException();
int dec = 0;
int pow = 1;
for(int i = number.length()-1;i >= 0;i--)
{
int c = number.charAt(i);
dec += (c - 48 - (c > 64 ? 7 : 0) - (c > 96 ? 32 : 0))*pow;
pow *= radix;
}
return dec;
}
// Returns a String representing a base 'r' integer whose value is equal to 'dec'
public static String fromDecimal(int decimal,int radix) throws IllegalArgumentException
{
if(radix < 1 || 36 < radix)
throw new IllegalArgumentException();
String s = "";
int pow = 1;
while(pow*radix < decimal)
{
pow *= radix;
}
while(pow >= 1)
{
int val = decimal/pow;
s += (char)(val + (val > 9 ? 55 : 48));
decimal -= val*pow;
pow /= radix;
}
return s;
}
// Uses toDecimal and fromDecimal to convert a String from base r1 to r2
public static String convert(String number,int initialRadix,int finalRadix) throws IllegalArgumentException
{
try
{
return fromDecimal(toDecimal(number,initialRadix),finalRadix);
}
catch(IllegalArgumentException e)
{
throw e;
}
}
}
|
class Solution {
public int findUnsortedSubarray(int[] nums) {
int[] newNums = new int[nums.length];
for(int i = 0; i < nums.length; i++){
newNums[i] = nums[i];
}
Arrays.sort(newNums);
int pre = 0;
int back = nums.length - 1;
while(pre < nums.length && newNums[pre] == nums[pre]){
pre++;
}
while(back >= 0 && newNums[back] == nums[back]){
back--;
}
if(pre >= back) return 0;
else return back - pre + 1;
}
} |
/*
* 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 co.edu.uniandes.csw.mueblesdelosalpes.logica.interfaces;
import co.edu.uniandes.csw.mueblesdelosalpes.dto.Oferta;
import co.edu.uniandes.csw.mueblesdelosalpes.excepciones.OperacionInvalidaException;
import java.util.List;
/**
*
* @author don_d
*/
interface IServicioOfertaMockLocal {
public void agregarOferta(Oferta oferta)throws OperacionInvalidaException;
public List<Oferta> darOferta();
}
|
package com.cb.cbfunny.gzhk;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.cb.cbfunny.Constans;
public class GzhkFragmentAdapter extends FragmentPagerAdapter {
private String[] titleStr;
private FragmentManager fm;
private int mCount = 0;
public GzhkFragmentAdapter(FragmentManager fm, String[] Data) {
super(fm);
this.fm = fm;
this.titleStr = Data;
mCount = titleStr.length;
}
@Override
public int getCount() {
return mCount;
}
@Override
public CharSequence getPageTitle(int position) {
return titleStr[position];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
@Override
public Fragment getItem(int position) {
String type = null;
Bundle bundle = new Bundle();
switch (position){
case 0:
type= Constans.GZHK_4KSTAR;
break;
case 1:
type= Constans.GZHK_RQSTAR;
break;
case 2:
type= Constans.GZHK_YSWEB;
break;
case 3:
type= Constans.GZHK_40MISTRY;
break;
case 4:
type= Constans.GZHK_MINISUKA;
break;
case 5:
type= Constans.GZHK_BOMB;
break;
}
bundle.putString(Constans.PARAM_XZ_TYPE,type);
return GzhkFragmentContent.newInstance(bundle);
}
} |
package egovframework.com.pop.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ziaan.lcms.EduStartBean;
import egovframework.adm.stu.service.StuMemberService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.pop.service.StudyScoreService;
import egovframework.usr.stu.std.service.StudyExamService;
import egovframework.usr.stu.std.service.StudyManageService;
@Controller
public class StudyScoreController {
/** log */
protected static final Log log = LogFactory.getLog(StudyScoreController.class);
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
/** studyScoreService */
@Resource(name = "studyScoreService")
StudyScoreService studyScoreService;
/** stuMemberService */
@Resource(name = "stuMemberService")
StuMemberService stuMemberService;
/** studyManageService */
@Resource(name = "studyManageService")
StudyManageService studyManageService;
/** studyExamService */
@Resource(name = "studyExamService")
private StudyExamService studyExamService;
@RequestMapping(value="/com/pop/courseScoreListPopup.do")
public String listPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
Map<String, Object> scoreMap = new HashMap<String, Object>();
scoreMap.putAll(commandMap);
if(commandMap.get("p_isAdmin") != null && commandMap.get("p_isAdmin").equals("Y"))
{
/**
* ๊ด๋ฆฌ์์์ ๋์ด์จ๊ฒ์ธ์ง๋ฅผ ํ์
ํ๊ธฐ ์ํ์ฌ ๋ฃ์ด์ค๋ค.
*/
scoreMap.put("userid", commandMap.get("p_userid"));
}
//์ ์ฒด์ ์์ ์ฅ
studyExamService.calc_score(scoreMap);
setSummaryInfo(scoreMap, model);
//ํ์ต์ ์์ ๋ณด
Map scoreData = studyScoreService.selectEduScore(scoreMap);
model.addAttribute("scoreData", scoreData);
//ํ๊ฐ์ ๋ณด
List examdata = studyScoreService.selectExamData(scoreMap);
model.addAttribute("examdata", examdata);
//๊ณผ์ ์ ๋ณด
Map projdata = studyScoreService.selectProjData(scoreMap);
model.addAttribute("projdata", projdata);
//์ค๋ฌธ์ ๋ณด
Map suldata = studyScoreService.selectSulData(scoreMap);
model.addAttribute("suldata", suldata);
//์ถ์๋ถ ๋ ์ง
int levelDay = stuMemberService.selectLevelDay(scoreMap);
scoreMap.put("levelDay", levelDay);
// ์ถ์๋ถ [type : List]
List<?> checklist = stuMemberService.selectSatisCheckList(scoreMap);
model.addAttribute("checklist", checklist);
List itemList = studyManageService.selectItemList(scoreMap);
model.addAttribute("itemList", itemList);
if(commandMap.get("p_isAdmin") != null && commandMap.get("p_isAdmin").equals("Y"))
{
/**
* ๊ด๋ฆฌ์์์ ๋์ด์จ๊ฒ์ธ์ง๋ฅผ ํ์
ํ๊ธฐ ์ํ์ฌ ๋ฃ์ด์ค๋ค.
*/
scoreMap.remove("userid");
}
model.addAllAttributes(scoreMap);
return "com/pop/courseScoreListPopup";
}
public void setSummaryInfo(Map<String, Object> commandMap, ModelMap model) throws Exception{
// ๋์ ์ง๋์จ, ๊ถ์ฅ ์ง๋์จ
double progress = Double.parseDouble(studyManageService.getProgress(commandMap));
double promotion = Double.parseDouble(studyManageService.getPromotion(commandMap));
model.addAttribute("progress", String.valueOf(progress));
model.addAttribute("promotion", String.valueOf(promotion));
Map data2 = studyManageService.SelectEduScore(commandMap);
model.addAttribute("EduScore", data2);
// ํ์ต์ ๋ณด
EduStartBean bean = EduStartBean.getInstance();
List dataTime = studyManageService.SelectEduTimeCountOBC(commandMap); // ํ์ต์๊ฐ,์ต๊ทผํ์ต์ผ,๊ฐ์์ ๊ทผํ์
model.addAttribute("EduTime", dataTime);
// ์ด์ฐจ์, ํ์ตํ ์ฐจ์, ์ง๋์จ, ๊ณผ์ ๊ตฌ๋ถ
Map map = studyManageService.getStudyChasi(commandMap);
model.addAttribute("datecnt", map.get("datecnt")); // ์ด์ฐจ์
model.addAttribute("edudatecnt", map.get("edudatecnt")); // ํ์ตํ ์ฐจ์
model.addAttribute("wstep", map.get("wstep")); // ์ง๋์จ
model.addAttribute("attendCnt", map.get("attendCnt")); // ์ถ์๊ฐ์
}
}
|
package com.icanit.app_v2.sqlite;
import java.util.List;
import com.icanit.app_v2.entity.UserContact;
import com.icanit.app_v2.exception.AppException;
public interface UserContactDao {
List<UserContact> listUserContactsByPhone(String phone) throws AppException;
boolean saveUserContact(UserContact contact) throws AppException;
boolean deleteContact(UserContact contact)throws AppException;
}
|
package br.com.estore.web.control;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import br.com.estore.web.dao.BookDAO;
import br.com.estore.web.dao.CategoryDAO;
import br.com.estore.web.model.BookBean;
import br.com.estore.web.model.CategoryBean;
@WebServlet("/home")
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HomeServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
treatRequest(request, response);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
treatRequest(request, response);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void treatRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException, ClassNotFoundException, SQLException {
String url = "index.jsp";
//carregar livros
BookDAO dao = new BookDAO();
List<BookBean> books = null;
String op = request.getParameter("op");
String id = request.getParameter("id");
if (op != null && id != null) {
books = dao.getAll(Integer.parseInt(id));
}
else {
books = dao.getAll();
}
if (books != null) {
HttpSession session = request.getSession(true);
session.setAttribute("books", books);
//limpa os erros
session.setAttribute("error", 0);
session.setAttribute("isLogged", 0);
}
//Categoria
CategoryDAO daoCategory = new CategoryDAO();
List<CategoryBean> categories = daoCategory.getAll();
if (categories.size() > 0) {
HttpSession session = request.getSession(true);
session.setAttribute("categories", categories);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
|
package com.cy.web.action;
import com.opensymphony.xwork2.ActionContext;
/**
* ๅบๆฌ็Action
* @author CY
*
*/
public class BaseAction {
/* ๅฝๅ้กต */
private Integer page;
/* id */
private Integer id;
/* id้ๅ */
private Integer[] ids;
/* ้ช่ฏ็ */
private String validateCode;
/**
* ๅคๆญ้ช่ฏ็ ๆฏๅฆๆญฃ็กฎ
* @return
*/
public boolean validateCode() {
if(validateCode != null && validateCode.toUpperCase().equals(((String)ActionContext.getContext().getSession().get("validateCode")).toUpperCase())) {
return true;
}
return false;
}
public String getValidateCode() {
return validateCode;
}
public void setValidateCode(String validateCode) {
this.validateCode = validateCode;
}
public Integer getPage() {
if(page == null || page <= 0) {
page = 1;
return 1;
} else {
return page;
}
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer[] getIds() {
return ids;
}
public void setIds(Integer[] ids) {
this.ids = ids;
}
}
|
import java.util.Arrays;
public class Simulation_v21 extends GP_PilotStudy_v21 {
public Simulation_v21() {
simulation_initalize();
for (currentGen = 1; currentGen <= MASTER_GENERATIONS; currentGen++) {
for (currentTestedSize = MINSYSTEM; currentTestedSize <= MAXSYSTEM; currentTestedSize++) {
System.out.println("\nCurrent tested size is " + currentTestedSize );
System.out.print(" Working on Deme ");
for (currentDeme = 0; currentDeme < currentTestedSize; currentDeme++) {
System.out.print(currentDeme + 1 + " ");
int currentTestedIndex = currentTestedSize - MINSYSTEM;
initializeDeme();
createTempArrays();
calculateFitness();
for (int demeGen = 0; demeGen < DEME_GENERATIONS; demeGen++) {
evolve();
temp_init_strategy[0][0][currentTestedIndex]=(char[]) FT_init_strategy[currentTestedIndex][currentDeme].clone();
if (currentTestedIndex > 0)
temp_join_strategy[0][0][currentTestedIndex-1]=(char[]) FT_join_strategy[currentTestedIndex-1][currentDeme].clone();
calculateFitness();
}
createMasterArrays();
double prevBestFitness = fitness[0];
sortDesc();
if (prevBestFitness + prevBestFitness * ENHANCMENT_MARGIN < fitness[0]) {
FT_init_strategy[currentTestedIndex][currentDeme] = (char[]) init_strategy[0][currentTestedIndex]
.clone();
if (currentTestedIndex > 0)
FT_join_strategy[currentTestedIndex - 1][currentDeme] = (char[]) join_strategy[0][currentTestedIndex - 1]
.clone();
} else {
init_strategy[0][currentTestedIndex] = (char[]) FT_init_strategy[currentTestedIndex][currentDeme]
.clone();
if (currentTestedIndex > 0)
join_strategy[0][currentTestedIndex - 1] = (char[]) FT_join_strategy[currentTestedIndex - 1][currentDeme]
.clone();
}
finalizeDeme();
}
}
if (MAXSYSTEM == 2)
printStats(FT_init_strategy, null);
else
printStats(FT_init_strategy, FT_join_strategy);
}
}
private void finalizeDeme() {
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
demes_init_strategy[currentTestedSize - MINSYSTEM][currentDeme][indivs] = (char[]) init_strategy[indivs][currentTestedSize - MINSYSTEM].clone();
}
if (currentTestedSize > 2)
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
demes_join_strategy[currentTestedSize - MINSYSTEM - 1][currentDeme][indivs] = (char[]) join_strategy[indivs][currentTestedSize
- MINSYSTEM - 1].clone();
}
}
private void initializeDeme() {
init_strategy = new char[TOTAL_POPSIZE][currentTestedSize - 1][];
join_strategy = new char[TOTAL_POPSIZE][currentTestedSize - 2][];
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
init_strategy[indivs][currentTestedSize - MINSYSTEM] = (char[]) demes_init_strategy[currentTestedSize - MINSYSTEM][currentDeme][indivs].clone();
}
if (currentTestedSize > 2)
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
join_strategy[indivs][currentTestedSize - MINSYSTEM - 1] = (char[]) demes_join_strategy[currentTestedSize
- MINSYSTEM - 1][currentDeme][indivs].clone();
}
for (int i = currentTestedSize - MINSYSTEM - 1; i >= 0; i--) {
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
init_strategy[indivs][i] = (char[]) FT_init_strategy[i][rd.nextInt(FT_init_strategy[i].length-1)].clone();
}
if (i > 0)
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++) {
join_strategy[indivs][i-1] = (char[]) FT_join_strategy[i-1][rd.nextInt(FT_join_strategy[i-1].length-1)].clone();
}
}
}
private static void simulation_initalize() {
System.out.println("\n\n******************************************************************");
System.out.println("Start of simulation " + currentSimulation);
System.out.println("******************************************************************\n\n");
currentTestedSize = MINSYSTEM;
fitness = new double[TOTAL_POPSIZE];
prevSimilarityCount = 0;
sortedFit = false;
shuffled = false;
demes_init_strategy = new char[uniqueWorldSizes][][][];
demes_join_strategy = new char[uniqueWorldSizes-1][][][];
implementClass_v21 implement = new implementClass_v21();
for (int i = 0; i < uniqueWorldSizes; i++) {
demes_init_strategy[i] = new char[i + MINSYSTEM][TOTAL_POPSIZE][];
for (int currentDeme = 0; currentDeme < demes_init_strategy[i].length; currentDeme++)
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++)
demes_init_strategy[i][currentDeme][indivs] = implement.create_random_indiv(DEPTH);
}
for (int i = 0; i < uniqueWorldSizes - 1; i++) {
demes_join_strategy[i] = new char[i + MINSYSTEM + 1][TOTAL_POPSIZE][];
for (int currentDeme = 0; currentDeme < demes_join_strategy[i].length; currentDeme++)
for (int indivs = 0; indivs < TOTAL_POPSIZE; indivs++)
demes_join_strategy[i][currentDeme][indivs] = implement.create_random_indiv(DEPTH);
}
init_strategy = new char[TOTAL_POPSIZE][uniqueWorldSizes][];
join_strategy = new char[TOTAL_POPSIZE][uniqueWorldSizes - 1][];
temp_init_strategy = new char[processors][POPSIZE_PER_PROCESSOR][uniqueWorldSizes][];
temp_join_strategy = new char[processors][POPSIZE_PER_PROCESSOR][uniqueWorldSizes - 1][];
tempFitness = new double[processors][POPSIZE_PER_PROCESSOR];
FT_init_strategy = new char[uniqueWorldSizes][][];
FT_join_strategy = new char[uniqueWorldSizes - 1][][];
for (int i = 0; i < uniqueWorldSizes; i++) {
// extra one for randomness
FT_init_strategy[i] = new char[i + MINSYSTEM + 1][];
for (int k = 0; k < FT_init_strategy[i].length - 1; k++)
FT_init_strategy[i][k] = (char[]) demes_init_strategy[i][rd.nextInt(i + MINSYSTEM)][rd
.nextInt(TOTAL_POPSIZE)].clone();
}
for (int i = 0; i < uniqueWorldSizes - 1; i++) {
// extra one for randomness
FT_join_strategy[i] = new char[i + MINSYSTEM + 2][];
for (int k = 0; k < FT_join_strategy[i].length - 1; k++)
FT_join_strategy[i][k] = (char[]) demes_join_strategy[i][rd.nextInt(i + MINSYSTEM + 1)][rd
.nextInt(TOTAL_POPSIZE)].clone();
}
}
private static void evolve() {
initiateThreads(3);
waitForThreadsFinish();
}
private static void shuffle() {
// Implementing Fisher Yates shuffle of fitness and population
// arrays
int index;
double tempFitness;
char[][] tempIndiv_1, tempIndiv_2;
for (int i = TOTAL_POPSIZE - 1; i > 0; i--) {
index = rd.nextInt(i + 1);
tempFitness = fitness[index];
fitness[index] = fitness[i];
fitness[i] = tempFitness;
tempIndiv_1 = init_strategy[index];
init_strategy[index] = init_strategy[i];
init_strategy[i] = tempIndiv_1;
tempIndiv_2 = join_strategy[index];
join_strategy[index] = join_strategy[i];
join_strategy[i] = tempIndiv_2;
}
shuffled = true;
sortedFit = false;
}
private static void printStats(char[][][] init_strategy, char[][][] join_strategy) {
//how similar are the stratgies to each oteher in every level
//how many attacks per world
if (!sortedFit) {
System.out.println("Not Sorted!!!");
System.exit(0);
}
System.out.println("\n\nSimulation=" + currentSimulation + " Generation=" + currentGen);
char[][][] temp_init = new char[uniqueWorldSizes][][];
char[][][] temp_join = null;
for (int i = 0; i < uniqueWorldSizes; i++) {
temp_init[i] = new char[i + MINSYSTEM][];
for (int k = 0; k < temp_init[i].length; k++)
temp_init[i][k] = init_strategy[i][k];
}
init_strategy = temp_init;
if (join_strategy != null) {
temp_join = new char[uniqueWorldSizes - 1][][];
for (int i = 0; i < uniqueWorldSizes - 1; i++) {
temp_join[i] = new char[i + MINSYSTEM + 1][];
for (int k = 0; k < temp_join[i].length; k++)
temp_join[i][k] = join_strategy[i][k];
}
join_strategy = temp_join;
}
populateProfiles(init_strategy, join_strategy);
printProfilesToFile();
for (int i = 0; i < attackProfiles.length; i++) {
System.out.println("In world " + (i+MINSYSTEM) + ", percentage of attacks of state ");
for (int k = 0; k < attackProfiles[i].length; k++) {
System.out.print((k+1) + " is ") ;
int totalAttacks=0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (attackProfiles[i][k][l] == true)
totalAttacks++;
}
System.out.println((double)totalAttacks/PROFILES_PER_CAT * 100 + " %");
}
}
System.out.println();
if (MAXSYSTEM > 2) {
for (int i = 0; i < balanceProfiles.length; i++) {
System.out.println("In world " + (i + MINSYSTEM + 1) + ", percentage of balances of state ");
for (int k = 0; k < balanceProfiles[i].length; k++) {
System.out.print((k + 1) + " is ");
int totalbalances = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (balanceProfiles[i][k][l] == true)
totalbalances++;
}
System.out.println((double) totalbalances / PROFILES_PER_CAT * 100 + " %");
}
}
System.out.println();
for (int i = 0; i < bandwagonProfiles.length; i++) {
System.out.println("In world " + (i + MINSYSTEM + 1) + ", percentage of bandwagons of state ");
for (int k = 0; k < bandwagonProfiles[i].length; k++) {
System.out.print((k + 1) + " is ");
int totalbandwagons = 0;
for (int l = 0; l < PROFILES_PER_CAT; l++) {
if (bandwagonProfiles[i][k][l] == true)
totalbandwagons++;
}
System.out.println((double) totalbandwagons / PROFILES_PER_CAT * 100 + " %");
}
}
}
}
private static void printProfilesToFile() {
for (int i = 0; i < attackProfiles.length; i++) {
for (int k = 0; k < attackProfiles[i].length; k++) {
outputString = (currentSimulation + "," + (k + 1) + "," + currentGen + "," + (i + MINSYSTEM));
for (int l = 0; l < PROFILES_PER_CAT; l++) {
outputString += ("," + (attackProfiles[i][k][l] == true ? 1 : 0));
}
if (i > 0) {
for (int l = 0; l < PROFILES_PER_CAT; l++) {
outputString += ("," + (balanceProfiles[i - 1][k][l] == true ? 1 : 0));
}
for (int l = 0; l < PROFILES_PER_CAT; l++) {
outputString += ("," + (bandwagonProfiles[i - 1][k][l] == true ? 1 : 0));
}
}
state_profiles_writer.writeToFile(outputString + "\n");
}
}
}
private static void populateProfiles(char[][][] init_strategy, char[][][] join_strategy) {
attackProfiles = new boolean[init_strategy.length][][];
for (int i = 0; i < attackProfiles.length; i++)
attackProfiles[i] = new boolean[init_strategy[i].length][PROFILES_PER_CAT];
for (int i = 0; i < attackProfiles.length; i++) {
for (int k = 0; k < attackProfiles[i].length; k++) {
for (int l = 0; l < PROFILES_PER_CAT; l++) {
attackProfiles[i][k][l] = profilingWorlds_Attacks[i][l].willItAttack(init_strategy[i][k], 0);
}
}
}
if (join_strategy != null) {
balanceProfiles = new boolean[join_strategy.length][][];
bandwagonProfiles = new boolean[join_strategy.length][][];
for (int i = 0; i < balanceProfiles.length; i++) {
balanceProfiles[i] = new boolean[join_strategy[i].length][PROFILES_PER_CAT];
bandwagonProfiles[i] = new boolean[join_strategy[i].length][PROFILES_PER_CAT];
}
for (int i = 0; i < balanceProfiles.length; i++) {
for (int k = 0; k < balanceProfiles[i].length; k++) {
for (int l = 0; l < PROFILES_PER_CAT; l++) {
balanceProfiles[i][k][l] = profilingWorlds_Joins[i][l].willItAttack(join_strategy[i][k], 1);
bandwagonProfiles[i][k][l] = profilingWorlds_Joins[i][l].willItAttack(join_strategy[i][k], 2);
}
}
}
}
}
private static void sortDesc() {
// sort fitness and strategy arrays in fitness descending order
char[][][] tempinit_strategy = new char[TOTAL_POPSIZE][currentTestedSize - 1][];
char[][][] tempjoin_strategy = new char[TOTAL_POPSIZE][currentTestedSize - 2][];
for (int i = 0; i < TOTAL_POPSIZE; i++) {
tempinit_strategy[i][0] = (char[]) init_strategy[i][0].clone();
}
for (int k = 1; k < currentTestedSize - 1; k++) {
for (int i = 0; i < TOTAL_POPSIZE; i++) {
tempinit_strategy[i][k] = (char[]) init_strategy[i][k].clone();
tempjoin_strategy[i][k - 1] = (char[]) join_strategy[i][k - 1].clone();
}
}
double[] tempFitness = (double[]) fitness.clone();
Arrays.sort(fitness);
double temp;
for (int i = 0; i < TOTAL_POPSIZE / 2; i++) {
temp = fitness[i];
fitness[i] = fitness[TOTAL_POPSIZE - 1 - i];
fitness[TOTAL_POPSIZE - 1 - i] = temp;
}
for (int i = 0; i < TOTAL_POPSIZE; i++) {
init_strategy[i] = null;
join_strategy[i] = null;
int j = 0;
while (init_strategy[i] == null && j < TOTAL_POPSIZE) {
if (fitness[i] == tempFitness[j]) {
init_strategy[i] = (char[][]) tempinit_strategy[j].clone();
join_strategy[i] = (char[][]) tempjoin_strategy[j].clone();
tempinit_strategy[j] = null;
tempjoin_strategy[j] = null;
tempFitness[j] = -1e-5;
}
j++;
}
}
sortedFit = true;
shuffled = false;
}
private static void calculateFitness() {
initiateThreads(2);
waitForThreadsFinish();
sortedFit = false;
}
private static void createMasterArrays() {
int counter = 0;
for (int i = 0; i < processors; i++) {
System.arraycopy(temp_init_strategy[i], 0, init_strategy, counter, POPSIZE_PER_PROCESSOR);
System.arraycopy(temp_join_strategy[i], 0, join_strategy, counter, POPSIZE_PER_PROCESSOR);
System.arraycopy(tempFitness[i], 0, fitness, counter, POPSIZE_PER_PROCESSOR);
counter += POPSIZE_PER_PROCESSOR;
}
}
private static void createTempArrays() {
int counter = 0;
for (int i = 0; i < processors; i++) {
System.arraycopy(init_strategy, counter, temp_init_strategy[i], 0, POPSIZE_PER_PROCESSOR);
System.arraycopy(join_strategy, counter, temp_join_strategy[i], 0, POPSIZE_PER_PROCESSOR);
System.arraycopy(fitness, counter, tempFitness[i], 0, POPSIZE_PER_PROCESSOR);
counter += POPSIZE_PER_PROCESSOR;
}
}
private static void initiateThreads(int operationID) {
thread = new Thread[processors];
implement = new implementClass_v21[processors];
for (int threadID = 0; threadID < processors; threadID++) {
implement[threadID] = new implementClass_v21(threadID, randNum, POPSIZE_PER_PROCESSOR,
tempFitness[threadID], temp_init_strategy[threadID], temp_join_strategy[threadID], TOTAL_TESTCASES);
implement[threadID].setOperationID(operationID);
thread[threadID] = new Thread(implement[threadID]);
thread[threadID].start();
}
}
private static void waitForThreadsFinish() {
for (int i = 0; i < processors; i++) {
try {
thread[i].join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_1_START)
return (++buffercount);
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
case GT:
case LT:
case EQ:
case AND:
case OR:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
private static void calcSimilarity(char[][] init_strategy, char[][] join_strategy, int indivs) {
similarityWarInit_Avg = new double[uniqueWorldSizes];
similarityWarJoin_Avg = new double[uniqueWorldSizes - 1];
if (indivs == 1) {
for (int k = 0; k < uniqueWorldSizes - 1; k++) {
similarityWarInit_Avg[k] = 1;
similarityWarJoin_Avg[k] = 1;
}
similarityWarInit_Avg[uniqueWorldSizes - 1] = 1;
}
int[] m = new int[uniqueWorldSizes];
int[] n = new int[uniqueWorldSizes - 1];
for (int i = 0; i < indivs - 1; i++)
for (int j = i + 1; j < indivs; j++) {
for (int k = 0; k < uniqueWorldSizes; k++) {
for (int l = 0; l < PROFILES_PER_CAT; l++) {
m[k]++;
if (attackProfiles[i][k][l] == attackProfiles[j][k][l]) {
similarityWarInit_Avg[k]++;
}
}
}
}
if (currentTestedSize > 2)
for (int i = 0; i < indivs - 1; i++)
for (int j = i + 1; j < indivs; j++) {
for (int k = 0; k < uniqueWorldSizes - 1; k++) {
for (int l = 0; l < PROFILES_PER_CAT; l++) {
n[k]++;
if (balanceProfiles[i][k][l] == balanceProfiles[j][k][l] && bandwagonProfiles[i][k][l] == bandwagonProfiles[j][k][l]) {
similarityWarJoin_Avg[k]++;
}
}
}
}
for (int i = 0; i < uniqueWorldSizes; i++) {
similarityWarInit_Avg[i] = similarityWarInit_Avg[i] / m[i];
}
if (currentTestedSize > 2)
for (int i = 0; i < uniqueWorldSizes - 1; i++) {
similarityWarJoin_Avg[i] = similarityWarJoin_Avg[i] / n[i];
}
}
static int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_1_START) {
switch (buffer[buffercounter]) {
case CAPMED:
System.out.print("CAP_MED");
break;
case CAPAVG:
System.out.print("CAP_AVG");
break;
case CAPSTD:
System.out.print("CAP_STD");
break;
case CAPMIN:
System.out.print("CAP_MIN");
break;
case CAPMAX:
System.out.print("CAP_MAX");
break;
case MYCAP:
System.out.print("MY_CAP");
break;
case OPPCAP:
System.out.print("OPP_CAP");
break;
case MYSIDECAP:
System.out.print("MY_SIDE_CAP");
break;
case LEFTCAPSUM:
System.out.print("LEFT_CAP_SUM");
break;
default:
System.out.print(randNum[buffer[buffercounter]]);
break;
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" + ");
break;
case SUB:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" - ");
break;
case MUL:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" * ");
break;
case DIV:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" / ");
break;
case GT:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" > ");
break;
case LT:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" < ");
break;
case EQ:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" = ");
break;
case AND:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" AND ");
break;
case OR:
System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
System.out.print(" OR ");
break;
}
a2 = print_indiv(buffer, a1);
System.out.print(")");
return (a2);
}
} |
import gamepackage.KPSPublicLocator;
import gamepackage.KPSPublicSoap_PortType;
import org.apache.axis.AxisFault;
import javax.xml.rpc.ServiceException;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
public class MernisServiceAdapter implements UserCheckService{
private KPSPublicSoap_PortType port;
@Override
public boolean CheckIfRealPerson(User user) throws AxisFault, MalformedURLException, ServiceException {
KPSPublicLocator locator = new KPSPublicLocator();
final URL url = new URL("https://tckimlik.nvi.gov.tr/Service/KPSPublic.asmx?wsdl");
port = locator.getKPSPublicSoap(url);
boolean result=true;
try {
result = port.TCKimlikNoDogrula(Long.parseLong(user.getNationalityId()),
user.getFirstName(), user.getLastName(), user.dateOfBirth.getYear());
} catch (RemoteException e) {
e.printStackTrace();
}
return result;
}
}
|
package de.bjoern.ahlfeld.shoplytics.services;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.estimote.sdk.Utils;
import de.bjoern.ahlfeld.shoplytics.R;
import de.bjoern.ahlfeld.shoplytics.api.ApiService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class BeaconScanService extends Service {
private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId",
ESTIMOTE_PROXIMITY_UUID, null, null);
protected static final String TAG = BeaconScanService.class.getName();
private BeaconManager beaconManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
beaconManager = new BeaconManager(this);
// Default values are 5s of scanning and 25s of waiting time to save CPU
// cycles.
// In order for this demo to be more responsive and immediate we lower
// down those values.
beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(5), 0);
// Should be invoked in #onCreate.
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
@Override
public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
for (Beacon b : beacons) {
if (Utils.proximityFromAccuracy(Utils.computeAccuracy(b))
.equals(Utils.Proximity.NEAR)) {
Log.d(TAG+"beacon-discovered", b.toString());
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
getString(R.string.preferences),
Context.MODE_MULTI_PROCESS);
if (prefs != null
&& !prefs.getBoolean(
getString(R.string.first_launch), true)) {
Log.d(TAG, "Notify api");
ApiService.notifyCustomer(b);
}
}
}
}
});
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Should be invoked in #onStart.
super.onStartCommand(intent, flags, startId);
Log.d(TAG, "onStart");
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
@Override
public void onServiceReady() {
try {
Log.d(TAG, "service ready");
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
} catch (RemoteException e) {
Log.e(TAG, "Cannot start ranging", e);
}
}
});
// If we get killed, after returning from here, restart
return START_STICKY;
}
@Override
public void onDestroy() {
// When no longer needed. Should be invoked in #onDestroy.
if (beaconManager != null) {
beaconManager.disconnect();
}
super.onDestroy();
}
}
|
package by.orion.onlinertasks.data.datasource.credentials.remote;
import android.accounts.Account;
import android.support.annotation.NonNull;
import by.orion.onlinertasks.common.network.services.CredentialsService;
import by.orion.onlinertasks.data.datasource.credentials.CredentialsDataSource;
import by.orion.onlinertasks.data.models.common.requests.SignInRequestParams;
import by.orion.onlinertasks.data.models.credentials.AccessTokenRequestBody;
import by.orion.onlinertasks.data.models.credentials.Credentials;
import io.reactivex.Completable;
import io.reactivex.Single;
import static by.orion.onlinertasks.data.models.credentials.CredentialsConstants.AuthenticationClients;
import static by.orion.onlinertasks.data.models.credentials.CredentialsConstants.AuthenticationGrants;
public class RemoteCredentialsDataSource implements CredentialsDataSource {
@NonNull
private final CredentialsService service;
public RemoteCredentialsDataSource(@NonNull CredentialsService service) {
this.service = service;
}
@Override
public Single<Credentials> getValue(@NonNull String key) {
throw new UnsupportedOperationException();
}
@Override
public Completable setValue(@NonNull String key, @NonNull Credentials value) {
throw new UnsupportedOperationException();
}
@Override
public Single<Credentials> signIn(@NonNull SignInRequestParams params) {
return service.accessToken(new AccessTokenRequestBody(params.username(), params.password()));
}
@Override
public Single<Boolean> isAuthorized() {
throw new UnsupportedOperationException();
}
@Override
public Single<Credentials> refreshCredentials(@NonNull Credentials credentials) {
return service.refreshCredentials(credentials.refreshToken(), AuthenticationClients.USER, AuthenticationGrants.PASSWORD);
}
@Override
public Single<Account> saveAccount(@NonNull SignInRequestParams params, @NonNull Credentials token) {
throw new UnsupportedOperationException();
}
}
|
package com.example.hante.newprojectsum.okhttpactivity.model;
import java.io.Serializable;
/**
* Zhihu
*/
public class ZhiHuInfo implements Serializable{
private String mId;
private String mImg;
private String mTitle;
public ZhiHuInfo (String mId, String mImg, String mTitle) {
this.mId = mId;
this.mImg = mImg;
this.mTitle = mTitle;
}
public ZhiHuInfo () {
}
public String getmId () {
return mId;
}
public void setmId (String mId) {
this.mId = mId;
}
public String getmImg () {
return mImg;
}
public void setmImg (String mImg) {
this.mImg = mImg;
}
public String getmTitle () {
return mTitle;
}
public void setmTitle (String mTitle) {
this.mTitle = mTitle;
}
}
|
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class RiskController implements ActionListener, MouseListener, ChangeListener{
private RiskModel model;
private RiskView view;
public RiskController(RiskModel model, RiskView view){
this.model = model;
this.view = view;
}
public void actionPerformed(ActionEvent act){
//If they clicked on a button...
if(act.getActionCommand().equals("Two") || act.getActionCommand().equals("Three") ||
act.getActionCommand().equals("Four") || act.getActionCommand().equals("Five") ||
act.getActionCommand().equals("Six")){
//... do this:
model.setPlayersSelected(true);
view.removeButtons();
//Take button input and start new game based on button pressed
if(act.getActionCommand().equals("Two")){
model.setPlayers(2);
startTwoPlayerGame();
//TEST CODE PLEASE IGNORE
/*model.setIsAttacking(true);
model.setIsTurn(true);
model.setCurrentPlayer(1);
model.setAttackingSelectedSquare(model.getTerritories(0));
model.getAttackingSelectedSquare().setTroopNumber(20);
model.setDefendingSelectedSquare(model.getTerritories(1));*/
view.repaint();
}else if(act.getActionCommand().equals("Three")){
model.setPlayers(3);
startNewGame(3);
}else if(act.getActionCommand().equals("Four")){
model.setPlayers(4);
startNewGame(4);
}else if(act.getActionCommand().equals("Five")){
model.setPlayers(5);
startNewGame(5);
}else if(act.getActionCommand().equals("Six")){
model.setPlayers(6);
startNewGame(6);
}
}
}
public void startTwoPlayerGame(){
//Starts new two player game
model.setCurrentPlayer(1);
model.setPlayers(2);
model.twoPlayerSetup();
model.setIsDistributing(true);
view.setLabel("Player " + model.getCurrentPlayer() + ": Reinforce one of your territories. " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " left to distribute.");
view.repaint();
}
public void startNewGame(int players){
//Starts new non-two player game
model.setCurrentPlayer(1);
model.setPlayers(players);
model.setIsChoosing(true);
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose your territory. " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " left to distribute.");
view.repaint();
}
public void turnSetUp(){
//Sets up each player's first turn
model.setPlayerCurTroops(model.getCurrentPlayer(), model.calculateReinforcements(model.getCurrentPlayer()));
view.setLabelColor(model.getPlayerColor(model.getCurrentPlayer()));
view.setLabel("Player " + model.getCurrentPlayer() + " is distributing their reinforcements per turn: " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " reinforcements to distribute.");
model.setIsReinforcing(true);
}
////////////////////////////////// PRE-GAME TERRITORY SELECTION AND DISTRIBUTION /////////////////////////////////////////////////////
public void chooseTerritory(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() == -1){ //if square is unclaimed
tempSquare.setPlayer(model.getCurrentPlayer());
tempSquare.setTroopNumber(1);
decrementTroops();
nextPlayer();
if(model.getCurrentPlayer() > model.getPlayers()){
model.setCurrentPlayer(1);
}
view.setLabelColor(model.getPlayerColor(model.getCurrentPlayer()));
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose your territory. " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " left to distribute.");
}else{
view.setLabel("That territory has already been claimed. Player " + model.getCurrentPlayer() + ", choose one that is unclaimed.");
}
if(model.allTerritoriesChosen()){
model.setIsChoosing(false);
model.setIsDistributing(true);
view.setLabelColor(model.getPlayerColor(model.getCurrentPlayer()));
view.setLabel("Player " + model.getCurrentPlayer() + ": Reinforce one of your territories. " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " left to distribute.");
}
}
}
public void firstDistributeToTerritory(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){
if(tempSquare.getPlayer() == model.getCurrentPlayer()){
tempSquare.setTroopNumber(tempSquare.getTroopNumber() + 1);
decrementTroops();
nextPlayer();
if(model.getCurrentPlayer() > model.getPlayers()){
model.setCurrentPlayer(1);
}
view.setLabelColor(model.getPlayerColor(model.getCurrentPlayer()));
view.setLabel("Player " + model.getCurrentPlayer() + ": Reinforce one of your territories. " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " left to distribute.");
}else{
view.setLabelColor(model.getPlayerColor(model.getCurrentPlayer()));
view.setLabel("Player " + model.getCurrentPlayer() + " does not own that territory. Choose a territory you own.");
}
}
if(model.allTroopsDistributed()){
model.setIsDistributing(false);
model.setIsTurn(true);
model.setCurrentPlayer(1);
turnSetUp();
}
}
////////////////////////////////// END OF PRE-GAME TERRITORY SELECTION AND DISTRIBUTION /////////////////////////////////////////////////////
////////////////////////////////// START OF PLAYER TURN PHASES //////////////////////////////////////////////////////////////////////////////////////
public void distributeReinforcements(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() == model.getCurrentPlayer()){
model.decrementPlayerCurTroops(model.getCurrentPlayer());
tempSquare.setTroopNumber(tempSquare.getTroopNumber() + 1);
if(model.getPlayerCurTroops(model.getCurrentPlayer()) == 0){
model.setIsReinforcing(false);
model.setIsAttackPhase(true);
view.setLabel("Player " + model.getCurrentPlayer() + " is attacking. Choose where to attack from or end combat.");
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " is distributing their reinforcements per turn: " + model.getPlayerCurTroops(model.getCurrentPlayer()) + " reinforcements to distribute.");
}
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " does not own that territory. Reinforce a territory you own.");
}
}
}
//This code is a goddamn mess Eric
public void attackPhase(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() == model.getCurrentPlayer()){
if(tempSquare.getTroopNumber() > 1){
tempSquare.setIsSelected(true);
model.setAttackingSelectedSquare(tempSquare);
model.setIsAttackPhase(false);
model.setTerritorySelected(true);
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose where to attack.");
}else{
view.setLabel("That square does not have enough troops to attack! Choose again.");
}
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " does not own that territory. Attack from a territory you own.");
}
}
}
public void selectTerritoryToAttack(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() != model.getCurrentPlayer()){
if(model.getAttackingSelectedSquare().checkLinks(tempSquare)){
tempSquare.setIsSelected(true);
model.setDefendingSelectedSquare(tempSquare);
model.setTerritorySelected(false);
model.setIsAttacking(true);
}else{
view.setLabel("Player " + model.getCurrentPlayer() + ": Please select an adjacent territory.");
}
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " owns that territory. Attack a territory you don't own.");
}
}else{
model.setTerritorySelected(false);
model.setIsAttackPhase(true);
resetSquares();
view.setLabel("Player " + model.getCurrentPlayer() + " is attacking. Choose where to attack from.");
}
}
public void makeRoll(){
int attackingNumber = 0;
int defendingNumber = 0;
//Determine how many die will be rolled on each side
if(model.getAttackingSelectedSquare().getTroopNumber() >= 4){
attackingNumber = 3;
}else if(model.getAttackingSelectedSquare().getTroopNumber() == 3){
attackingNumber = 2;
}else if(model.getAttackingSelectedSquare().getTroopNumber() == 2){
attackingNumber = 1;
}else{
System.out.println("You shouldn't be able to attack from here.");
}
if(model.getDefendingSelectedSquare().getTroopNumber() > 1){
defendingNumber = 2;
}else{
defendingNumber = 1;
}
// Die rolls are added
for(int i = 0; i < attackingNumber; i++){
model.addAttackingNumber((int)(Math.random()*6)+1);
}
for(int i = 0; i < defendingNumber; i++){
model.addDefendingNumber((int)(Math.random()*6)+1);
}
//Get the array for the rolls
int[] defeats = model.compareAttackingAndDefendingNumbers();
//Subtract the losses
model.getAttackingSelectedSquare().setTroopNumber(model.getAttackingSelectedSquare().getTroopNumber() - defeats[0]);
model.getDefendingSelectedSquare().setTroopNumber(model.getDefendingSelectedSquare().getTroopNumber() - defeats[1]);
//Setup the string for the label to print the roll numbers
ArrayList<Integer> attackingNumbers = model.getAttackingNumbers();
ArrayList<Integer> defendingNumbers = model.getDefendingNumbers();
String a = "";
for(int i = 0; i < attackingNumbers.size(); i++){
a = a + attackingNumbers.get(i) + ", ";
}
a=a.substring(0,a.length()-2);
String d = "";
for(int i = 0; i < defendingNumbers.size(); i++){
d = d + defendingNumbers.get(i) + ", ";
}
d=d.substring(0,d.length()-2);
view.setLabel("Player " + model.getCurrentPlayer() + " rolls " + a + ". Player " + model.getDefendingSelectedSquare().getPlayer() + " rolls " + d + ".");
model.clearRollNumbers();
//If the attacker won and the defender has no troops left
if(model.getDefendingSelectedSquare().getTroopNumber() <= 0){
model.getDefendingSelectedSquare().setPlayer(model.getAttackingSelectedSquare().getPlayer());
model.setPrintNum(model.getAttackingSelectedSquare().getTroopNumber()-1);
model.setIsAttacking(false);
model.setAttackMoving(true);
model.setPaintSliderBoard(true);
view.setLabel("Player " + model.getCurrentPlayer() + " captured " + model.getDefendingSelectedSquare().getName() + ". Choose how many troops to move to the captured territory.");
}
//If the attackers are down to one troop
else if(model.getAttackingSelectedSquare().getTroopNumber() == 1){
model.setIsAttacking(false);
model.setIsAttackPhase(true);
view.setLabel("Player " + model.getCurrentPlayer() + "'s attack on " + model.getDefendingSelectedSquare().getName() + " failed. You may now attack again or end combat.");
resetSquares();
}
//You shouldn't be able to get here but it doesn't hurt to leave this here
else if(model.getAttackingSelectedSquare().getTroopNumber() == 0){
System.out.println("Attacking Troop number equals 0. This shouldnt happen.");
}
}
public void selectTroopsToMove(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() == model.getCurrentPlayer()){
if(tempSquare.getTroopNumber() > 1){
tempSquare.setIsSelected(true);
model.setAttackingSelectedSquare(tempSquare);
model.setIsMoving(false);
model.setisSelectingWhereToMove(true);
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose where to move your troops.");
}else{
view.setLabel("That square does not have enough troops to move! Choose again.");
}
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " does not own that territory. Move from a territory you own.");
}
}
}
public void whereToMove(MouseEvent m){
TerritorySquare tempSquare = model.isInTerritoryArea(m.getX(), m.getY());
if(tempSquare != null){ //If clicked on a square
if(tempSquare.getPlayer() == model.getCurrentPlayer()){
model.setDefendingSelectedSquare(tempSquare);
if(checkPath(model.getAttackingSelectedSquare())){
tempSquare.setIsSelected(true);
model.setPrintNum(model.getAttackingSelectedSquare().getTroopNumber()-1);
model.setisSelectingWhereToMove(false);
model.setPaintSliderBoard(true);
model.resetIsChecked();
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose how many troops to move.");
}else{
model.resetIsChecked();
model.setDefendingSelectedSquare(null);
view.setLabel("Player " + model.getCurrentPlayer() + " cannot not move to that territory. Move to a territory with a direct path to it.");
}
}else{
view.setLabel("Player " + model.getCurrentPlayer() + " does not own that territory. Move to a territory you own.");
}
}else{
model.setTerritorySelected(false);
model.setIsMoving(true);
resetSquares();
view.setLabel("Player " + model.getCurrentPlayer() + " is moving. Choose where to move from or skip moving.");
}
}
public void confirmMoveTroops(MouseEvent m){
if(isConfirm(m.getX(), m.getY())){
model.getAttackingSelectedSquare().setTroopNumber(model.getAttackingSelectedSquare().getTroopNumber() - model.getPrintNum());
model.getDefendingSelectedSquare().setTroopNumber(model.getDefendingSelectedSquare().getTroopNumber() + model.getPrintNum());
if(model.getAttackMoving()){
model.setPaintSliderBoard(false);
model.setIsAttackPhase(true);
model.setAttackMoving(false);
view.setLabel("Player " + model.getCurrentPlayer() + " moved troops to " + model.getDefendingSelectedSquare().getName() + ". Attack again or end combat.");
resetSquares();
return;
}
}if(isCancel(m.getX(), m.getY())){
if(model.getAttackMoving()){
model.getAttackingSelectedSquare().setTroopNumber(model.getAttackingSelectedSquare().getTroopNumber() - 1);
model.getDefendingSelectedSquare().setTroopNumber(1);
model.setIsAttackPhase(true);
view.setLabel("Player " + model.getCurrentPlayer() + " moved only 1 troop to " + model.getDefendingSelectedSquare().getName() + ". Attack again or end combat.");
model.setisSelectingWhereToMove(false);
model.setPaintSliderBoard(false);
resetSquares();
return;
}else{
model.setIsMoving(true);
model.setisSelectingWhereToMove(false);
model.setPaintSliderBoard(false);
resetSquares();
view.setLabel("Player " + model.getCurrentPlayer() + " cancelled their move. Move again or skip moving.");
return;
}
}
if(isConfirm(m.getX(), m.getY()) && !model.getAttackMoving()){
model.setisSelectingWhereToMove(false);
model.setPaintSliderBoard(false);
nextTurn();
}
}
////////////////////////////////// END OF PLAYER TURN PHASES //////////////////////////////////////////////////////////////////////////////////////
public void mouseClicked(MouseEvent m) {
// First check to see if the game is over
if(model.checkGameOver()){
view.setLabel("Player " + model.getCurrentPlayer() + " has achieved world domination!");
model.setPaintSliderBoard(false);
model.setAttackMoving(false);
model.setIsMoving(false);
try{
model.getDefendingSelectedSquare().setTroopNumber(1);
model.getAttackingSelectedSquare().setTroopNumber(model.getAttackingSelectedSquare().getTroopNumber()-1);
}catch(NullPointerException e){};
resetSquares();
//Now check if they are still choosing territories
}else if(model.getIsChoosing()){
chooseTerritory(m);
//Check if they are distributing
}else if(model.getIsDistributing()){
firstDistributeToTerritory(m);
//Check if its a turn
}else if(model.getIsTurn()){
//Check if they are reinforcing
if(model.getIsReinforcing()){
distributeReinforcements(m);
//If they aren't reinforcing check to see if it is now the attack phase
}else if(model.getIsAttackPhase()){
//Check if they clicked the skip button
if(isSkipButton(m.getX(), m.getY())){
resetSquares();
model.setIsAttacking(false);
model.setIsAttackPhase(false);
model.setIsMoving(true);
view.setLabel("Player " + model.getCurrentPlayer() + ": Choose a country to move from or skip moving.");
}
attackPhase(m);
//If the first territory is selected to attack from
}else if(model.getTerritorySelected()){
selectTerritoryToAttack(m);
//If both the attacking territory and the territory being attacked are selected
}else if(model.getIsAttacking()){
//If they are rolling
if(isRoll(m.getX(), m.getY())){
makeRoll();
//If they are retreating
}else if(isRetreat(m.getX(), m.getY())){
resetSquares();
model.clearRollNumbers();
model.setIsAttacking(false);
model.setIsAttackPhase(true);
view.setLabel("Player " + model.getCurrentPlayer() + " retreats. You may now attack again or end combat.");
}
//If it is the moving phase
}else if(model.getIsMoving()){
//If they skip moving
if(isSkipButton(m.getX(), m.getY())){
model.setIsMoving(false);
nextTurn();
//If they are selecting what territory to move from
}else{
selectTroopsToMove(m);
}
//If they are selecting where to move to
}else if(model.getisSelectingWhereToMove()){
//If they skip moving
if(isSkipButton(m.getX(), m.getY())){
resetSquares();
model.setIsMoving(false);
nextTurn();
//select where to move
}else{
whereToMove(m);
}
//Paint the slider board for either post-combat movement or end of turn troop movement
}else if(model.getPaintSliderBoard()){
confirmMoveTroops(m);
}
}
//Repaint the screen
view.repaint();
}
public void stateChanged(ChangeEvent meow) {
//If the slider is changed
model.setPrintNum(view.getSlider().getValue());
view.repaint();
}
public void resetSquares(){
// Resets attacking and defending squares back to null so none are selected
try{
model.getAttackingSelectedSquare().setIsSelected(false);
model.getDefendingSelectedSquare().setIsSelected(false);
}
catch(NullPointerException e){}
model.setAttackingSelectedSquare(null);
model.setDefendingSelectedSquare(null);
}
public void nextTurn(){
//Sets up the next turn
resetSquares();
model.setCurrentPlayer(model.getCurrentPlayer() + 1);
if(model.getCurrentPlayer() > model.getPlayers()){
model.setCurrentPlayer(1);
}
turnSetUp();
}
public boolean checkPath(TerritorySquare square){
//Recursively checks to see if there is one player can move troops from one territory to another
//There has to be a direct path between the two countries
square.setChecked(true);
if(model.getDefendingSelectedSquare().getName().equals(square.getName())){
return true;
}
boolean localCheck = false;
int iterator = 0;
for(TerritorySquare s : square.getLinks()){
if(s.getPlayer() == model.getCurrentPlayer() && (!s.getChecked())){
iterator++;
localCheck = checkPath(s);
if(localCheck){
return true;
}
}
if(iterator == square.getLinks().size()){
return false;
}
}
return localCheck;
}
///////////////////////////////////// AND NOW FOR SOMETHING COMPLETELY DIFFERENT ////////////////////////////////
// Dealing with buttons and sub routines Java makes me include
public boolean isRoll(int x, int y){
return((x >= 480) && (x <= 580) && (y >= 500) && (y <= 550));
}
public boolean isRetreat(int x, int y){
return((x >= 610) && (x <= 710) && (y >= 500) && (y <= 550));
}
public boolean isSkipButton(int x, int y){
return((x >= 8) && (x <= 108) && (y >= 740) && (y <= 790));
}
public boolean isConfirm(int x, int y){
return((x >= 479) && (x <= 580) && (y >= 509) && (y <= 560));
}
public boolean isCancel(int x, int y){
return((x >= 609) && (x <= 710) && (y >= 509) && (y <= 560));
}
public void nextPlayer(){
model.setCurrentPlayer(model.getCurrentPlayer()+1);
}
public void decrementTroops(){
model.setPlayerCurTroops(model.getCurrentPlayer(), model.getPlayerCurTroops(model.getCurrentPlayer()) - 1);
}
public void mouseEntered(MouseEvent m) {}
public void mouseExited(MouseEvent m) {}
public void mousePressed(MouseEvent m) {}
public void mouseReleased(MouseEvent m) {}
}
|
package com.stive;
import java.util.LinkedList;
import java.util.StringTokenizer;
/**
* ๅๅ่ฟ็ฎ + - * /
*
* @author stive 2019/4/23 14:40
*/
public class Arithmetic {
private LinkedList<Integer> optNumsStack = new LinkedList<>(); //ๆไฝๆฐๆ
private LinkedList<String> optSymbolStack = new LinkedList<>(); //ๆไฝ็ฌฆๆ
public int cal(String calStr) {
if (calStr == null || "".equals(calStr)) throw new RuntimeException("้ๆณ่กจ่พพๅผ");
calStr = calStr.replaceAll("[\\s\\n\\t\\r]", "");
boolean matches = calStr.matches("(\\d+[+*/\\\\-]\\d+)*([+*/\\\\-]\\d+)*");
if (!matches) throw new RuntimeException(String.format("้ๆณ่กจ่พพๅผ%s", calStr));
if (calStr.startsWith("-") || calStr.startsWith("+")) calStr = "0" + calStr;
parseString(calStr);
return calRemain();
}
private void parseString(String calStr) {
StringTokenizer tokenizer = new StringTokenizer(calStr, "+-*/", true);
boolean caling = false; //ๆฏๅฆๅจไธๆฌก่ฟ่ก่ฎก็ฎ
while (tokenizer.hasMoreTokens()) {
String s = tokenizer.nextToken();
if (s.matches("\\d+")) {
optNumsStack.addLast(Integer.valueOf(s));
if (caling) { //้ฆๅ
่ฎก็ฎไน้คๅนถๅ
ฅๆ
int b = optNumsStack.removeLast();
int a = optNumsStack.removeLast();
String opt = optSymbolStack.removeLast();
optNumsStack.addLast(cal(a, b, opt));
}
} else {
if (s.matches("[*/]")) {
caling = true; // * /ๆถไธๆฌก้่ฆ่ฟ่ก่ฎก็ฎ
}
optSymbolStack.addLast(s);
}
}
}
private int cal(int a, int b, String opt) {
if ("+".equals(opt)) {
return a + b;
}
if ("-".equals(opt)) {
return a - b;
}
if ("*".equals(opt)) {
return a * b;
}
if ("/".equals(opt)) {
return a / b;
}
return 0;
}
private int calRemain() {
while (optSymbolStack.size() > 0) {
int a = optNumsStack.removeFirst();
int b = optNumsStack.removeFirst();
String opt = optSymbolStack.removeFirst();
optNumsStack.addFirst(cal(a, b, opt));
}
return optNumsStack.removeFirst();
}
}
|
package leetCode.copy.lcci;
import java.util.HashMap;
import java.util.HashSet;
/**
* ้ข่ฏ้ข 01.01. ๅคๅฎๅญ็ฌฆๆฏๅฆๅฏไธ
* ๅฎ็ฐไธไธช็ฎๆณ๏ผ็กฎๅฎไธไธชๅญ็ฌฆไธฒ s ็ๆๆๅญ็ฌฆๆฏๅฆๅ
จ้ฝไธๅใ
*
* ็คบไพ 1๏ผ
* ่พๅ
ฅ: s = "leetcode"
* ่พๅบ: false
*
* ็คบไพ 2๏ผ
* ่พๅ
ฅ: s = "abc"
* ่พๅบ: true
*
* ้ๅถ๏ผ
* 0 <= len(s) <= 100
* ๅฆๆไฝ ไธไฝฟ็จ้ขๅค็ๆฐๆฎ็ปๆ๏ผไผๅพๅ ๅใ
*
* ้พๆฅ๏ผhttps://leetcode-cn.com/problems/is-unique-lcci
*/
public class s_unique_lcci {
/**
* ้ข็ฎไธญๆๆฒกๆไบคไปฃๅญ็ฌฆไธฒ็ๅญ็ฌฆไธๅฎๆฏ26ไธช่ฑๆๅญๆฏ๏ผๆไปฅๆๅฅฝไธๅฅฝ็จarray[26]ๆฅๅ
* ้ข่ฏ่
ไธ่ฆๆฅไบ่งฃ็ญ ๅค้ฎๆธ
ๆฅ็บฆๆๆกไปถ
* @param astr
* @return
*/
public boolean isUnique(String astr) {
if (astr == null || astr.isEmpty()) return true;
HashSet<Character> map = new HashSet<>();
for (char ch : astr.toCharArray()) {
if (map.contains(ch)) {
return false;
}
map.add(ch);
}
return true;
}
public static void main(String args[]){
int result = 5 ^6^ 7^5;
System.out.println(result);
result = 5^7 ^ 6;
System.out.println(result);
System.out.println();
}
}
|
package com.harikesh.smsaesdecrypt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class MainActivity extends AppCompatActivity {
EditText key, Emsg;
Button dec;
String sKey, sMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
key = findViewById(R.id.key);
Emsg = findViewById(R.id.msg);
dec = findViewById(R.id.decrypt);
dec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sKey = key.getText().toString();
sMsg = Emsg.getText().toString();
Log.d("msg", sMsg);
Log.d("key", sKey);
if (sMsg.isEmpty() || sKey.isEmpty()) {
Toast.makeText(MainActivity.this, "Enter all fields", Toast.LENGTH_SHORT).show();
} else {
try {
byte msg[] = hex2byte(sMsg.getBytes());
byte result[] = decryptSMS(sKey, msg);
String ans = new String(result);
Emsg.setText(ans);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
public static byte[] decryptSMS(String sKey, byte[] msg) throws Exception {
Key key = generateKey(sKey);
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, key);
byte[] decValue = c.doFinal(msg);
return decValue;
}
private static Key generateKey(String sKey) {
Key key = new SecretKeySpec(sKey.getBytes(), "AES");
return key;
}
public static byte[] hex2byte(byte[] bytes) {
if ((bytes.length % 2) != 0) {
throw new IllegalArgumentException("hello");
}
byte[] b2 = new byte[bytes.length / 2];
for (int i = 0; i < bytes.length; i += 2) {
String item = new String(bytes, i, 2);
b2[i / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
}
|
package inven;
import java.util.Date;
/**
* UserInfo
*
* @author : jwt1029
* @date : 2019-05-13
* @description :
*/
public class UserInfo {
String userName;
Date lastScanDate;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Date getLastScanDate() {
return lastScanDate;
}
public void setLastScanDate(Date lastScanDate) {
this.lastScanDate = lastScanDate;
}
}
|
package com.amdocs.training;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.amdocs.training.dao.UserDAO;
import com.amdocs.training.dao.impl.UserDAOImpl;
import com.amdocs.training.model.User;
class UserDAOJUnitTest {
static User user = null;
static UserDAO dao = null;
@BeforeAll
public static void init() {
user = new User();
dao = new UserDAOImpl();
System.out.println("Object Created");
}
@Test
public void test_insert_user_success() {
User u = new User(null, "Rahul", "9586234712" ,"rahul@gmail.com","banglore","2021-12-21","rahul","img1.jpg");
assertEquals(true, dao.saveUser(u));
}
@Test
public void test_get_user_by_id_success() {
assertEquals("Raj", dao.getUserById(120).getName());
}
@Test
public void test_get_all_users_success() {
assertEquals(13, dao.findAll().size());
}
@Test
public void test_delete_user_success() {
assertEquals(true, dao.deleteUser(120));
}
@AfterAll
public static void init1() {
user = null;
dao = null;
System.out.println("Object Destroyed");
}
} |
package com.cs.devcode;
import com.cs.payment.Currency;
import com.cs.payment.DCEventType;
import com.cs.payment.DCPaymentTransaction;
import com.cs.payment.Money;
import com.google.common.base.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.math.BigDecimal;
import java.util.Date;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Hadi Movaghar
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class TransferRequest {
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.userId.notNull")
private String userId;
@XmlElement
@Nullable
private String authCode;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.txAmount.notNull")
private BigDecimal txAmount;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.txAmountCy.notNull")
private String txAmountCy;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.txId.notNull")
private String txId;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.txTypeId.notNull")
private Integer txTypeId;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.txName.notNull")
private String txName;
@XmlElement
@Nullable
private String refTxId;
@XmlElement
@Nonnull
@NotNull(message = "transferRequest.provider.notNull")
private String provider;
@XmlElement
@Nullable
private String accountId;
@XmlElement
@Nullable
private String maskedAccount;
@XmlElement
@Nullable
private Attributes attributes;
@XmlElement
@Nonnull
private BigDecimal fee;
@XmlElement
@Nonnull
private String feeCy;
@XmlElement
@Nonnull
private BigDecimal txPspAmount;
@XmlElement
@Nonnull
private String txPspAmountCy;
public TransferRequest() {
}
@Nonnull
public String getUserId() {
return userId;
}
public DCPaymentTransaction getDCPaymentTransaction() {
final DCPaymentTransaction dcPaymentTransaction = new DCPaymentTransaction();
dcPaymentTransaction.setDcEventType(DCEventType.TRANSFER);
dcPaymentTransaction.setAuthorizationCode(authCode);
dcPaymentTransaction.setAmount(new Money(txAmount));
dcPaymentTransaction.setCurrency(Currency.valueOf(txAmountCy));
dcPaymentTransaction.setTransactionId(txId);
dcPaymentTransaction.setTransactionType(txTypeId);
dcPaymentTransaction.setTransactionName(txName);
dcPaymentTransaction.setOriginalTransaction(refTxId);
dcPaymentTransaction.setTransactionProvider(provider);
dcPaymentTransaction.setAccountId(accountId);
dcPaymentTransaction.setMaskedAccount(maskedAccount);
dcPaymentTransaction.setAttributes(attributes != null ? attributes.getAllAttributes() : null);
dcPaymentTransaction.setBonusCode(attributes != null ? attributes.getBonusId() : null);
dcPaymentTransaction.setFee(new Money(fee));
dcPaymentTransaction.setFeeCurrency(Currency.valueOf(feeCy));
dcPaymentTransaction.setPspAmount(new Money(txPspAmount));
dcPaymentTransaction.setPspCurrency(Currency.valueOf(txPspAmountCy));
dcPaymentTransaction.setCreatedDate(new Date());
dcPaymentTransaction.setSuccess(true);
return dcPaymentTransaction;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("userId", userId)
.add("authCode", authCode)
.add("txAmount", txAmount)
.add("txAmountCy", txAmountCy)
.add("txId", txId)
.add("txTypeId", txTypeId)
.add("txName", txName)
.add("refTxId", refTxId)
.add("provider", provider)
.add("accountId", accountId)
.add("maskedAccount", maskedAccount)
.add("attributes", attributes)
.add("fee", fee)
.add("feeCY", feeCy)
.add("txPspAmount", txPspAmount)
.add("txPspAmountCy", txPspAmountCy)
.toString();
}
}
|
package ffadilaputra.org.cobaretrofit.services;
import ffadilaputra.org.cobaretrofit.model.ChuckNorrisQuote;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by ardha_winata on 22-Nov-17.
*/
public interface ChuckServices {
@GET("jokes/random")
Call<ChuckNorrisQuote> getQuote();
}
|
package com.platform.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.platform.au.dao.AuDao;
import com.platform.au.entity.LoginLog;
import com.platform.au.entity.Role;
import com.platform.au.service.AuService;
import com.platform.au.service.UserService;
import com.platform.session.SessionVariable;
import net.sf.json.JSONObject;
/**
* ๅนณๅฐ้
็ฝฎๆไปถๅ ่ฝฝๅทฅๅ
ท็ฑป
*
*/
public class LoginInitUtil {
public static HashMap<String, String> loginLog = new HashMap<String, String>(); // ๅนณๅฐ่ฎฐๅฝ็็ปๅฝ่ฎฐๅฝ
public static HashMap<String, String> userRoleMap = new HashMap<String, String>();// ็จๆทๅฝๅไฝฟ็จ่ง่ฒ
/**
* ๅๅงๅSessionๅ้
*
* @param request
* Http่ฏทๆฑ
* @param response
* Httpๅๅบ
* @param userId
* ็ปๅฝ็จๆทID
* @param userName
* ็ปๅฝ็จๆทๅ
* @param loginId
* ็จๆท็ปๅฝId
* @param needWriteCookie
* ๆฏๅฆ้่ฆๅๅ
ฅcookie
*/
@SuppressWarnings("unchecked")
public static void initSession(HttpServletRequest request,
HttpServletResponse response, String userId, String userName,
String loginId, boolean needWriteCookie) {
HashMap<String, String> sessionVars = null;
HttpSession session = request.getSession();
sessionVars = (HashMap<String, String>) session
.getAttribute(SessionVariable.SESSION_VARS);
if (sessionVars == null) {
sessionVars = new HashMap<String, String>();
}
String tempUserId = userId;
String tempUserName = userName;
UserService userService = SpringUtil.getBean("userServiceImpl", UserService.class);
if (tempUserId == null) {
tempUserId = userService.getUserIdByName(userName);
}
if (tempUserName == null) {
tempUserName = userService.getUserNameById(userId);
}
if (userService == null)
userService = SpringUtil.getBean("userServiceImpl", UserService.class);
String empName = userService.getUserEmpNameById(tempUserId);
sessionVars.put(SessionVariable.userName, tempUserName);
sessionVars.put(SessionVariable.userId, tempUserId);
sessionVars.put(SessionVariable.empName, empName);
AuService auService = SpringUtil.getBean("auServiceImpl", AuService.class);
//String funcLogFlag = getSystemParamVal(PfConstants.FUNC_LOG_FLAG);
boolean isResetPassword = auService.isResetPassword(tempUserId);
boolean isIneffective = auService.isIneffectivePassword(tempUserId);
boolean hasDefineDefaultRole = auService
.isDefineDefaultRole(tempUserId);
//sessionVars.put(SessionVariable.FUNC_LOG_FLAG, funcLogFlag);
sessionVars.put(SessionVariable.isResetPassword,
Boolean.toString(isResetPassword));
sessionVars.put(SessionVariable.isIneffective,
Boolean.toString(isIneffective));
sessionVars.put(SessionVariable.hasDefineDefaultRole,
Boolean.toString(hasDefineDefaultRole));
String roleId = getUserRole(tempUserId);
String defaultRoleId = auService.getDefaultRoleByUserId(tempUserId);
Role role = null;
if (roleId != null && !"".equals(roleId))
role = auService.getRoleById(roleId);
if ((defaultRoleId != null && !"".equals(defaultRoleId))
&& role == null) {
role = auService.getRoleById(defaultRoleId);
}
if (role != null) {
sessionVars.put(SessionVariable.roleId, role.getRole_id());
sessionVars.put(SessionVariable.roleCode, role.getRole_code());
sessionVars.put(SessionVariable.roleName, role.getRole_name());
setUserRole(tempUserId, role.getRole_id());
}
sessionVars.put(SessionVariable.recordLoginId, loginId);
session.setAttribute(SessionVariable.SESSION_VARS, sessionVars);
String touchPersonalSet = ConfigLoadUtil.getParamVal(
"TOUCH_PERSONAL_SET", null, null, tempUserId);
if (touchPersonalSet != null && !"".equals(touchPersonalSet)) {
JSONObject ps = JSONObject.fromObject(touchPersonalSet);
String theme = ps.getString("theme");
if (!StringUtil.isEmpty(theme)) {
session.setAttribute("sys.touchTheme", theme);
}
}
String loginName = null;
try {
loginName = URLEncoder.encode(tempUserName, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (needWriteCookie) {
//String casServerUrl = getCasServer();
String encServerUrl = "";
try {
encServerUrl = URLEncoder.encode(ConfigLoadUtil.getServer(), "UTF-8");
} catch (UnsupportedEncodingException e) {
encServerUrl = "";
}
Cookie loginCookie = new Cookie("AcLogin." + encServerUrl,
loginName);
loginCookie.setPath("/");
response.addCookie(loginCookie);
Cookie loginIdCookie = new Cookie("AcLoginId." + encServerUrl,
loginId);
loginIdCookie.setPath("/");
response.addCookie(loginIdCookie);
}
}
public static void outPrint(HttpServletResponse response, String rData) {
// ่ฎพ็ฝฎ็ผ็ ๆ ผๅผ
rData = rData.replaceAll("\\n", "");
rData = rData.replaceAll("\\r", "");
response.setContentType("text/html;charset=utf-8");
try {
// ่พๅบJSONไธฒ
response.getWriter().write(rData);
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* ่ทๅIP
*
* @param request
* @return
*/
public static String getRemoteHost(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
/**
* ๅฐ็จๆท็จๆท็ปๅฝIdๅ็จๆทๅๅๅ
ฅ็ปๅฝ่ฎฐๅฝ็HashMapไธญ
*/
public static void putLoginLog(String loginId, String userName) {
loginLog.put(userName, loginId);
}
/**
* ็ปๅฝๅๅงๅSessionๅ้๏ผ็จๆทๅๅ็จๆทIDไธคไธชๅฟ
้กปไผ ๅ
ฅไธไธช
*/
public static void loginInit(HttpServletRequest request,
HttpServletResponse response, String userId, String userName,
String loginType, boolean needWriteLoginLog, boolean needWriteCookie) {
String tempUserId = null;
String tempUserName = null;
UserService userService = SpringUtil.getBean("userServiceImpl", UserService.class);
tempUserId = userId;
tempUserName = userName;
if (userId == null) {
tempUserId = userService.getUserIdByName(userName);
}
if (userName == null) {
tempUserName = userService.getUserNameById(userId);
}
String ip = getRemoteHost(request);
String loginId = UUID.randomUUID().toString();
Date loginDate = new Date();
String terminal_name = "";
String terminal_ip = ip;
String os_user = "";
String session_id = request.getSession().getId();
LoginLog log = new LoginLog();
log.setLogin_id(loginId);
log.setUserId(tempUserId);
log.setLoginDate(loginDate);
log.setTerminal_name(terminal_name);
log.setTerminal_ip(terminal_ip);
log.setOs_user(os_user);
log.setSession_id(session_id);
log.setLogin_type(loginType);
AuDao auDao = SpringUtil.getBean("auDao", AuDao.class);
try {
auDao.insertLoginLog(log);
} catch (Exception e) {
e.printStackTrace();
}
if (needWriteLoginLog) {
putLoginLog(loginId, tempUserName);
}
initSession(request, response, tempUserId, tempUserName, loginId,
needWriteCookie);
}
/**
* ๅขๅ ็ปๅฝๆฅๅฟ
*/
public static void addLoginLog(HttpServletRequest request,
HttpServletResponse response, String userId, String userName,
String loginType) {
String tempUserId = null;
String tempUserName = null;
UserService userService = SpringUtil.getBean("userServiceImpl", UserService.class);
tempUserId = userId;
tempUserName = userName;
if (userId == null) {
tempUserId = userService.getUserIdByName(userName);
}
if (userName == null) {
tempUserName = userService.getUserNameById(userId);
}
String ip = getRemoteHost(request);
String loginId = UUID.randomUUID().toString();
Date loginDate = new Date();
String terminal_name = "";
String terminal_ip = ip;
String os_user = "";
String session_id = request.getSession().getId();
LoginLog log = new LoginLog();
log.setLogin_id(loginId);
log.setUserId(tempUserId);
log.setLoginDate(loginDate);
log.setTerminal_name(terminal_name);
log.setTerminal_ip(terminal_ip);
log.setOs_user(os_user);
log.setSession_id(session_id);
log.setLogin_type(loginType);
AuDao auDao = SpringUtil.getBean("auDao", AuDao.class);
try {
auDao.insertLoginLog(log);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ๅฐ็จๆท็่ง่ฒๅๅ
ฅๅ
ๅญๅ้HashMapไธญ
*/
public static void setUserRole(String userId, String roleId) {
userRoleMap.put(userId, roleId);
}
/**
*ๆ นๆฎ็จๆทID่ทๅ่ฏฅ็จๆทๅฝๅๆไฝฟ็จ็่ง่ฒ
*/
public static String getUserRole(String userId) {
return userRoleMap.get(userId);
}
} |
package com.mvc.baseinterface;
public class InterfaceDispatcher {
IEventInterface iEventInterface;
//ๆทปๅ ็ๅฌๅจ
public void addEventListener(IEventInterface iEventInterface){
this.iEventInterface =iEventInterface;
}
//็ป็ๅฌไบไปถๆทปๅ ไบไปถ
public void fireOut(int event, String data){
iEventInterface.onEvent(event, data);
}
}
|
package com.gsccs.sme.plat.auth.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.gsccs.sme.plat.auth.model.Role;
import com.gsccs.sme.plat.auth.model.User;
import com.gsccs.sme.plat.auth.service.ResourceService;
import com.gsccs.sme.plat.auth.service.RoleService;
import com.gsccs.sme.plat.bass.Datagrid;
import com.gsccs.sme.plat.bass.JsonMsg;
/*
* ็ณป็ป่ง่ฒ็ฎก็
*/
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
private RoleService roleService;
@Autowired
private ResourceService resourceService;
//@RequiresPermissions("role:view")
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("roleList", roleService.findAll());
return "auth/role-list";
}
//@RequiresPermissions("role:view")
@RequestMapping(value = "/datagrid", method = RequestMethod.POST)
@ResponseBody
public Datagrid roleList(User user,
@RequestParam(defaultValue = "") String order,
@RequestParam(defaultValue = "1") int currPage,
@RequestParam(defaultValue = "10") int pageSize, ModelMap map,
HttpServletRequest request) {
Datagrid datagrid = new Datagrid();
List<Role> roleList = roleService.findAll();
int count = 0;
if (null != roleList) {
count = roleList.size();
}
datagrid.setRows(roleList);
datagrid.setTotal(Long.valueOf(count));
return datagrid;
}
//@RequiresPermissions("role:create")
@RequestMapping(value = "/dataform", method = RequestMethod.GET)
public String dataform(Long id, Model model) {
setCommonData(model);
if (null != id) {
model.addAttribute("role", roleService.findByRoleid(id));
}
return "auth/role-edit";
}
//@RequiresPermissions("role:create")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public JsonMsg create(Role role, RedirectAttributes redirectAttributes) {
JsonMsg json = new JsonMsg();
roleService.createRole(role);
json.setSuccess(true);
json.setMsg("่ง่ฒๆฐๅขๆๅ!");
return json;
}
//@RequiresPermissions("role:update")
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public JsonMsg update(Role role, RedirectAttributes redirectAttributes) {
JsonMsg json = new JsonMsg();
roleService.updateRole(role);
json.setSuccess(true);
json.setMsg("่ง่ฒไฟกๆฏไฟฎๆนๆๅ!");
return json;
}
/**
* ่ง่ฒๆๆ
* @param roleid
* @param resourceIds
* @param redirectAttributes
* @return
*/
//@RequiresPermissions("role:update")
@RequestMapping(value = "/roleauth", method = RequestMethod.POST)
@ResponseBody
public JsonMsg roleauth(Long roleid,String resourceIds, RedirectAttributes redirectAttributes) {
JsonMsg json = new JsonMsg();
if (null != roleid){
Role role = roleService.findByRoleid(roleid);
role.setResourceIds(resourceIds);
roleService.updateRole(role);
}
json.setSuccess(true);
json.setMsg("่ง่ฒไฟกๆฏไฟฎๆนๆๅ!");
return json;
}
//@RequiresPermissions("role:delete")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public JsonMsg delete(Long id, RedirectAttributes redirectAttributes) {
JsonMsg json = new JsonMsg();
roleService.deleteRole(id);
json.setMsg("ๅ ้คๆๅ");
return json;
}
//@RequiresPermissions("role:create")
@RequestMapping(value = "/authform", method = RequestMethod.GET)
public String authform(Long id, Model model) {
if (null != id) {
model.addAttribute("role", roleService.findByRoleid(id));
}
return "auth/role-auth";
}
private void setCommonData(Model model) {
model.addAttribute("resourceList", resourceService.findAll(null));
}
}
|
package main_package;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author Spencer Ekstrom
* @version May 19, 2020
*/
public class Client implements ActionListener {
JFrame frame;
JPanel main, sub;
GUI gui;
JButton start, end;
Container container;
int[][] board ={{9, 4, 6, 0, 0, 0, 8, 3, 0},
{0, 0, 8, 9, 0, 0, 0, 4, 5},
{0, 7, 3, 0, 0, 2, 1, 9, 6},
{0, 0, 0, 2, 0, 0, 0, 0, 1},
{0, 9, 0, 1, 0, 0, 3, 7, 8},
{8, 0, 0, 0, 0, 0, 4, 0, 0},
{0, 0, 1, 7, 2, 6, 9, 0, 0},
{4, 6, 0, 0, 1, 0, 2, 0, 0},
{2, 8, 0, 0, 9, 0, 6, 0, 3}};;
boolean solved = false;
public Client() {
//Creates the Frame
frame = new JFrame("Sudoku Back-Tracking Visualized");
frame.setSize(615, 675);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creates Container from the Frame
container = frame.getContentPane();
//Creates the GUI
gui = new GUI(board);
//Creates the Start Button
start = new JButton("Start");
start.addActionListener(this);
end = new JButton("End");
end.addActionListener(this);
//Creates the JPanels
main = new JPanel();
sub = new JPanel();
//Sets sizes of panels
main.setSize(600, 700);
sub.setSize(600, 100);
//Adds start button to sub
sub.add(start);
sub.add(end);
//Set the Layout of of the frame
main.setLayout(new BorderLayout());
main.add(gui, BorderLayout.CENTER);
main.add(sub, BorderLayout.SOUTH);
//Add main to the container
container.add(main);
//Show the frame
frame.show();
}
public void runSolve() {
Thread runner = new Thread();
while (!solved) {
try {
runner.sleep(1000);
System.out.println("drawing");
gui.repaint();
solved = solve(board);
printBoard(board);
} catch (InterruptedException e) {}
}
}
public boolean solve(int[][] board) {
Rectangle r = new Rectangle(0, 0, 700, 700);
gui.paintImmediately(r);
int roww;
int coll;
Thread runner = new Thread();
//Base Case
int[] findempty = findEmpty(board);
if (findempty[0] == -1 && findempty[1] == -1) {
return true;
} else {
roww = findempty[0];
coll = findempty[1];
gui.updateBoard(board);
}
for (int val = 1; val <= 9; val++) {
try {
runner.sleep(10);
}catch(Exception e){}
if (validPlacement(board, roww, coll, val)) {
board[roww][coll] = val;
if (solve(board)) {
return true;
}
board[roww][coll] = 0;
gui.updateBoard(board);
}
}
return false;
}
public int[] findEmpty(int[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
int[] ret = new int[2];
ret[0] = i;
ret[1] = j;
return ret;
}
}
}
int[] ret = new int[2];
ret[0] = -1;
ret[1] = -1;
return ret;
}
public boolean validPlacement(int[][] board, int row, int col, int val) {
//Checks for invalidities in it's row
for (int i = 0; i < 9; i++) {
if (i != col && board[row][i] == val) {
return false;
}
}
//Checks Invalidities in it's column
for (int i = 0; i < 9; i++) {
if (i != row && board[i][col] == val) {
return false;
}
}
int box_x = row / 3;
int box_y = col / 3;
for (int ro = box_x * 3; ro < box_x * 3 + 3; ro++) {
for (int co = box_y * 3; co < box_y * 3 + 3; co++) {
if (board[ro][co] == val) {
return false;
}
}
}
//If it get's here, it's a valid placement
return true;
}
public void printBoard(int[][] board) {
System.out.println("+------+------+------+");
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (j == 0) {
System.out.print("|");
}
if (j == 3) {
System.out.print("|");
}
if (j == 6) {
System.out.print("|");
}
System.out.print(board[i][j] + " ");
if (j == 8) {
System.out.print("|");
}
}
System.out.println("");
if (i == 2) {
System.out.println("+------+------+------+");
}
if (i == 5) {
System.out.println("+------+------+------+");
}
}
System.out.println("+------+------+------+");
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == start) {
runSolve();
}
if(evt.getSource() == end) {
frame.dispose();
}
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 art;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Base64;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
import static art.SuspendEvents.setupTest;
import static art.SuspendEvents.setupSuspendBreakpointFor;
import static art.SuspendEvents.clearSuspendBreakpointFor;
import static art.SuspendEvents.setupSuspendSingleStepAt;
import static art.SuspendEvents.setupFieldSuspendFor;
import static art.SuspendEvents.setupSuspendMethodEvent;
import static art.SuspendEvents.setupSuspendExceptionEvent;
import static art.SuspendEvents.setupSuspendPopFrameEvent;
import static art.SuspendEvents.EVENT_TYPE_CLASS_LOAD;
import static art.SuspendEvents.EVENT_TYPE_CLASS_PREPARE;
import static art.SuspendEvents.setupSuspendClassEvent;
public class Test1953 {
public final boolean canRunClassLoadTests;
public static void doNothing() {}
public interface TestRunnable extends Runnable {
public int getBaseCallCount();
public Method getCalledMethod() throws Exception;
public default Method getCallingMethod() throws Exception {
return this.getClass().getMethod("run");
};
}
public static interface TestSuspender {
public void setup(Thread thr);
public void waitForSuspend(Thread thr);
public void cleanup(Thread thr);
}
public static interface ThreadRunnable { public void run(Thread thr); }
public static TestSuspender makeSuspend(final ThreadRunnable setup, final ThreadRunnable clean) {
return new TestSuspender() {
public void setup(Thread thr) { setup.run(thr); }
public void waitForSuspend(Thread thr) { SuspendEvents.waitForSuspendHit(thr); }
public void cleanup(Thread thr) { clean.run(thr); }
};
}
public void runTestOn(TestRunnable testObj, ThreadRunnable su, ThreadRunnable cl) throws
Exception {
runTestOn(testObj, makeSuspend(su, cl));
}
private static void SafePrintStackTrace(StackTraceElement st[]) {
for (StackTraceElement e : st) {
System.out.println("\t" + e.getClassName() + "." + e.getMethodName() + "(" +
(e.isNativeMethod() ? "Native Method" : e.getFileName()) + ")");
if (e.getClassName().equals("art.Test1953") && e.getMethodName().equals("runTests")) {
System.out.println("\t<Additional frames hidden>");
break;
}
}
}
public void runTestOn(TestRunnable testObj, TestSuspender su) throws Exception {
System.out.println("Single call with PopFrame on " + testObj + " base-call-count: " +
testObj.getBaseCallCount());
final CountDownLatch continue_latch = new CountDownLatch(1);
final CountDownLatch startup_latch = new CountDownLatch(1);
Runnable await = () -> {
try {
startup_latch.countDown();
continue_latch.await();
} catch (Exception e) {
throw new Error("Failed to await latch", e);
}
};
Thread thr = new Thread(() -> { await.run(); testObj.run(); });
thr.start();
// Wait until the other thread is started.
startup_latch.await();
// Do any final setup.
preTest.accept(testObj);
// Setup suspension method on the thread.
su.setup(thr);
// Let the other thread go.
continue_latch.countDown();
// Wait for the other thread to hit the breakpoint/watchpoint/whatever and suspend itself
// (without re-entering java)
su.waitForSuspend(thr);
// Cleanup the breakpoint/watchpoint/etc.
su.cleanup(thr);
try {
// Pop the frame.
popFrame(thr);
} catch (Exception e) {
System.out.println("Failed to pop frame due to " + e);
SafePrintStackTrace(e.getStackTrace());
}
// Start the other thread going again.
Suspension.resume(thr);
// Wait for the other thread to finish.
thr.join();
// See how many times calledFunction was called.
System.out.println("result is " + testObj + " base-call count: " + testObj.getBaseCallCount());
}
public static abstract class AbstractTestObject implements TestRunnable {
public int callerCnt;
public AbstractTestObject() {
callerCnt = 0;
}
public int getBaseCallCount() {
return callerCnt;
}
public void run() {
callerCnt++;
// This function should be re-executed by the popFrame.
calledFunction();
}
public Method getCalledMethod() throws Exception {
return this.getClass().getMethod("calledFunction");
}
public abstract void calledFunction();
}
public static class RedefineTestObject extends AbstractTestObject implements Runnable {
public static enum RedefineState { ORIGINAL, REDEFINED, };
/* public static class RedefineTestObject extends AbstractTestObject implements Runnable {
* public static final byte[] CLASS_BYTES;
* public static final byte[] DEX_BYTES;
* static {
* CLASS_BYTES = null;
* DEX_BYTES = null;
* }
*
* public EnumSet<RedefineState> redefine_states;
* public RedefineTestObject() {
* super();
* redefine_states = EnumSet.noneOf(RedefineState.class);
* }
* public String toString() {
* return "RedefineTestObject { states: " + redefine_states.toString()
* + " current: REDEFINED }";
* }
* public void calledFunction() {
* redefine_states.add(RedefineState.REDEFINED); // line +0
* // We will trigger the redefinition using a breakpoint on the next line.
* doNothing(); // line +2
* }
* }
*/
public static final byte[] CLASS_BYTES = Base64.getDecoder().decode(
"yv66vgAAADUATQoADQAjBwAkCgAlACYJAAwAJwoAJQAoEgAAACwJAAIALQoAJQAuCgAvADAJAAwA" +
"MQkADAAyBwAzBwA0BwA2AQASUmVkZWZpbmVUZXN0T2JqZWN0AQAMSW5uZXJDbGFzc2VzAQANUmVk" +
"ZWZpbmVTdGF0ZQEAC0NMQVNTX0JZVEVTAQACW0IBAAlERVhfQllURVMBAA9yZWRlZmluZV9zdGF0" +
"ZXMBABNMamF2YS91dGlsL0VudW1TZXQ7AQAJU2lnbmF0dXJlAQBETGphdmEvdXRpbC9FbnVtU2V0" +
"PExhcnQvVGVzdDE5NTMkUmVkZWZpbmVUZXN0T2JqZWN0JFJlZGVmaW5lU3RhdGU7PjsBAAY8aW5p" +
"dD4BAAMoKVYBAARDb2RlAQAPTGluZU51bWJlclRhYmxlAQAIdG9TdHJpbmcBABQoKUxqYXZhL2xh" +
"bmcvU3RyaW5nOwEADmNhbGxlZEZ1bmN0aW9uAQAIPGNsaW5pdD4BAApTb3VyY2VGaWxlAQANVGVz" +
"dDE5NTMuamF2YQwAGQAaAQAtYXJ0L1Rlc3QxOTUzJFJlZGVmaW5lVGVzdE9iamVjdCRSZWRlZmlu" +
"ZVN0YXRlBwA3DAA4ADkMABUAFgwAHQAeAQAQQm9vdHN0cmFwTWV0aG9kcw8GADoIADsMADwAPQwA" +
"PgA/DABAAEEHAEIMAEMAGgwAEgATDAAUABMBAB9hcnQvVGVzdDE5NTMkUmVkZWZpbmVUZXN0T2Jq" +
"ZWN0AQAfYXJ0L1Rlc3QxOTUzJEFic3RyYWN0VGVzdE9iamVjdAEAEkFic3RyYWN0VGVzdE9iamVj" +
"dAEAEmphdmEvbGFuZy9SdW5uYWJsZQEAEWphdmEvdXRpbC9FbnVtU2V0AQAGbm9uZU9mAQAmKExq" +
"YXZhL2xhbmcvQ2xhc3M7KUxqYXZhL3V0aWwvRW51bVNldDsKAEQARQEAM1JlZGVmaW5lVGVzdE9i" +
"amVjdCB7IHN0YXRlczogASBjdXJyZW50OiBSRURFRklORUQgfQEAF21ha2VDb25jYXRXaXRoQ29u" +
"c3RhbnRzAQAmKExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzsBAAlSRURFRklO" +
"RUQBAC9MYXJ0L1Rlc3QxOTUzJFJlZGVmaW5lVGVzdE9iamVjdCRSZWRlZmluZVN0YXRlOwEAA2Fk" +
"ZAEAFShMamF2YS9sYW5nL09iamVjdDspWgEADGFydC9UZXN0MTk1MwEACWRvTm90aGluZwcARgwA" +
"PABJAQAkamF2YS9sYW5nL2ludm9rZS9TdHJpbmdDb25jYXRGYWN0b3J5BwBLAQAGTG9va3VwAQCY" +
"KExqYXZhL2xhbmcvaW52b2tlL01ldGhvZEhhbmRsZXMkTG9va3VwO0xqYXZhL2xhbmcvU3RyaW5n" +
"O0xqYXZhL2xhbmcvaW52b2tlL01ldGhvZFR5cGU7TGphdmEvbGFuZy9TdHJpbmc7W0xqYXZhL2xh" +
"bmcvT2JqZWN0OylMamF2YS9sYW5nL2ludm9rZS9DYWxsU2l0ZTsHAEwBACVqYXZhL2xhbmcvaW52" +
"b2tlL01ldGhvZEhhbmRsZXMkTG9va3VwAQAeamF2YS9sYW5nL2ludm9rZS9NZXRob2RIYW5kbGVz" +
"ACEADAANAAEADgADABkAEgATAAAAGQAUABMAAAABABUAFgABABcAAAACABgABAABABkAGgABABsA" +
"AAAuAAIAAQAAAA4qtwABKhICuAADtQAEsQAAAAEAHAAAAA4AAwAAACEABAAiAA0AIwABAB0AHgAB" +
"ABsAAAAlAAEAAQAAAA0qtAAEtgAFugAGAACwAAAAAQAcAAAABgABAAAAJQABAB8AGgABABsAAAAv" +
"AAIAAQAAAA8qtAAEsgAHtgAIV7gACbEAAAABABwAAAAOAAMAAAApAAsAKwAOACwACAAgABoAAQAb" +
"AAAAKQABAAAAAAAJAbMACgGzAAuxAAAAAQAcAAAADgADAAAAGwAEABwACAAdAAMAIQAAAAIAIgAQ" +
"AAAAIgAEAAwALwAPAAkAAgAMABFAGQANAC8ANQQJAEcASgBIABkAKQAAAAgAAQAqAAEAKw==");
public static final byte[] DEX_BYTES = Base64.getDecoder().decode(
"ZGV4CjAzNQAaR23N6WpunLRVX+BexSuzzNNiHNOvQpFoBwAAcAAAAHhWNBIAAAAAAAAAAKQGAAAq" +
"AAAAcAAAABEAAAAYAQAABQAAAFwBAAAEAAAAmAEAAAwAAAC4AQAAAQAAABgCAAAwBQAAOAIAACID" +
"AAA5AwAAQwMAAEsDAABPAwAAXAMAAGcDAABqAwAAbgMAAJEDAADCAwAA5QMAAPUDAAAZBAAAOQQA" +
"AFwEAAB7BAAAjgQAAKIEAAC4BAAAzAQAAOcEAAD8BAAAEQUAABwFAAAwBQAATwUAAF4FAABhBQAA" +
"ZAUAAGgFAABsBQAAeQUAAH4FAACGBQAAlgUAAKEFAACnBQAArwUAAMAFAADKBQAA0QUAAAgAAAAJ" +
"AAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAGwAAABwA" +
"AAAeAAAABgAAAAsAAAAAAAAABwAAAAwAAAAMAwAABwAAAA0AAAAUAwAAGwAAAA4AAAAAAAAAHQAA" +
"AA8AAAAcAwAAAQABABcAAAACABAABAAAAAIAEAAFAAAAAgANACYAAAAAAAMAAgAAAAIAAwABAAAA" +
"AgADAAIAAAACAAMAIgAAAAIAAAAnAAAAAwADACMAAAAMAAMAAgAAAAwAAQAhAAAADAAAACcAAAAN" +
"AAQAIAAAAA0AAgAlAAAADQAAACcAAAACAAAAAQAAAAAAAAAEAwAAGgAAAIwGAABRBgAAAAAAAAQA" +
"AQACAAAA+gIAAB0AAABUMAMAbhALAAAADAAiAQwAcBAGAAEAGgIZAG4gBwAhAG4gBwABABoAAABu" +
"IAcAAQBuEAgAAQAMABEAAAABAAAAAAAAAPQCAAAGAAAAEgBpAAEAaQACAA4AAgABAAEAAADuAgAA" +
"DAAAAHAQAAABABwAAQBxEAoAAAAMAFsQAwAOAAMAAQACAAAA/gIAAAsAAABUIAMAYgEAAG4gCQAQ" +
"AHEABQAAAA4AIQAOPIcAGwAOPC0AJQAOACkADnk8AAEAAAAKAAAAAQAAAAsAAAABAAAACAAAAAEA" +
"AAAJABUgY3VycmVudDogUkVERUZJTkVEIH0ACDxjbGluaXQ+AAY8aW5pdD4AAj47AAtDTEFTU19C" +
"WVRFUwAJREVYX0JZVEVTAAFMAAJMTAAhTGFydC9UZXN0MTk1MyRBYnN0cmFjdFRlc3RPYmplY3Q7" +
"AC9MYXJ0L1Rlc3QxOTUzJFJlZGVmaW5lVGVzdE9iamVjdCRSZWRlZmluZVN0YXRlOwAhTGFydC9U" +
"ZXN0MTk1MyRSZWRlZmluZVRlc3RPYmplY3Q7AA5MYXJ0L1Rlc3QxOTUzOwAiTGRhbHZpay9hbm5v" +
"dGF0aW9uL0VuY2xvc2luZ0NsYXNzOwAeTGRhbHZpay9hbm5vdGF0aW9uL0lubmVyQ2xhc3M7ACFM" +
"ZGFsdmlrL2Fubm90YXRpb24vTWVtYmVyQ2xhc3NlczsAHUxkYWx2aWsvYW5ub3RhdGlvbi9TaWdu" +
"YXR1cmU7ABFMamF2YS9sYW5nL0NsYXNzOwASTGphdmEvbGFuZy9PYmplY3Q7ABRMamF2YS9sYW5n" +
"L1J1bm5hYmxlOwASTGphdmEvbGFuZy9TdHJpbmc7ABlMamF2YS9sYW5nL1N0cmluZ0J1aWxkZXI7" +
"ABNMamF2YS91dGlsL0VudW1TZXQ7ABNMamF2YS91dGlsL0VudW1TZXQ8AAlSRURFRklORUQAElJl" +
"ZGVmaW5lVGVzdE9iamVjdAAdUmVkZWZpbmVUZXN0T2JqZWN0IHsgc3RhdGVzOiAADVRlc3QxOTUz" +
"LmphdmEAAVYAAVoAAlpMAAJbQgALYWNjZXNzRmxhZ3MAA2FkZAAGYXBwZW5kAA5jYWxsZWRGdW5j" +
"dGlvbgAJZG9Ob3RoaW5nAARuYW1lAAZub25lT2YAD3JlZGVmaW5lX3N0YXRlcwAIdG9TdHJpbmcA" +
"BXZhbHVlAFt+fkQ4eyJtaW4tYXBpIjoxLCJzaGEtMSI6IjUyNzNjM2RmZWUxMDQ2NzIwYWY0MjVm" +
"YTg1NTMxNmM5OWM4NmM4ZDIiLCJ2ZXJzaW9uIjoiMS4zLjE4LWRldiJ9AAIHASgcAxcWFwkXAwIE" +
"ASgYAwIFAh8ECSQXGAIGASgcARgBAgECAgEZARkDAQGIgASEBQGBgASgBQMByAUBAbgEAAAAAAAB" +
"AAAALgYAAAMAAAA6BgAAQAYAAEkGAAB8BgAAAQAAAAAAAAAAAAAAAwAAAHQGAAAQAAAAAAAAAAEA" +
"AAAAAAAAAQAAACoAAABwAAAAAgAAABEAAAAYAQAAAwAAAAUAAABcAQAABAAAAAQAAACYAQAABQAA" +
"AAwAAAC4AQAABgAAAAEAAAAYAgAAASAAAAQAAAA4AgAAAyAAAAQAAADuAgAAARAAAAQAAAAEAwAA" +
"AiAAACoAAAAiAwAABCAAAAQAAAAuBgAAACAAAAEAAABRBgAAAxAAAAMAAABwBgAABiAAAAEAAACM" +
"BgAAABAAAAEAAACkBgAA");
public EnumSet<RedefineState> redefine_states;
public RedefineTestObject() {
super();
redefine_states = EnumSet.noneOf(RedefineState.class);
}
public String toString() {
return "RedefineTestObject { states: " + redefine_states.toString() + " current: ORIGINAL }";
}
public void calledFunction() {
redefine_states.add(RedefineState.ORIGINAL); // line +0
// We will trigger the redefinition using a breakpoint on the next line.
doNothing(); // line +2
}
}
public static class ClassLoadObject implements TestRunnable {
public int cnt;
public int baseCallCnt;
public static final String[] CLASS_NAMES = new String[] {
"Lart/Test1953$ClassLoadObject$TC0;",
"Lart/Test1953$ClassLoadObject$TC1;",
"Lart/Test1953$ClassLoadObject$TC2;",
"Lart/Test1953$ClassLoadObject$TC3;",
"Lart/Test1953$ClassLoadObject$TC4;",
"Lart/Test1953$ClassLoadObject$TC5;",
"Lart/Test1953$ClassLoadObject$TC6;",
"Lart/Test1953$ClassLoadObject$TC7;",
"Lart/Test1953$ClassLoadObject$TC8;",
"Lart/Test1953$ClassLoadObject$TC9;",
};
private static int curClass = 0;
private static class TC0 { public static int foo; static { foo = 1; } }
private static class TC1 { public static int foo; static { foo = 2; } }
private static class TC2 { public static int foo; static { foo = 3; } }
private static class TC3 { public static int foo; static { foo = 4; } }
private static class TC4 { public static int foo; static { foo = 5; } }
private static class TC5 { public static int foo; static { foo = 6; } }
private static class TC6 { public static int foo; static { foo = 7; } }
private static class TC7 { public static int foo; static { foo = 8; } }
private static class TC8 { public static int foo; static { foo = 9; } }
private static class TC9 { public static int foo; static { foo = 10; } }
public ClassLoadObject() {
super();
cnt = 0;
baseCallCnt = 0;
}
public int getBaseCallCount() {
return baseCallCnt;
}
public void run() {
baseCallCnt++;
if (curClass == 0) {
$noprecompile$calledFunction0();
} else if (curClass == 1) {
$noprecompile$calledFunction1();
} else if (curClass == 2) {
$noprecompile$calledFunction2();
} else if (curClass == 3) {
$noprecompile$calledFunction3();
} else if (curClass == 4) {
$noprecompile$calledFunction4();
} else if (curClass == 5) {
$noprecompile$calledFunction5();
} else if (curClass == 6) {
$noprecompile$calledFunction6();
} else if (curClass == 7) {
$noprecompile$calledFunction7();
} else if (curClass == 8) {
$noprecompile$calledFunction8();
} else if (curClass == 9) {
$noprecompile$calledFunction9();
}
curClass++;
}
public Method getCalledMethod() throws Exception {
return this.getClass().getMethod("jnoprecompile$calledFunction" + curClass);
}
// Give these all a tag to prevent 1954 from compiling them (and loading the class as a
// consequence).
public void $noprecompile$calledFunction0() {
cnt++;
System.out.println("TC0.foo == " + TC0.foo);
}
public void $noprecompile$calledFunction1() {
cnt++;
System.out.println("TC1.foo == " + TC1.foo);
}
public void $noprecompile$calledFunction2() {
cnt++;
System.out.println("TC2.foo == " + TC2.foo);
}
public void $noprecompile$calledFunction3() {
cnt++;
System.out.println("TC3.foo == " + TC3.foo);
}
public void $noprecompile$calledFunction4() {
cnt++;
System.out.println("TC4.foo == " + TC4.foo);
}
public void $noprecompile$calledFunction5() {
cnt++;
System.out.println("TC5.foo == " + TC5.foo);
}
public void $noprecompile$calledFunction6() {
cnt++;
System.out.println("TC6.foo == " + TC6.foo);
}
public void $noprecompile$calledFunction7() {
cnt++;
System.out.println("TC7.foo == " + TC7.foo);
}
public void $noprecompile$calledFunction8() {
cnt++;
System.out.println("TC8.foo == " + TC8.foo);
}
public void $noprecompile$calledFunction9() {
cnt++;
System.out.println("TC9.foo == " + TC9.foo);
}
public String toString() {
return "ClassLoadObject { cnt: " + cnt + ", curClass: " + curClass + "}";
}
}
public static class FieldBasedTestObject extends AbstractTestObject implements Runnable {
public int cnt;
public int TARGET_FIELD;
public FieldBasedTestObject() {
super();
cnt = 0;
TARGET_FIELD = 0;
}
public void calledFunction() {
cnt++;
// We put a watchpoint here and PopFrame when we are at it.
TARGET_FIELD += 10;
if (cnt == 1) { System.out.println("FAILED: No pop on first call!"); }
}
public String toString() {
return "FieldBasedTestObject { cnt: " + cnt + ", TARGET_FIELD: " + TARGET_FIELD + " }";
}
}
public static class StandardTestObject extends AbstractTestObject implements Runnable {
public int cnt;
public final boolean check;
public StandardTestObject(boolean check) {
super();
cnt = 0;
this.check = check;
}
public StandardTestObject() {
this(true);
}
public void calledFunction() {
cnt++; // line +0
// We put a breakpoint here and PopFrame when we are at it.
doNothing(); // line +2
if (check && cnt == 1) { System.out.println("FAILED: No pop on first call!"); }
}
public String toString() {
return "StandardTestObject { cnt: " + cnt + " }";
}
}
public static class SynchronizedFunctionTestObject extends AbstractTestObject implements Runnable {
public int cnt;
public SynchronizedFunctionTestObject() {
super();
cnt = 0;
}
public synchronized void calledFunction() {
cnt++; // line +0
// We put a breakpoint here and PopFrame when we are at it.
doNothing(); // line +2
}
public String toString() {
return "SynchronizedFunctionTestObject { cnt: " + cnt + " }";
}
}
public static class SynchronizedTestObject extends AbstractTestObject implements Runnable {
public int cnt;
public final Object lock;
public SynchronizedTestObject() {
this(new Object());
}
public SynchronizedTestObject(Object l) {
super();
cnt = 0;
lock = l;
}
public void calledFunction() {
synchronized (lock) { // line +0
cnt++; // line +1
// We put a breakpoint here and PopFrame when we are at it.
doNothing(); // line +3
}
}
public String toString() {
return "SynchronizedTestObject { cnt: " + cnt + " }";
}
}
public static class ExceptionCatchTestObject extends AbstractTestObject implements Runnable {
public static class TestError extends Error {}
public int cnt;
public ExceptionCatchTestObject() {
super();
cnt = 0;
}
public void calledFunction() {
cnt++;
try {
doThrow();
} catch (TestError e) {
System.out.println(e.getClass().getName() + " caught in called function.");
}
}
public void doThrow() {
throw new TestError();
}
public String toString() {
return "ExceptionCatchTestObject { cnt: " + cnt + " }";
}
}
public static class ExceptionThrowFarTestObject implements TestRunnable {
public static class TestError extends Error {}
public int cnt;
public int baseCallCnt;
public final boolean catchInCalled;
public ExceptionThrowFarTestObject(boolean catchInCalled) {
super();
cnt = 0;
baseCallCnt = 0;
this.catchInCalled = catchInCalled;
}
public int getBaseCallCount() {
return baseCallCnt;
}
public void run() {
baseCallCnt++;
try {
callingFunction();
} catch (TestError e) {
System.out.println(e.getClass().getName() + " thrown and caught!");
}
}
public void callingFunction() {
calledFunction();
}
public void calledFunction() {
cnt++;
if (catchInCalled) {
try {
throw new TestError(); // We put a watch here.
} catch (TestError e) {
System.out.println(e.getClass().getName() + " caught in same function.");
}
} else {
throw new TestError(); // We put a watch here.
}
}
public Method getCallingMethod() throws Exception {
return this.getClass().getMethod("callingFunction");
}
public Method getCalledMethod() throws Exception {
return this.getClass().getMethod("calledFunction");
}
public String toString() {
return "ExceptionThrowFarTestObject { cnt: " + cnt + " }";
}
}
public static class ExceptionOnceObject extends AbstractTestObject {
public static final class TestError extends Error {}
public int cnt;
public final boolean throwInSub;
public ExceptionOnceObject(boolean throwInSub) {
super();
cnt = 0;
this.throwInSub = throwInSub;
}
public void calledFunction() {
cnt++;
if (cnt == 1) {
if (throwInSub) {
doThrow();
} else {
throw new TestError();
}
}
}
public void doThrow() {
throw new TestError();
}
public String toString() {
return "ExceptionOnceObject { cnt: " + cnt + ", throwInSub: " + throwInSub + " }";
}
}
public static class ExceptionThrowTestObject implements TestRunnable {
public static class TestError extends Error {}
public int cnt;
public int baseCallCnt;
public final boolean catchInCalled;
public ExceptionThrowTestObject(boolean catchInCalled) {
super();
cnt = 0;
baseCallCnt = 0;
this.catchInCalled = catchInCalled;
}
public int getBaseCallCount() {
return baseCallCnt;
}
public void run() {
baseCallCnt++;
try {
calledFunction();
} catch (TestError e) {
System.out.println(e.getClass().getName() + " thrown and caught!");
}
}
public void calledFunction() {
cnt++;
if (catchInCalled) {
try {
throw new TestError(); // We put a watch here.
} catch (TestError e) {
System.out.println(e.getClass().getName() + " caught in same function.");
}
} else {
throw new TestError(); // We put a watch here.
}
}
public Method getCalledMethod() throws Exception {
return this.getClass().getMethod("calledFunction");
}
public String toString() {
return "ExceptionThrowTestObject { cnt: " + cnt + " }";
}
}
public static class NativeCalledObject extends AbstractTestObject {
public int cnt = 0;
public native void calledFunction();
public String toString() {
return "NativeCalledObject { cnt: " + cnt + " }";
}
}
public static class NativeCallerObject implements TestRunnable {
public int baseCnt = 0;
public int cnt = 0;
public int getBaseCallCount() {
return baseCnt;
}
public native void run();
public void calledFunction() {
cnt++;
// We will stop using a MethodExit event.
}
public Method getCalledMethod() throws Exception {
return this.getClass().getMethod("calledFunction");
}
public String toString() {
return "NativeCallerObject { cnt: " + cnt + " }";
}
}
public static class SuspendSuddenlyObject extends AbstractTestObject {
public volatile boolean stop_spinning = false;
public volatile boolean is_spinning = false;
public int cnt = 0;
public void calledFunction() {
cnt++;
while (!stop_spinning) {
is_spinning = true;
}
}
public String toString() {
return "SuspendSuddenlyObject { cnt: " + cnt + " }";
}
}
public static void run(boolean canRunClassLoadTests) throws Exception {
new Test1953(canRunClassLoadTests, (x)-> {}).runTests();
}
// This entrypoint is used by CTS only. */
public static void run() throws Exception {
/* TODO: Due to the way that CTS tests are verified we cannot run class-load-tests since the
* verifier will be delayed until runtime and then load the classes all at once. This
* makes the test impossible to run.
*/
run(/*canRunClassLoadTests*/ false);
}
public Test1953(boolean canRunClassLoadTests, Consumer<TestRunnable> preTest) {
this.canRunClassLoadTests = canRunClassLoadTests;
this.preTest = preTest;
}
private Consumer<TestRunnable> preTest;
public void runTests() throws Exception {
setupTest();
final Method calledFunction = StandardTestObject.class.getDeclaredMethod("calledFunction");
final Method doNothingMethod = Test1953.class.getDeclaredMethod("doNothing");
// Add a breakpoint on the second line after the start of the function
final int line = Breakpoint.locationToLine(calledFunction, 0) + 2;
final long loc = Breakpoint.lineToLocation(calledFunction, line);
System.out.println("Test stopped using breakpoint");
runTestOn(new StandardTestObject(),
(thr) -> setupSuspendBreakpointFor(calledFunction, loc, thr),
SuspendEvents::clearSuspendBreakpointFor);
final Method syncFunctionCalledFunction =
SynchronizedFunctionTestObject.class.getDeclaredMethod("calledFunction");
// Add a breakpoint on the second line after the start of the function
// Annoyingly r8 generally has the first instruction (a monitor enter) not be marked as being
// on any line but javac has it marked as being on the first line of the function. Just use the
// second entry on the line-number table to get the breakpoint. This should be good for both.
final long syncFunctionLoc =
Breakpoint.getLineNumberTable(syncFunctionCalledFunction)[1].location;
System.out.println("Test stopped using breakpoint with declared synchronized function");
runTestOn(new SynchronizedFunctionTestObject(),
(thr) -> setupSuspendBreakpointFor(syncFunctionCalledFunction, syncFunctionLoc, thr),
SuspendEvents::clearSuspendBreakpointFor);
final Method syncCalledFunction =
SynchronizedTestObject.class.getDeclaredMethod("calledFunction");
// Add a breakpoint on the second line after the start of the function
final int syncLine = Breakpoint.locationToLine(syncCalledFunction, 0) + 3;
final long syncLoc = Breakpoint.lineToLocation(syncCalledFunction, syncLine);
System.out.println("Test stopped using breakpoint with synchronized block");
Object lock = new Object();
synchronized (lock) {}
runTestOn(new SynchronizedTestObject(lock),
(thr) -> setupSuspendBreakpointFor(syncCalledFunction, syncLoc, thr),
SuspendEvents::clearSuspendBreakpointFor);
synchronized (lock) {}
System.out.println("Test stopped on single step");
runTestOn(new StandardTestObject(),
(thr) -> setupSuspendSingleStepAt(calledFunction, loc, thr),
SuspendEvents::clearSuspendSingleStepFor);
final Field target_field = FieldBasedTestObject.class.getDeclaredField("TARGET_FIELD");
System.out.println("Test stopped on field access");
runTestOn(new FieldBasedTestObject(),
(thr) -> setupFieldSuspendFor(FieldBasedTestObject.class, target_field, true, thr),
SuspendEvents::clearFieldSuspendFor);
System.out.println("Test stopped on field modification");
runTestOn(new FieldBasedTestObject(),
(thr) -> setupFieldSuspendFor(FieldBasedTestObject.class, target_field, false, thr),
SuspendEvents::clearFieldSuspendFor);
System.out.println("Test stopped during Method Exit of doNothing");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendMethodEvent(doNothingMethod, /*enter*/ false, thr),
SuspendEvents::clearSuspendMethodEvent);
// NB We need another test to make sure the MethodEntered event is triggered twice.
System.out.println("Test stopped during Method Enter of doNothing");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendMethodEvent(doNothingMethod, /*enter*/ true, thr),
SuspendEvents::clearSuspendMethodEvent);
System.out.println("Test stopped during Method Exit of calledFunction");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendMethodEvent(calledFunction, /*enter*/ false, thr),
SuspendEvents::clearSuspendMethodEvent);
System.out.println("Test stopped during Method Enter of calledFunction");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendMethodEvent(calledFunction, /*enter*/ true, thr),
SuspendEvents::clearSuspendMethodEvent);
final Method exceptionOnceCalledMethod =
ExceptionOnceObject.class.getDeclaredMethod("calledFunction");
System.out.println("Test stopped during Method Exit due to exception thrown in same function");
runTestOn(new ExceptionOnceObject(/*throwInSub*/ false),
(thr) -> setupSuspendMethodEvent(exceptionOnceCalledMethod, /*enter*/ false, thr),
SuspendEvents::clearSuspendMethodEvent);
System.out.println("Test stopped during Method Exit due to exception thrown in subroutine");
runTestOn(new ExceptionOnceObject(/*throwInSub*/ true),
(thr) -> setupSuspendMethodEvent(exceptionOnceCalledMethod, /*enter*/ false, thr),
SuspendEvents::clearSuspendMethodEvent);
System.out.println("Test stopped during notifyFramePop without exception on pop of calledFunction");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendPopFrameEvent(1, doNothingMethod, thr),
SuspendEvents::clearSuspendPopFrameEvent);
System.out.println("Test stopped during notifyFramePop without exception on pop of doNothing");
runTestOn(new StandardTestObject(false),
(thr) -> setupSuspendPopFrameEvent(0, doNothingMethod, thr),
SuspendEvents::clearSuspendPopFrameEvent);
final Method exceptionThrowCalledMethod =
ExceptionThrowTestObject.class.getDeclaredMethod("calledFunction");
System.out.println("Test stopped during notifyFramePop with exception on pop of calledFunction");
runTestOn(new ExceptionThrowTestObject(false),
(thr) -> setupSuspendPopFrameEvent(0, exceptionThrowCalledMethod, thr),
SuspendEvents::clearSuspendPopFrameEvent);
final Method exceptionCatchThrowMethod =
ExceptionCatchTestObject.class.getDeclaredMethod("doThrow");
System.out.println("Test stopped during notifyFramePop with exception on pop of doThrow");
runTestOn(new ExceptionCatchTestObject(),
(thr) -> setupSuspendPopFrameEvent(0, exceptionCatchThrowMethod, thr),
SuspendEvents::clearSuspendPopFrameEvent);
System.out.println("Test stopped during ExceptionCatch event of calledFunction " +
"(catch in called function, throw in called function)");
runTestOn(new ExceptionThrowTestObject(true),
(thr) -> setupSuspendExceptionEvent(exceptionThrowCalledMethod, /*catch*/ true, thr),
SuspendEvents::clearSuspendExceptionEvent);
final Method exceptionCatchCalledMethod =
ExceptionCatchTestObject.class.getDeclaredMethod("calledFunction");
System.out.println("Test stopped during ExceptionCatch event of calledFunction " +
"(catch in called function, throw in subroutine)");
runTestOn(new ExceptionCatchTestObject(),
(thr) -> setupSuspendExceptionEvent(exceptionCatchCalledMethod, /*catch*/ true, thr),
SuspendEvents::clearSuspendExceptionEvent);
System.out.println("Test stopped during Exception event of calledFunction " +
"(catch in calling function)");
runTestOn(new ExceptionThrowTestObject(false),
(thr) -> setupSuspendExceptionEvent(exceptionThrowCalledMethod, /*catch*/ false, thr),
SuspendEvents::clearSuspendExceptionEvent);
System.out.println("Test stopped during Exception event of calledFunction " +
"(catch in called function)");
runTestOn(new ExceptionThrowTestObject(true),
(thr) -> setupSuspendExceptionEvent(exceptionThrowCalledMethod, /*catch*/ false, thr),
SuspendEvents::clearSuspendExceptionEvent);
final Method exceptionThrowFarCalledMethod =
ExceptionThrowFarTestObject.class.getDeclaredMethod("calledFunction");
System.out.println("Test stopped during Exception event of calledFunction " +
"(catch in parent of calling function)");
runTestOn(new ExceptionThrowFarTestObject(false),
(thr) -> setupSuspendExceptionEvent(exceptionThrowFarCalledMethod, /*catch*/ false, thr),
SuspendEvents::clearSuspendExceptionEvent);
System.out.println("Test stopped during Exception event of calledFunction " +
"(catch in called function)");
runTestOn(new ExceptionThrowFarTestObject(true),
(thr) -> setupSuspendExceptionEvent(exceptionThrowFarCalledMethod, /*catch*/ false, thr),
SuspendEvents::clearSuspendExceptionEvent);
// These tests are disabled for either the RI (b/116003018) or for jvmti-stress. For the
// later it is due to the additional agent causing classes to be loaded earlier as it forces
// deeper verification during class redefinition, causing failures.
// NB the agent is prevented from popping frames in either of these events in ART. See
// b/117615146 for more information about this restriction.
if (canRunClassLoadTests && CanRunClassLoadingTests()) {
// This test doesn't work on RI since the RI disallows use of PopFrame during a ClassLoad
// event. See b/116003018 for more information.
System.out.println("Test stopped during a ClassLoad event.");
runTestOn(new ClassLoadObject(),
(thr) -> setupSuspendClassEvent(EVENT_TYPE_CLASS_LOAD, ClassLoadObject.CLASS_NAMES, thr),
SuspendEvents::clearSuspendClassEvent);
// The RI handles a PopFrame during a ClassPrepare event incorrectly. See b/116003018 for
// more information.
System.out.println("Test stopped during a ClassPrepare event.");
runTestOn(new ClassLoadObject(),
(thr) -> setupSuspendClassEvent(EVENT_TYPE_CLASS_PREPARE,
ClassLoadObject.CLASS_NAMES,
thr),
SuspendEvents::clearSuspendClassEvent);
}
System.out.println("Test stopped during random Suspend.");
final SuspendSuddenlyObject sso = new SuspendSuddenlyObject();
runTestOn(
sso,
new TestSuspender() {
public void setup(Thread thr) { }
public void waitForSuspend(Thread thr) {
while (!sso.is_spinning) {}
Suspension.suspend(thr);
}
public void cleanup(Thread thr) {
sso.stop_spinning = true;
}
});
final Method redefineCalledFunction =
RedefineTestObject.class.getDeclaredMethod("calledFunction");
final int redefLine = Breakpoint.locationToLine(redefineCalledFunction, 0) + 2;
final long redefLoc = Breakpoint.lineToLocation(redefineCalledFunction, redefLine);
System.out.println("Test redefining frame being popped.");
runTestOn(new RedefineTestObject(),
(thr) -> setupSuspendBreakpointFor(redefineCalledFunction, redefLoc, thr),
(thr) -> {
clearSuspendBreakpointFor(thr);
Redefinition.doCommonClassRedefinition(RedefineTestObject.class,
RedefineTestObject.CLASS_BYTES,
RedefineTestObject.DEX_BYTES);
});
System.out.println("Test stopped during a native method fails");
runTestOn(new NativeCalledObject(),
SuspendEvents::setupWaitForNativeCall,
SuspendEvents::clearWaitForNativeCall);
System.out.println("Test stopped in a method called by native fails");
final Method nativeCallerMethod = NativeCallerObject.class.getDeclaredMethod("calledFunction");
runTestOn(new NativeCallerObject(),
(thr) -> setupSuspendMethodEvent(nativeCallerMethod, /*enter*/ false, thr),
SuspendEvents::clearSuspendMethodEvent);
final Object lock2 = new Object();
synchronized (lock2) {}
System.out.println("Test stopped with monitor in enclosing frame.");
runTestOn(new StandardTestObject() {
@Override
public void run() {
synchronized (lock2) {
super.run();
}
}
},
(thr) -> setupSuspendBreakpointFor(calledFunction, loc, thr),
SuspendEvents::clearSuspendBreakpointFor);
synchronized (lock2) {}
}
// Volatile is to prevent any future optimizations that could invalidate this test by doing
// constant propagation and eliminating the failing paths before the verifier is able to load the
// class.
static volatile boolean ranClassLoadTest = false;
static boolean classesPreverified = false;
private static final class RCLT0 { public void foo() {} }
private static final class RCLT1 { public void foo() {} }
// If classes are not preverified for some reason (interp-ac, no-image, etc) the verifier will
// actually load classes as it runs. This means that we cannot use the class-load tests as they
// are written. TODO Support this.
public boolean CanRunClassLoadingTests() {
if (ranClassLoadTest) {
return classesPreverified;
}
if (!ranClassLoadTest) {
// Only this will ever be executed.
new RCLT0().foo();
} else {
// This will never be executed. If classes are not preverified the verifier will load RCLT1
// when the enclosing method is run. This behavior makes the class-load/prepare test cases
// impossible to successfully run (they will deadlock).
new RCLT1().foo();
System.out.println("FAILURE: UNREACHABLE Location!");
}
classesPreverified = !isClassLoaded("Lart/Test1953$RCLT1;");
ranClassLoadTest = true;
return classesPreverified;
}
public static native boolean isClassLoaded(String name);
public static native void popFrame(Thread thr);
}
|
/*
* 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 jssows;
import java.io.IOException;
import org.java_websocket.WebSocketImpl;
/**
*
* @author Frank Afriat
*/
public class Main {
public static void main(String[] args) throws InterruptedException, IOException {
WebSocketImpl.DEBUG = true;
int port = 8887; // 843 flash policy port
try {
port = Integer.parseInt(args[0]);
} catch (Exception ex) {
}
JsonStandardJavaWebSocketServerServices<WebsocketSession> s = new JsonStandardJavaWebSocketServerServices(port);
s.start();
System.out.println("WebSocketServer started on port: " + s.getPort());
}
}
|
package edu.neu.ccs.cs5010;
import org.junit.Before;
import org.junit.Test;
import java.math.BigInteger;
import static org.junit.Assert.*;
/**
* Created by bikegcy on 10/31/17.
*/
public class PairGeneratorTest {
private Client client;
private BigInteger[][] keyPair;
private RSAKeyGenerator keyGenerator;
private RandomNumber randomNum;
private PairGenerator pairGenerator;
@Before
public void setUp() throws Exception {
keyGenerator = new RSAKeyGenerator();
keyPair = keyGenerator.generateKey();
randomNum = new RandomNumber();
pairGenerator = new PairGenerator();
client = new Client(
101791,
keyPair[RSAKeyGenerator.publicKeyIndex], keyPair[RSAKeyGenerator.privateKeyIndex],
2000,
500
);
}
@Test
public void generatePairs() throws Exception {
Double fraction = 0.5;
BigInteger[] pair;
pair = pairGenerator.generatePairs(fraction, client);
}
} |
/**
* Created with IntelliJ IDEA.
* User: daixing
* Date: 12-11-15
* Time: ไธๅ10:53
* To change this template use File | Settings | File Templates.
*/
public class p1_1_32 {
public static void main(String[] args)
{
int l = 0;
int r = 1;
int N = StdIn.readInt();
int num = 10000;
int[] a = new int[N];
for(int i = 0; i < num; i ++)
{
a[(int)(StdRandom.uniform() * N)]++;
}
double w = 1.0 / N;
for(int i = 0; i < N; ++i)
{
double h = (double)a[i] / num;
double x = (double)i / N + w /2;
double y = h / 2;
StdDraw.filledRectangle(x, y, w / 2, h / 2);
}
}
}
|
package com.wu.cy.xiaoyreader.fragment.news;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.wu.cy.library.loadrecyclerview.LoadRecyclerView;
import com.wu.cy.xiaoyreader.R;
import com.wu.cy.xiaoyreader.activity.WebViewActivity;
import com.wu.cy.xiaoyreader.api.ApiClient;
import com.wu.cy.xiaoyreader.model.NewsListModel;
import com.wu.cy.xiaoyreader.model.NewsListModel.ShowapiResBodyEntity.PagebeanEntity.ContentlistEntity;
import com.wu.cy.xiaoyreader.network.NetWorkManager;
import com.wu.cy.xiaoyreader.view.DividerItemDecoration;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
/**
* Created by wcy8038 on 2016/2/3.
*/
public class NewsFragment extends BaseFragment {
String id = "";
String name = "";
@Bind(R.id.recycler_view)
LoadRecyclerView mRecyclerView;
@Bind(R.id.swipe_layout)
SwipeRefreshLayout mSwipeLayout;
LinearLayoutManager lm;
private int currentPage = 1;
private int totalPage = 1;
private List<ContentlistEntity> mList = new ArrayList<>();
MyAdapter myAdapter;
Call<NewsListModel> mCall;
private Handler mHandler = new Handler();
private boolean loaded;
private boolean isCreate;
public static Fragment newInstance(String id, String name) {
Fragment newsFragment = new NewsFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
newsFragment.setArguments(bundle);
return newsFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
id = getArguments().getString("id");
name = getArguments().getString("name");
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news, null);
ButterKnife.bind(this, view);
initViews();
isCreate = true;
Log.d("www", "fragment " + this.getClass().getSimpleName() + " onCreateView: " + view);
return view;
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d("www", "setUserVisibleHint name:" +name + ", isVisibleToUser =" + isVisibleToUser);
load();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d("www", "fragment " + this.getClass().getSimpleName() + " onActivityCreated: ");
load();
}
private void load(){
if(getUserVisibleHint() && isCreate && !loaded){
requestData(1);
}
}
private void initViews() {
mSwipeLayout.setColorSchemeColors(Color.BLUE);
mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// if(!mSwipeLayout.isRefreshing()) {
requestData(1);
// }
}
});
mSwipeLayout.setRefreshing(false);
lm = new LinearLayoutManager(getContext());
lm.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(lm);
myAdapter = new MyAdapter();
mRecyclerView.setAdapter(myAdapter);
Log.d("www", "fragment " + this.getClass().getSimpleName() + " initViews: " + myAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),
DividerItemDecoration.VERTICAL_LIST);
mRecyclerView.addItemDecoration(dividerItemDecoration);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setOnLoadNextListener(new LoadRecyclerView.OnLoadNextListener() {
@Override
public void onLoadNext() {
requestData(currentPage);
}
});
}
class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_NO_IMG = 1;
private static final int TYPE_ONE_IMG = 2;
private static final int TYPE_THREE_IMG = 3;
class OneImgViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
TextView from;
TextView time;
public OneImgViewHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.iv);
title = (TextView) itemView.findViewById(R.id.item_text);
from = (TextView) itemView.findViewById(R.id.item_text_from);
time = (TextView) itemView.findViewById(R.id.item_text_time);
}
public void setEntry(final ContentlistEntity entry){
title.setText(entry.getTitle());
from.setText(entry.getSource());
time.setText(entry.getPubDate());
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!TextUtils.isEmpty(entry.getLink())){
Intent intent = new Intent(getContext(), WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_KEY_URL,entry.getLink());
startActivity(intent);
}
}
});
if(entry.getImageurls() != null && entry.getImageurls().size() > 0){
ContentlistEntity.ImageurlsEntity imageENtry = entry.getImageurls().get(0);
Picasso.with(getContext())
.load(imageENtry.getUrl())
.resize(imageENtry.getWidth(), imageENtry.getHeight())
.centerCrop()
.into(icon);
}else{
icon.setImageResource(R.mipmap.no_pic);
}
}
}
class NoImgViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView from;
TextView time;
public NoImgViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.item_text);
from = (TextView) itemView.findViewById(R.id.item_text_from);
time = (TextView) itemView.findViewById(R.id.item_text_time);
}
public void setEntry(final ContentlistEntity entry){
title.setText(entry.getTitle());
from.setText(entry.getSource());
time.setText(entry.getPubDate());
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!TextUtils.isEmpty(entry.getLink())){
Intent intent = new Intent(getContext(), WebViewActivity.class);
intent.putExtra(WebViewActivity.EXTRA_KEY_URL,entry.getLink());
startActivity(intent);
}
}
});
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(viewType == TYPE_ONE_IMG) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_item_one_img, parent, false);
return new OneImgViewHolder(view);
}else {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_item_no_img, parent, false);
return new NoImgViewHolder(view);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder instanceof OneImgViewHolder){
((OneImgViewHolder) holder).setEntry(mList.get(position));
}else if(holder instanceof NoImgViewHolder){
((NoImgViewHolder) holder).setEntry(mList.get(position));
}
}
@Override
public int getItemCount() {
return mList.size();
}
@Override
public int getItemViewType(int position) {
if(mList.get(position).getImageurls() != null
&& mList.get(position).getImageurls().size() == 1){
return TYPE_ONE_IMG;
}else if(mList.get(position).getImageurls() != null &&
mList.get(position).getImageurls().size() == 3){
return TYPE_THREE_IMG;
}else{
return TYPE_NO_IMG;
}
}
}
private void requestData(int page) {
final boolean isRefresh = page == 1;
if (isRefresh) {
new Handler().post(new Runnable() {
@Override
public void run() {
mSwipeLayout.setRefreshing(true);
}
});
currentPage = 1;
}else{
mRecyclerView.setState(LoadRecyclerView.STATE_LOADING);
}
Log.d("wcy", "url:" + ApiClient.getNewsUrl(name, page));
mCall = ApiClient.getServices().listNews(ApiClient.getNewsUrl(name, page));
new NetWorkManager<NewsListModel>().execRequest(mCall, new NetWorkManager.NetWorkCallback<NewsListModel>() {
@Override
public void onSuccess(NewsListModel newsListModel) {
loaded = true;
totalPage = newsListModel.getShowapi_res_body().getPagebean().getAllPages();
currentPage = newsListModel.getShowapi_res_body().getPagebean().getCurrentPage();
if (isRefresh) {
mSwipeLayout.setRefreshing(false);
mList.clear();
}else{
mRecyclerView.setState(LoadRecyclerView.STATE_IDLE);
}
mList.addAll(newsListModel.getShowapi_res_body().getPagebean().getContentlist());
if (currentPage == totalPage - 1) {
mRecyclerView.setCanLoadMore(false);
}else{
mRecyclerView.setCanLoadMore(true);
}
mRecyclerView.getAdapter().notifyDataSetChanged();
currentPage++;
}
@Override
public void onFail(String msg) {
Toast.makeText(getContext(), "onError" + msg, Toast.LENGTH_LONG).show();
if (isRefresh) {
mSwipeLayout.setRefreshing(false);
}else{
mRecyclerView.setState(LoadRecyclerView.STATE_IDLE);
}
}
});
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(mCall != null && !mCall.isCanceled()){
mCall.cancel();
}
if(mHandler != null){
mHandler.removeCallbacksAndMessages(null);
}
ButterKnife.unbind(this);
Log.d("www", "fragment " + this.getClass().getSimpleName() + " onDestroyView: ");
}
}
|
package org.bitbucket.alltra101ify.advancedsatelliteutilization.modcontainers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.modblocks.tileentities.TileEntityEnderCoreGenerator;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.modcontainers.modslots.EnderCoreGeneratorSlot;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.moditems.ModItems;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.moditemblockreference.TileEntityGenerator;
public class ContainerEnderCoreGenerator extends Container {
public static final byte INPUT_1 = 0;
public TileEntityEnderCoreGenerator endercoregenerator;
public ContainerEnderCoreGenerator(InventoryPlayer inventoryplayer, TileEntityEnderCoreGenerator tileentity) {
this.endercoregenerator = tileentity;
this.addSlotToContainer(new EnderCoreGeneratorSlot(tileentity, INPUT_1, 7, 28, tileentity));
for (int i = 0; i < 3; i++) {
this.addSlotToContainer(new Slot(tileentity, 1 + i, 155, 5 + i * 19));
}
for (int i = 0; i < 9; i++) {
this.addSlotToContainer(new Slot(inventoryplayer, i, 8 + i * 18,
125));
}
for (byte i = 0; i < 3; i++) {
for (byte j = 0; j < 9; j++) {
this.addSlotToContainer(new Slot(inventoryplayer,
9 + j + i * 9, 8 + j * 18, 67 + i * 18));
}
}
}
@Override
public boolean canInteractWith(EntityPlayer p_75145_1_) {
// TODO Auto-generated method stub
return true;
}
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2SlotId) {
ItemStack itemstack = null;
Slot slot = (Slot) this.inventorySlots.get(par2SlotId);
if (slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (par2SlotId == INPUT_1) {
if (!this.mergeItemStack(itemstack1, INPUT_1+1, INPUT_1+36+1, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (par2SlotId != INPUT_1 && endercoregenerator.isItemValidForSlot(par2SlotId, itemstack1)) {
if (!this.mergeItemStack(itemstack1, INPUT_1, INPUT_1+1,
false)) {
return null;
}
}
if (itemstack1.stackSize == 0) {
slot.putStack((ItemStack) null);
} else {
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize) {
return null;
}
slot.onPickupFromSlot(par1EntityPlayer, itemstack1);
}
return itemstack;
}
}
|
package egovframework.adm.lcms.nct.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.util.HSSFColor.GOLD;
import org.lcms.api.com.Util;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import egovframework.adm.lcms.cts.service.LcmsOrganizationService;
import egovframework.adm.lcms.nct.service.LcmsModuleService;
import egovframework.adm.lcms.nct.service.LcmsNonScormManageService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.com.cmm.service.EgovProperties;
import egovframework.com.cmm.service.Globals;
import egovframework.com.file.controller.FileController;
import egovframework.com.pag.controller.PagingManageController;
import egovframework.com.utl.fcc.service.EgovStringUtil;
import egovframework.rte.fdl.property.EgovPropertyService;
@Controller
public class LcmsNonScormManageController {
/** log */
protected Log log = LogFactory.getLog(this.getClass());
/** EgovPropertyService */
@Resource(name = "propertiesService")
protected EgovPropertyService propertiesService;
/** EgovMessageSource */
@Resource(name="egovMessageSource")
EgovMessageSource egovMessageSource;
/** PagingManageController */
@Resource(name = "pagingManageController")
private PagingManageController pagingManageController;
/** CodeManageService */
@Resource(name = "lcmsNonScormManageService")
private LcmsNonScormManageService lcmsNonScormManageService;
/** lcmsModuleService */
@Resource(name = "lcmsModuleService")
private LcmsModuleService lcmsModuleService;
/** lcmsOrganizationService */
@Resource(name = "lcmsOrganizationService")
private LcmsOrganizationService lcmsOrganizationService;
/**
* NonScorm ๋ฆฌ์คํธํ์ด์ง
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/lcmsNonScormList.do")
public String pageList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
int totCnt = lcmsNonScormManageService.selectNonScormListTotCnt(commandMap);
pagingManageController.PagingManage(commandMap, model, totCnt);
List list = lcmsNonScormManageService.selectNonScormList(commandMap);
List codeList = lcmsNonScormManageService.selectContentCodeList(commandMap);
model.addAttribute("list", list);
model.addAttribute("codeList", codeList);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admLcmsNonScormList";
}
/**
* ์
๋ก๋ ์์
๋ฆฌ์คํธ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/excelNonScormList.do")
public String excelNonScormList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String strSavePath = (String)commandMap.get("path");//Globals.CONTNET_REAL_PATH+commandMap.get("subj");
/*
MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
Iterator fileIter = mptRequest.getFileNames();
while (fileIter.hasNext()) {
MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
if (mFile.getSize() > 0) {
EgovFileMngUtil.uploadContentFile(mFile, strSavePath);
}
}
*/
FileController file = new FileController();
List result = file.getExcelDataList(strSavePath);
model.addAttribute("list", result);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormExcelList";
}
@RequestMapping(value="/adm/lcms/nct/LcmsNonScormModuleDelete.do")
public String nonScormModuleDelete(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
String resultMsg = "";
String forwardUrl = "";
int check = lcmsOrganizationService.checkCourseMapping(commandMap);
if( check == 0){
String[] module = EgovStringUtil.getStringSequence(commandMap,"chk");
commandMap.put("module", module);
//List filePath = lcmsModuleService.selectModulePath(commandMap);
int result = lcmsModuleService.deleteLcmsModule( commandMap);
// FileController file = new FileController();
// for( int i=0; i<filePath.size(); i++ ){
// //์ ํ์ฐจ์ ์ปจํ
์ธ ํ์ผ ์ญ์
// boolean deleteResult = file.deleteDirector(Globals.CONTNET_REAL_PATH+((Map)filePath.get(i)).get("modulePath"));
// }
if(result > 0){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
}else{
resultMsg = "์ด๋ฏธ ์ฌ์ฉ์ค์ธ ๊ต๊ณผ๋ ์์ ํ ์ ์์ต๋๋ค.";
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/adm/lcms/nct/nonScormOrgList.do";
}
/**
* ์์
ํ์ผ ๋ฐ์ดํฐ ๋ฑ๋ก( ์ค๊ณต๊ต )
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/LcmsCotiExcelInsert.do")
public String insertCotiExcel(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String resultMsg = "";
String strSavePath = Globals.CONTNET_REAL_PATH+commandMap.get("subj");
FileController file = new FileController();
List dataList = file.getExcelDataList(strSavePath);
// // ์์ถํ์ผ ํด์
// String contents[] = (new File(strSavePath)).list();
// for(int j=0; j<contents.length; j++){
// String saveFile = contents[j];
// if( !saveFile.endsWith(".xls") ){
// String strSavePath2 = file.checkCotiFile(strSavePath, saveFile);
// file.fileUnZip2(strSavePath, strSavePath2, saveFile);
// }
// }
commandMap.put("strSavePath", strSavePath);
int result = lcmsNonScormManageService.insertCotiExcel(dataList, commandMap);
if( result > 0 ){
resultMsg = egovMessageSource.getMessage("success.common.insert");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.insert");
// ํด๋ ์ญ์
boolean deleteResult = file.deleteDirector(strSavePath);
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormExcelList";
}
/**
* ์์
ํ์ผ ๋ฐ์ดํฐ ๋ฑ๋ก( nonscorm )
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/LcmsExcelInsert.do")
public String insertExcel(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
String resultMsg = "";
String strSavePath = Globals.CONTNET_REAL_PATH+commandMap.get("subj");
FileController file = new FileController();
List dataList = file.getExcelDataList(strSavePath);
commandMap.put("strSavePath", strSavePath);
int result = lcmsNonScormManageService.insertExcel(dataList, commandMap);
if( result > 0 ){
resultMsg = egovMessageSource.getMessage("success.common.insert");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.insert");
// ํด๋ ์ญ์
boolean deleteResult = file.deleteDirector(strSavePath);
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormExcelList";
}
/**
* ์ปจํ
์ธ ์
๋ก๋ ์ทจ์( ์
๋ก๋ํ์ผ ์ญ์ )
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/LcmsNonScormCancel.do")
public String deleteFolder(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String resultMsg = "";
FileController file = new FileController();
String strSavePath = Globals.CONTNET_REAL_PATH+commandMap.get("subj");
// ํด๋ ์ญ์
boolean deleteResult = file.deleteDirector(strSavePath);
if( deleteResult ){
resultMsg = "์ทจ์ ๋์์ต๋๋ค.";
}else{
resultMsg = "์ทจ์์ฒ๋ฆฌ์ค ์ค๋ฅ๋ก ์ธํ์ฌ ํ์ผ์ด ์ ์์ ์ผ๋ก ์ญ์ ๋์ง ์์์ต๋๋ค.";
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormExcelList";
}
@RequestMapping(value="/adm/lcms/nct/nonScormOrgList.do")
public String moduleList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
List list = lcmsNonScormManageService.selectNonScormOrgList(commandMap);
Map data = lcmsModuleService.selectSaveInfoData(commandMap);
model.addAttribute("list", list);
model.addAttribute("data", data);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormOrgList";
}
/**
* ํ์๊ด๋ฆฌ ๋ชฉ๋ก ํ์ด์ง
* @param LcmsContentManageService
* @param Map commandMap, ModelMap model
* @return ์ถ๋ ฅํ์ด์ง์ ๋ณด "adm/lcms/nct/lcmsContentList.jsp"
* @exception Exception
*/
@RequestMapping(value="/adm/lcms/nct/lcmsNonScormContentList.do")
public String fileList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
String folder = (String)commandMap.get("folder");
folder = folder != null && !folder.equals("") ? "/"+folder : "";
String path = "";
if( commandMap.get("path") != null && !commandMap.get("path").toString().equals("") ){
path = (String)commandMap.get("path");
if( commandMap.get("eventType").toString().equals("IN") ){
path += folder;
}else{
path = path.substring(0, path.lastIndexOf("/"));
}
}else{
path = lcmsNonScormManageService.selectContentPath(commandMap);
}
commandMap.put("path", path);
List fileList = this.getContentList(Globals.CONTNET_REAL_PATH + path);
model.addAttribute("fileList", this.sortList(fileList));
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admNonScormContentList";
}
/**
* ํ์๊ด๋ฆฌ ํด๋์์ฑํ์
* @param LcmsContentManageService
* @param Map commandMap, ModelMap model
* @return ์ถ๋ ฅํ์ด์ง์ ๋ณด "adm/lcms/nct/createContentFolder.jsp"
* @exception Exception
*/
@RequestMapping(value="/adm/lcms/nct/createContentFolderPopup.do")
public String createContentFolderPopup(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admLcmsContentFolder";
}
/**
* ํ์๊ด๋ฆฌ ํด๋์์ฑํ์
* @param LcmsContentManageService
* @param Map commandMap, ModelMap model
* @return ์ถ๋ ฅํ์ด์ง์ ๋ณด "adm/lcms/nct/createContentFolder.jsp"
* @exception Exception
*/
@RequestMapping(value="/adm/lcms/nct/createContentFolder.do")
public String createContentFolder(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
String path = Globals.CONTNET_REAL_PATH + (String)commandMap.get("path");
String fileName = (String)commandMap.get("folderName");
String resultMsg = "";
File file = new File(path +"/"+ fileName);
if( file.isDirectory() ){
resultMsg = "์ด๋ฏธ ์กด์ฌํ๋ ํด๋์
๋๋ค.";
}else{
file.mkdir();
resultMsg = "ํด๋๋ฅผ ์์ฑ ํ์์ต๋๋ค.";
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admLcmsContentFolder";
}
/**
* ํ์๊ด๋ฆฌ ํ์ผ์ญ์
* @param LcmsContentManageService
* @param Map commandMap, ModelMap model
* @return ์ถ๋ ฅํ์ด์ง์ ๋ณด "adm/lcms/nct/lcmsContentList.jsp"
* @exception Exception
*/
@RequestMapping(value="/adm/lcms/nct/deleteContentFile.do")
public String deleteContentFile(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
String[] fileName = EgovStringUtil.getStringSequence(commandMap,"chk");
String path = Globals.CONTNET_REAL_PATH+(String)commandMap.get("path");
FileController file = new FileController();
for( int i=0; i<fileName.length; i++ ){
File tmp = new File(path+"/"+fileName[i]);
if( tmp.isDirectory() ){
file.deleteDirector(path+"/"+fileName[i]);
}else{
tmp.delete();
}
}
model.addAttribute("resultMsg", "์ญ์ ์ฒ๋ฆฌ ๋์์ต๋๋ค.");
model.addAllAttributes(commandMap);
return "forward:/adm/lcms/nct/lcmsNonScormContentList.do";
}
/**
* ํ์๊ด๋ฆฌ ํด๋์์ฑํ์
* @param LcmsContentManageService
* @param Map commandMap, ModelMap model
* @return ์ถ๋ ฅํ์ด์ง์ ๋ณด "adm/lcms/nct/createContentFolder.jsp"
* @exception Exception
*/
@RequestMapping(value="/adm/lcms/nct/changeContentFilePopup.do")
public String changeFilePopup(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception {
model.addAllAttributes(commandMap);
return "adm/lcms/nct/admLcmsContentChangeFile";
}
/**
* CA์ ๋ณด ์์
๋ค์ด๋ก๋
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/lcms/nct/lcmsNonScormExcelDown.do")
public ModelAndView excelDownload(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
List list = new ArrayList();
String contentType = (String)commandMap.get("contentType");
if( commandMap.get("contentType") != null ){
if( contentType.equals("C") ){
list = lcmsNonScormManageService.selectCotiExcelList(commandMap);
}else{
list = lcmsNonScormManageService.selectExcelList(commandMap);
}
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", list);
map.put("contentType", contentType);
return new ModelAndView("lcmsExcelView", "lcmsMap", map);
}
@RequestMapping(value="/adm/lcms/nct/deleteLcmsCA.do")
public String deleteLcmsCA(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
String resultMsg = "";
int result = lcmsNonScormManageService.deleteLcmsCA(commandMap);
if( result > 0 ){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/adm/lcms/nct/lcmsNonScormList.do";
}
@RequestMapping(value="/adm/lcms/nct/progressLogPopup.do")
public String progressLogPopup(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
String[] arrOrgSeq = EgovStringUtil.getStringSequence(commandMap, "chk");
commandMap.put("arrOrgSeq", arrOrgSeq);
List progressList = lcmsNonScormManageService.selectProgressLogList(commandMap);
model.addAttribute("progressList", progressList);
model.addAllAttributes(commandMap);
return "adm/lcms/nct/progressLogPopup";
}
@RequestMapping(value="/adm/lcms/nct/deleteLog.do")
public String deletePorgressLog(HttpServletRequest request, HttpServletResponse response, Map commandMap, ModelMap model) throws Exception{
String[] arrOrgSeq = EgovStringUtil.getStringSequence(commandMap, "chk");
commandMap.put("arrOrgSeq", arrOrgSeq);
String resultMsg = "";
int result = lcmsNonScormManageService.deletePorgressLog(commandMap);
if( result > 0 ){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/adm/lcms/nct/progressLogPopup.do";
}
@RequestMapping(value="/adm/lcms/nct/sampleExcelPopup.do")
public String sampleExcelPopup(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
model.addAllAttributes(commandMap);
return "adm/lcms/nct/sampleExcelPopup";
}
public List getContentList(String path) throws Exception{
ArrayList result = new ArrayList();
try{
File file = new File(path);
String contents[] = file.list();
Map<String, Object> inputMap;
Map ext = this.getExtension();
for( int i=0; i<contents.length; i++ ){
inputMap = new HashMap<String, Object>();
String fileName = contents[i];
File child = new File(file, fileName);
inputMap.put("fileName", fileName);
inputMap.put("modified", Util.dateToString(new Date(child.lastModified()), "yyyy-MM-dd HH:MM:SS"));
if( child.isDirectory() ){
inputMap.put("byte", 0);
inputMap.put("fileType", 1);
}else{
inputMap.put("byte", child.length());
inputMap.put("fileType", 2);
}
inputMap.put("fileExt", ext.containsKey(fileName.substring(fileName.indexOf(".") + 1)));
result.add(inputMap);
}
}catch(Exception ex){
log.info("getContentList exception : "+ex);
}
return result;
}
public static Map getExtension(){
Map map = new HashMap();
map.put("zip","PACK");
map.put("alz","PACK");
map.put("jar","PACK");
map.put("swf","FLASH");
map.put("fla","FLASH");
map.put("gif","IMAGE");
map.put("jpg","IMAGE");
map.put("bmp","IMAGE");
map.put("png","IMAGE");
map.put("doc","WORD");
map.put("ppt","POWERPOINT");
map.put("xls","EXCEL");
map.put("hwp","DOCUMENT");
map.put("pdf","DOCUMENT");
return map;
}
public List sortList(List list) throws Exception{
ArrayList result = new ArrayList();
Map temp = new HashMap();
for( int i=1; i<=2; i++ ){
for( int j=0; j<list.size(); j++ ){
temp = (Map)list.get(j);
if( (Integer)temp.get("fileType") == i ){
result.add(temp);
}
}
}
return result;
}
}
|
import java.io.*;
import java.util.*;
public class Main {
static class Edge {
int src;
int nbr;
int wt;
Edge(int src, int nbr, int wt) {
this.src = src;
this.nbr = nbr;
this.wt = wt;
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int vtces = Integer.parseInt(br.readLine());
ArrayList<Edge>[] graph = new ArrayList[vtces];
for (int i = 0; i < vtces; i++) {
graph[i] = new ArrayList<>();
}
int edges = Integer.parseInt(br.readLine());
for (int i = 0; i < edges; i++) {
String[] parts = br.readLine().split(" ");
int v1 = Integer.parseInt(parts[0]);
int v2 = Integer.parseInt(parts[1]);
int wt = Integer.parseInt(parts[2]);
graph[v1].add(new Edge(v1, v2, wt));
graph[v2].add(new Edge(v2, v1, wt));
}
connectAllPcs(graph, new boolean[vtces]);
}
public static class pair implements Comparable<pair>{
int vtx;
int parent;
int wt;
pair(int vtx, int parent, int wt){
this.vtx = vtx;
this.parent = parent;
this.wt = wt;
}
public int compareTo(pair o){
return this.wt - o.wt;
}
}
public static void minSpanningTree(ArrayList<Edge>[] graph, boolean[] visited){
PriorityQueue<pair> pq = new PriorityQueue<>();
pq.add(new pair(0,-1,0));
visited[0]= true;
while(pq.size() > 0){
pair rem = pq.remove();
if(rem.parent != -1){
if( !visited[rem.vtx] ){
//mark visited
visited[rem.vtx] = true;
//print
System.out.println("["+rem.vtx+"-"+rem.parent+"@"+rem.wt+"]");
}
}
for(Edge e : graph[rem.vtx] ){
if(!visited[e.nbr]){
pq.add(new pair(e.nbr, rem.vtx, e.wt));
}
}
}
}
}
|
/*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.server;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.http.server.PathContainer.Element;
import org.springframework.http.server.PathContainer.Options;
import org.springframework.http.server.PathContainer.PathSegment;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for {@link DefaultPathContainer}.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
class DefaultPathContainerTests {
@Test
void pathSegment() {
// basic
testPathSegment("cars", "cars", emptyMap());
// empty
testPathSegment("", "", emptyMap());
// spaces
testPathSegment("%20%20", " ", emptyMap());
testPathSegment("%20a%20", " a ", emptyMap());
}
@Test
void pathSegmentParams() {
// basic
LinkedMultiValueMap<String, String> params = emptyMap();
params.add("colors", "red");
params.add("colors", "blue");
params.add("colors", "green");
params.add("year", "2012");
testPathSegment("cars;colors=red,blue,green;year=2012", "cars", params);
// trailing semicolon
params = emptyMap();
params.add("p", "1");
testPathSegment("path;p=1;", "path", params);
// params with spaces
params = emptyMap();
params.add("param name", "param value");
testPathSegment("path;param%20name=param%20value;%20", "path", params);
// empty params
params = emptyMap();
params.add("p", "1");
testPathSegment("path;;;%20;%20;p=1;%20", "path", params);
}
@Test
void pathSegmentParamsAreImmutable() {
assertPathSegmentParamsAreImmutable("cars", emptyMap(), Options.HTTP_PATH);
LinkedMultiValueMap<String, String> params = emptyMap();
params.add("colors", "red");
params.add("colors", "blue");
params.add("colors", "green");
assertPathSegmentParamsAreImmutable(";colors=red,blue,green", params, Options.HTTP_PATH);
assertPathSegmentParamsAreImmutable(";colors=red,blue,green", emptyMap(), Options.MESSAGE_ROUTE);
}
private void assertPathSegmentParamsAreImmutable(String path, LinkedMultiValueMap<String, String> params, Options options) {
PathContainer container = PathContainer.parsePath(path, options);
assertThat(container.elements()).hasSize(1);
PathSegment segment = (PathSegment) container.elements().get(0);
MultiValueMap<String, String> segmentParams = segment.parameters();
assertThat(segmentParams).isEqualTo(params);
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(() -> segmentParams.add("enigma", "boom"));
}
private void testPathSegment(String rawValue, String valueToMatch, MultiValueMap<String, String> params) {
PathContainer container = PathContainer.parsePath(rawValue);
if ("".equals(rawValue)) {
assertThat(container.elements()).isEmpty();
return;
}
assertThat(container.elements()).hasSize(1);
PathSegment segment = (PathSegment) container.elements().get(0);
assertThat(segment.value()).as("value: '" + rawValue + "'").isEqualTo(rawValue);
assertThat(segment.valueToMatch()).as("valueToMatch: '" + rawValue + "'").isEqualTo(valueToMatch);
assertThat(segment.parameters()).as("params: '" + rawValue + "'").isEqualTo(params);
}
@Test
void path() {
// basic
testPath("/a/b/c", "/a/b/c", "/", "a", "/", "b", "/", "c");
// root path
testPath("/", "/", "/");
// empty path
testPath("", "");
testPath("%20%20", "%20%20", "%20%20");
// trailing slash
testPath("/a/b/", "/a/b/", "/", "a", "/", "b", "/");
testPath("/a/b//", "/a/b//", "/", "a", "/", "b", "/", "/");
// extra slashes and spaces
testPath("/%20", "/%20", "/", "%20");
testPath("//%20/%20", "//%20/%20", "/", "/", "%20", "/", "%20");
}
private void testPath(String input, String value, String... expectedElements) {
PathContainer path = PathContainer.parsePath(input, Options.HTTP_PATH);
assertThat(path.value()).as("value: '" + input + "'").isEqualTo(value);
assertThat(path.elements()).map(Element::value).as("elements: " + input)
.containsExactly(expectedElements);
}
@Test
void subPath() {
// basic
PathContainer path = PathContainer.parsePath("/a/b/c");
assertThat(path.subPath(0)).isSameAs(path);
assertThat(path.subPath(2).value()).isEqualTo("/b/c");
assertThat(path.subPath(4).value()).isEqualTo("/c");
// root path
path = PathContainer.parsePath("/");
assertThat(path.subPath(0).value()).isEqualTo("/");
// trailing slash
path = PathContainer.parsePath("/a/b/");
assertThat(path.subPath(2).value()).isEqualTo("/b/");
}
@Test // gh-23310
void pathWithCustomSeparator() {
PathContainer path = PathContainer.parsePath("a.b%2Eb.c", Options.MESSAGE_ROUTE);
Stream<String> decodedSegments = path.elements().stream()
.filter(PathSegment.class::isInstance)
.map(PathSegment.class::cast)
.map(PathSegment::valueToMatch);
assertThat(decodedSegments).containsExactly("a", "b.b", "c");
}
private static LinkedMultiValueMap<String, String> emptyMap() {
return new LinkedMultiValueMap<>();
}
}
|
package com.example.api.web.rest;
import com.example.api.domain.Endereco;
import com.example.api.service.CustomerService;
import com.example.api.service.EnderecoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
@RequestMapping("/api/enderecos")
public class EnderecoController {
private EnderecoService enderecoService;
private CustomerService customerService;
@Autowired
public EnderecoController(CustomerService customerService, EnderecoService enderecoService){
this.customerService = customerService;
this.enderecoService = enderecoService;
}
@GetMapping("/{cep}")
public Endereco getEnderecoFromApi(@PathVariable String cep){
final String uri = "https://viacep.com.br/ws/" + cep + "/json/";
RestTemplate restTemplate = new RestTemplate();
Endereco endereco = restTemplate.getForObject(uri, Endereco.class);
return endereco;
}
@GetMapping
public List<Endereco> getEnderecos(){
return enderecoService.findAll();
}
@PostMapping()
public ResponseEntity<String> insertEndereco(@RequestParam String cep,
@RequestParam String numero,
@RequestParam long idCustomer){
if(! customerService.isCustomerExist(idCustomer))
return new ResponseEntity<>("", HttpStatus.OK);
final String uri = "https://viacep.com.br/ws/" + cep + "/json/";
RestTemplate restTemplate = new RestTemplate();
Endereco endereco = restTemplate.getForObject(uri, Endereco.class);
if(endereco == null)
return new ResponseEntity<>("", HttpStatus.OK);
endereco.setNumero(numero);
endereco.setCustomer(customerService.findById(idCustomer).get());
enderecoService.insertEndereco(endereco);
return new ResponseEntity<>("", HttpStatus.CREATED);
}
}
|
package HTTP.Requests.AccountArea;
import HTTP.RequestBase;
import Settings.MySettings;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
/**
* Created by ะะปะตะบัะฐะฝะดั on 14.06.2017.
*/
public class UserLoginRequests extends RequestBase {
//should be refactored with baseClass method
public HttpResponse<String> sendLoginRequest(String email, String password) {
try {
response = Unirest.post(MySettings.getRequestSettings().getBaseUrl() + "login")
.header("accept", "application/json, text/plain, */*")
.header("origin", MySettings.getRequestSettings().getBaseUrl())
// .header("x-devtools-emulate-network-conditions-client-id", "35839de4-25ed-4ae1-9027-625bd6cd5c3e")
// .header("x-devtools-request-id", "1728.1976")
.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36")
.header("content-type", "application/json;charset=UTF-8")
.header("referer", MySettings.getRequestSettings().getBaseUrl() + "itech/login")
.header("accept-encoding", "gzip, deflate, br")
.header("accept-language", "en-US,en;q=0.8")
// .header("cache-control", "no-cache")
// .header("postman-token", "cbf1ef8a-9eb2-5dbf-5083-35e4b5426698")
.body("{\"signinEmail\":\""+ email+"\", \"signinPass\":\""+password+"\"}")
.asString();
} catch (UnirestException e) {
System.out.println("bad request");
}
return response;
}
// @Override
// public HttpResponse<String> sendRequest(Object[] args) {
// return null;
// }
}
|
package org.test.ht;
import java.util.Arrays;
import java.util.List;
import org.test.ht.util.Utils;
public class RecoverBinarySearchTree {
private TreeNode swappedANode = null, swappedBNode = null;
public void recover(TreeNode root) {
dfsCheckRightRelationship(root, null, false);
if (swappedANode == null) {
dfsCheckLeftRelationship(root, null, false);
}
int temp = swappedANode.val;
swappedANode.val = swappedBNode.val;
swappedBNode.val = temp;
return;
}
public void dfsCheckRightRelationship(TreeNode node, TreeNode lastRight, boolean occurredRight) {
if (node == null) {
return;
}
if (lastRight != null && node.val < lastRight.val) {
if (occurredRight) {
swappedBNode = node;
}
else {
swappedANode = lastRight;
swappedBNode = node;
occurredRight = true;
}
}
dfsCheckRightRelationship(node.left, lastRight, occurredRight);
dfsCheckRightRelationship(node.right, node, occurredRight);
}
public void dfsCheckLeftRelationship(TreeNode node, TreeNode lastLeft, boolean occurredLeft) {
if (node == null) {
return;
}
if (lastLeft != null && node.val > lastLeft.val) {
if (occurredLeft) {
swappedANode = node;
}
else {
swappedANode = node;
swappedBNode = lastLeft;
occurredLeft = true;
}
}
dfsCheckLeftRelationship(node.left, node, occurredLeft);
dfsCheckLeftRelationship(node.right, lastLeft, occurredLeft);
}
public static void main(String[] args) {
List<Integer> arrs = Arrays.asList(1, 3, 5, null, null, 4, 20, null, null, null, null, null, null, 15, 21, null, null,null,null,null,null,null,null,null,null,null,null,14,17,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,16,18,null,null,null,null);
TreeNode root = Utils.arrayToTree(arrs);
RecoverBinarySearchTree recoverBinarySearchTree = new RecoverBinarySearchTree();
recoverBinarySearchTree.recover(root);
}
}
|
package com.esum.comp.dbc.jdbc.support;
import java.io.File;
import java.util.List;
import com.esum.comp.dbc.DbcCode;
import com.esum.comp.dbc.DbcConfig;
import com.esum.comp.dbc.jdbc.DbConnectionManager;
import com.esum.comp.dbc.jdbc.common.OrderedRecord;
import com.esum.comp.dbc.job.JobException;
import com.esum.comp.dbc.table.DbcInfoRecord;
import com.esum.comp.dbc.template.impl.JdbcWriter;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.jdbc.datasource.DataSourceManager;
import com.esum.framework.jdbc.datasource.JdbcDataSource;
/**
* Update ์ฒ๋ฆฌ. ์ฐ๋ ๋.
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class ListSqlUpdateRunnable extends ListSqlUpdate implements Runnable {
protected List<? extends OrderedRecord> dataList;
protected boolean errorOccured;
public ListSqlUpdateRunnable(List<? extends OrderedRecord> list) {
this.dataList = list;
}
@Override
public void run() {
try {
log.info(traceId + "Starting Db Processor. Data count: " + dataList.size());
initialize();
log.info(traceId + "Db connection initialized.");
process();
log.info(traceId + "Db Processor end.");
} catch (JobException e) {
log.info(traceId + "JobException: Error while processing on runnable.");
} finally {
close();
}
}
protected void initialize() throws JobException {
DbcInfoRecord info = jobInstance.getBatchInfo();
String errorMsg = null;
/** Source DbConnection */
String sourceConfigId = info.getSourceJdbcName();
if (sourceConfigId != null) {
try {
Configurator.init(sourceConfigId, DbcConfig.CONNECTION_PATH + File.separator + sourceConfigId);
JdbcDataSource ds = DataSourceManager.getInstance().createDataSourceById(sourceConfigId);
sourceCon = DbConnectionManager.getInstance(ds);
sourceCon.setAutoCommit(false);
} catch (Throwable e) {
errorMsg = "Error while getting a connection. configId=["+sourceConfigId+"] "+e.toString();
log.error(traceId + errorMsg, e);
this.errorOccured = true;
}
}
/** Target DbConnection */
String targetConfigId = info.getTargetJdbcNames().get(0);
if (targetConfigId != null) {
try {
Configurator.init(targetConfigId, DbcConfig.CONNECTION_PATH + File.separator + targetConfigId);
JdbcDataSource ds = DataSourceManager.getInstance().createDataSourceById(targetConfigId);
targetCon = DbConnectionManager.getInstance(ds);
targetCon.setAutoCommit(false);
} catch (Throwable e) {
errorMsg = "Error while getting a connection. configId=["+targetConfigId+"] "+e.toString();
log.error(traceId + errorMsg, e);
this.errorOccured = true;
}
if (errorOccured) {
int allocatedSize = dataList.size();
for (int i = 0; i < allocatedSize; i++) {
OrderedRecord item = dataList.get(i);
JobException bex = new JobException(DbcCode.ERROR_DB_CONNECTION, errorMsg);
doHandle(item, bex);
}
throw new JobException(DbcCode.ERROR_DB_CONNECTION, errorMsg);
}
}
}
protected void process() throws JobException {
try {
processSql((JdbcWriter)template.getWriter(), dataList, null, 0);
} catch (JobException e) {
log.error(traceId + "JobException: Error while executing SQL.", e);
} catch (Throwable e) {
log.error(traceId + "Throwable: Error while executing SQL.", e);
}
}
}
|
package cn.tedu.oop;
//ๆฌ็ฑป็จไบ้ขๅๅฏน่ฑก็ๅทฉๅบ็ปไน
public class TestCar {
public static void main(String[] args) {
Car c =new Car();
// c.brand="ไฟๆถๆท";
// c.color="้ป่ฒ";
// c.price=688888.88;
// c.length=3.57;
// System.out.println(c.brand);
// System.out.println(c.price);
// System.out.println(c.color);
// System.out.println(c.length);
// System.out.println(c.getPrice());
// System.out.println(c.getLength());
// System.out.println(c.getColor());
// System.out.println(c.getBrand());
//7.3ๆไฝsetๆนๆณ็ปๆๆๅฑๆง่ตๅผ
c.setBrand("ๅฅฅ่ฟช");
System.out.println(c.getBrand());
c.setColor("ๆดปๅ่");
System.out.println(c.getColor());
c.setLength(4.15);
System.out.println(c.getLength());
c.setPrice(428888.88);
System.out.println(c.getPrice());
//8.้่ฟๅๅปบๅฅฝ็ๅฏน่ฑก่ฐ็จๆฑฝ่ฝฆ็ๅ่ฝ
c.start();
// c.stop();
}
}
//1.ๆฝ่ฑกๆฑฝ่ฝฆ่ฟไธ็ฑปไบ็ฉ็ๅ
ฑๅ็น๏ผ็จclassๆ่ฟฐ
class Car{
//2.ๅฑๆง--็จๆๅๅ้
//7.ๅฐ่ฃ
ๆๆๅฑๆง
private String brand;//ๅ็
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
private String color;//้ข่ฒ
private double price;//ไปทๆ ผ
private double length;//้ฟๅบฆ
//3.ๅ่ฝ--็จๆนๆณๆฅๆ่ฟฐ
public void start(){
System.out.println("ๆฑฝ่ฝฆๅฏๅจไบ");
stop();
}
private void stop(){
System.out.println("ๆฑฝ่ฝฆๅๆญขไบ");
}
} |
package go4Code.Restaurante.dto;
import java.util.List;
import go4Code.Restaurante.model.Menu;
public class MenuPageDTO {
List<MenuDTO> content;
boolean last;
public MenuPageDTO(
List<MenuDTO> content,
boolean last
) {
this.content = content;
this.last = last;
}
public List<MenuDTO> getContent() {
return content;
}
public void setContent(List<MenuDTO> content) {
this.content = content;
}
public boolean isLast() {
return last;
}
public void setLast(boolean last) {
this.last = last;
}
}
|
/*
* Copyright 2014 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file 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.amediamanager.scheduled;
import java.io.IOException;
import org.joda.time.Instant;
import org.joda.time.Minutes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import com.amediamanager.config.ConfigurationSettings;
import com.amediamanager.config.ConfigurationSettings.ConfigProps;
import com.amediamanager.domain.Video;
import com.amediamanager.service.VideoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Holds scheduled tasks related to our Elastic Transcoder
*
*/
public class ElasticTranscoderTasks {
protected static final Logger LOG = LoggerFactory.getLogger(ElasticTranscoderTasks.class);
@Autowired
protected ConfigurationSettings config;
@Autowired
protected VideoService videoService;
@Autowired
protected AmazonSQS sqsClient;
protected final ObjectMapper mapper = new ObjectMapper();
protected void checkStatus() {
String sqsQueue = config.getProperty(ConfigProps.TRANSCODE_QUEUE);
LOG.info("Polling transcode queue {} for changes.", sqsQueue);
ReceiveMessageRequest request = new ReceiveMessageRequest(sqsQueue)
.withMaxNumberOfMessages(3)
.withWaitTimeSeconds(20);
ReceiveMessageResult result = sqsClient.receiveMessage(request);
for (Message msg : result.getMessages()) {
handleMessage(msg);
}
LOG.info("Finished polling transcode queue {} and handled {} message(s).", sqsQueue, result.getMessages().size());
}
protected void deleteMessage(final Message message) {
DeleteMessageRequest request = new DeleteMessageRequest()
.withQueueUrl(config.getProperty(ConfigProps.TRANSCODE_QUEUE))
.withReceiptHandle(message.getReceiptHandle());
sqsClient.deleteMessage(request);
}
protected void handleMessage(final Message message) {
try {
LOG.info("Handling message received from checkStatus");
ObjectNode snsMessage = (ObjectNode) mapper.readTree(message.getBody());
ObjectNode notification = (ObjectNode) mapper.readTree(snsMessage.get("Message").asText());
String state = notification.get("state").asText();
String jobId = notification.get("jobId").asText();
String pipelineId = notification.get("pipelineId").asText();
Video video = videoService.findByTranscodeJobId(jobId);
if (video == null) {
LOG.warn("Unable to process result for job {} because it does not exist.", jobId);
Instant msgTime = Instant.parse(snsMessage.get("Timestamp").asText());
if (Minutes.minutesBetween(msgTime, new Instant()).getMinutes() > 20) {
LOG.error("Job {} has not been found for over 20 minutes, deleting message from queue", jobId);
deleteMessage(message);
}
// Leave it on the queue for now.
return;
}
if ("ERROR".equals(state)) {
LOG.warn("Job {} for pipeline {} failed to complete. Body: \n{}", jobId, pipelineId, notification.get("messageDetails").asText());
video.setThumbnailKey(videoService.getDefaultVideoPosterKey());
videoService.save(video);
} else {
// Construct our url prefix: https://bucketname.s3.amazonaws.com/output/key/
String prefix = notification.get("outputKeyPrefix").asText();
if (!prefix.endsWith("/")) { prefix += "/"; }
ObjectNode output = ((ObjectNode) ((ArrayNode) notification.get("outputs")).get(0));
String previewFilename = prefix + output.get("key").asText();
String thumbnailFilename = prefix + output.get("thumbnailPattern").asText().replaceAll("\\{count\\}", "00002") + ".png";
video.setPreviewKey(previewFilename);
video.setThumbnailKey(thumbnailFilename);
videoService.save(video);
}
deleteMessage(message);
} catch (JsonProcessingException e) {
LOG.error("JSON exception handling notification: {}", message.getBody(), e);
} catch (IOException e) {
LOG.error("IOException handling notification: {}", message.getBody(), e);
}
}
}
|
/*
* 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 bbdd;
/**
*
* @author JD
*/
public class Originador {
// Referencia a la ficha.
private FichaSorteo ficha;
/**
* Devuelve la ficha.
* @return FichaSorteo.
*/
public FichaSorteo getFichaSorteo() {
return this.ficha;
}
/**
* Establece la ficha.
* @param ficha
*/
public void setFichaSorteo(FichaSorteo ficha) {
this.ficha = ficha;
}
/**
* Asigna un participante a la ficha.
* @param participante
*/
public void setParticipante(Participante participante) {
ficha = participante.getFichaSorteo();
}
/**
* Devuelve un participante creado a partir de la ficha actual.
* @return
*/
public Participante crearParticipante() {
return new Participante(ficha);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.